【问题标题】:How to create/build REST URI using form parameters如何使用表单参数创建/构建 REST URI
【发布时间】:2013-06-19 06:58:16
【问题描述】:

好的,所以我创建了 restful webservice。现在如何为用户“abc”创建路径。
像这样的

http://stackoverflow.com/user/abc

以下是我通过 html 获取用户输入的表单

@POST
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void newUser(
            @FormParam("uname") String uname,
            @FormParam("password") String password,
            @Context HttpServletResponse servletResponse
    ) throws IOException {
        User u = new User(uname,password);
        User.userdata.put(uname,password);
    }

如果用户的 uname 为“abc”,如何从表单参数中生成类似这样的 URI

http://mysite/user/abc  

【问题讨论】:

    标签: rest jersey uri


    【解决方案1】:

    使用@Path@PathParam 注释:

    @Path("/user/{uname}")
    @PUT
    @Consumes("text/plain")
    public void putUser(@PathParam("uname") String uname, String password) {
      // ..
    }
    

    如果你 PUT/user/joe 的正文为 s3cret,那么 uname 将是 joepassword 将是 s3cret

    我使用PUT,因为您要使用的 URL 暗示用户名是由客户端设置的。 /user是所有用户的收藏资源。

    编辑: 由于此方法会通过创建新用户来更改服务器状态,因此必须使用PUTPOSTGET 不得更改服务器状态。

    【讨论】:

    • 所以我需要创建这个方法putUser,在 newUser 的末尾使用这个方法将用户重定向到:servletResponse.sendRedirect("http://mysite/user/"+uname); ... ??你不觉得应该是GET ??
    • @Accepts("text/plain")
    • 但是如果我需要将用户重定向到他的照片,我将如何以 html 形式使用它。http://mysite/user/{user}/pics ...嗯,这不使用休息的动态方法!
    • 收到错误 Apache Tomcat 错误 405 !!它要去http://mysite/user/abc,但给出这个错误!! .. 错误 405 方法不允许!!
    • 是的,只接受PUT。您询问了包含用户名的 URL 的外观。我已经回答过了。由于您的问题被标记为“球衣”和“休息”,因此我的回答描述了一种 RESTful 方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多