URL 在 Jersey 和 MongoDB 中页面重定向没有改变

URL not changing on page redirection in Jersey and MongoDB

我的场景是这样的: 我正在建立一个网站,并在其中 post 投放有关某个主题的广告。因此,在填写完广告表格后,请求将转到 REST 服务 class 为:

http://localhost:8080/cloudproject/postadvaction?title=tution&tag=tution&description=tution+%401000+%2F+month&category=TUTOR&location=indore

此处,广告的详细信息进入数据库 MongoDB。完成所有这些后,我将重定向到使用 Viewable model of jersey 的用户的个人资料页面,他可以在其中看到他 post 编辑的所有广告。它是这样完成的: return new Viewable("/profile.jsp"); 在此之后,响应被重定向到用户的个人资料页面。

但问题是,在将响应重定向到简单的 profile.jsp 时,地址栏中的 URL 并没有更改为 http://localhost:8080/profile.jsp, 相反,它与上面提到的保持一致。因此,当用户刷新页面时,同一广告 post 的请求会触发,整个过程将再次进行。由于数据库是 MongoDB,相同的广告在其中存储了两次,并且在具有 2 个相同广告的用户的个人资料页面上显示了相同的广告。

那么,如何在地址栏中没有 servlet 地址的情况下重定向到个人资料页面?

更新: 这个问题与 PRG 技术和重复表单提交 有关,而不仅仅是重定向。

Post/Redirect/Get

When a web form is submitted to a server through an HTTP POST request, a web user that attempts to refresh the server response in certain user agents can cause the contents of the original HTTP POST request to be resubmitted, possibly causing undesired results, such as a duplicate web purchase.

To avoid this problem, many web developers use the PRG pattern[1] — instead of returning a web page directly, the POST operation returns a redirection command. The HTTP 1.1 specification introduced the HTTP 303 ("See other") response code to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted. However most common commercial applications in use today (new and old alike) still continue to issue HTTP 302 ("Found") responses in these situations.

有了 Jersey,您可以使用

  • Response.seeOther(URI) - Create a new ResponseBuilder for a redirection. Used in the redirect-after-POST (aka POST/redirect/GET) pattern.

您只需要将您的方法签名更改为 return a Response 和 return 内置的 Response

return Response.seeOther(URI.create(...)).build();

还说明了 URI 参数

the redirection URI. If a relative URI is supplied it will be converted into an absolute URI by resolving it relative to the base URI of the application (see UriInfo.getBaseUri()).