Restlet路径参数不起作用

Déb*_*ora 8 java jax-rs restlet java-ee

以下是我的路线

public Restlet createInboundRoot(){
 Router router = new Router(getContext());
router.attach("account/profile",UserProfile.class);
Run Code Online (Sandbox Code Playgroud)

以下是Resource类UserProfile.java

@post
@path("add")
public void addUser(User user){

@post
@path("modify")
public void modifyUser(User user){

@post
public void test(){//only this is called
Run Code Online (Sandbox Code Playgroud)

我想调用一个资源类,并为资源类做几个相同的函数.这意味着,我的上面的资源类处理与UserProfiles相关的函数,例如add,modify.URL为:
account/profile/add =>添加用户
帐户/ profile/modify =>以修改用户

无论如何,在我的实现之上不起作用,因为只能通过account/profile /调用test()方法

我也尝试过Pathparams.但它也没有用.对于路径参数:

router.attach("account/profile/{action}",UserProfile.class);
Run Code Online (Sandbox Code Playgroud)

已添加并在资源类中,

@post
@path("{action}")
public void addUser(@pathparam("action") String action, User user){ 
Run Code Online (Sandbox Code Playgroud)

有谁告诉我我的问题在哪里.

Thi*_*ier 0

附加服务器资源的方式UserProfile有点奇怪。我认为您混合了 Restlet 的本机路由和 JAXRS 扩展的路由。

我对您的用例进行了一些测试,并且能够实现您期望的行为。我使用的是Restlet 2.3.5版本。

这是我所做的:

  • 由于您想使用 JAXRS,因此需要创建一个JaxRsApplication并将其附加到组件上:

    Component component = new Component();
    component.getServers().add(Protocol.HTTP, 8182);
    
        // JAXRS application
        JaxRsApplication application
           = new JaxRsApplication(component.getContext());
        application.add(new MyApplication());
    
        // Attachment
        component.getDefaultHost().attachDefault(application);
    
        // Start
        component.start();
    
    Run Code Online (Sandbox Code Playgroud)
  • 该应用程序仅列出您要使用的服务器资源,但不定义路由和路径:

    import javax.ws.rs.core.Application;
    
    public class MyApplication extends Application {
        public Set<Class<?>> getClasses() {
            Set<Class<?>> rrcs = new HashSet<Class<?>>();
            rrcs.add(AccountProfileServerResource.class);
            return rrcs;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 服务器资源定义处理方法和关联的路由:

    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    
    @Path("account/profile/")
    public class AccountProfileServerResource {
        @POST
        @Path("add")
        public User addUser(User user) {
            System.out.println(">> addUser");
            return user;
        }
    
        @POST
        @Path("modify")
        public User modifyUser(User user) {
            System.out.println(">> modifyUser");
            return user;
        }
    
        @POST
        public void test() {
            System.out.println(">> test");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 当我调用不同的路径时,会调用正确的方法:

    • http://localhost:8182/account/profile/modify: 该modifyUser方法被调用
    • http://localhost:8182/account/profile/add: 该addUser方法被调用
    • http://localhost:8182/account/profile/: 该test方法被调用

希望它对你有帮助,蒂埃里