如何使用 HTTP 响应重定向用户
我有一个场景,用户单击“餐厅”链接(用于搜索特定地点的餐厅)。我必须检查位置是否已设置。如果未设置,我想将他重定向到允许他设置位置的页面,然后返回按设置位置过滤的搜索结果。我使用 response.sendRedirect(url)
将用户重定向到设置位置页面。但是,如何发送重定向回 URL(即设置位置后我想要发送给用户的 URL)?
我尝试了这个:
response.sendRedirect("/location/set.html?action=asklocation&redirectUrl="+
request.getRequestUri()+request.getQueryString());
但这不起作用,并且显示 404 错误;另外,浏览器中形成的 url 看起来不太好。
拜托,如果有人能解决这个问题...
I have a scenario where the user clicks on a 'restaurant' link (for searching restaurants in a particular locality). I have to check whether the location is set or not. If it is not set, I want to redirect him to a page that allows him to set the location, and, then, go back to search results filtered by the set location. I'm using response.sendRedirect(url)
to redirect the user to the setting location page. But, how can I send the redirect back URL (i.e., the URL where I want to send the user after the location is set)?
I tried this:
response.sendRedirect("/location/set.html?action=asklocation&redirectUrl="+
request.getRequestUri()+request.getQueryString());
but this isn't working and 404 error is shown; also, the url formed in the browser doesn't look good.
Please, if anyone could solve the problem ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来你至少缺少一个“?”在
request.getRequestUri()
和request.getQueryString()
之间。您还应该对参数进行 url 编码,可以使用 java.net.URLEncoder 进行编码。另外,在进行重定向时,您需要添加上下文路径:
request.getContextPath()
。就个人而言
,我宁愿通过在会话中存储
RequestDispatcher
并在设置位置后转发到它来解决问题。Looks like you're missing at least a "?" between
request.getRequestUri()
andrequest.getQueryString()
. You should url-encode the parameter as well, which you can usejava.net.URLEncoder
for.Also, when doing redirects you need to prepend the context path:
request.getContextPath()
.Something like
Personally, i'd rather solve the problem by storing a
RequestDispatcher
in the session and forwarding to it after the location has been set.我的第一个回应是删除 URL 上的
/
,对您的代码有这样的效果:如果这不起作用,请添加
request.getContextPath()
在 url 字符串的开头,如下所示:Javadoc 指出:
My first response will be to remove the
/
on your URL, something of this effect (to your code):If that doesn't work, add
request.getContextPath()
at the beginning of your url string, like so:The Javadoc states: