Restlet路径参数不起作用

时间:2016-01-13 12:49:33

标签: java java-ee jax-rs restlet

以下是我的路线

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

以下是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

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

无论如何,上面我的实现不起作用,因为只能通过account / profile /

调用test()方法

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

router.attach("account/profile/{action}",UserProfile.class);

已添加到资源类

@post
@path("{action}")
public void addUser(@pathparam("action") String action, User user){ 

有人告诉我我的问题在哪里。

1 个答案:

答案 0 :(得分: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();
    
  • 应用程序只列出您要使用的服务器资源,但不定义路由和路径:

    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;
        }
    }
    
  • 服务器资源定义处理方法和相关路由:

    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");
        }
    }
    
  • 当我调用不同的路径时,会调用正确的方法:

    • http://localhost:8182/account/profile/modifymodifyUser方法称为
    • http://localhost:8182/account/profile/addaddUser方法称为
    • http://localhost:8182/account/profile/test方法称为

希望它可以帮到你, 亨利