开发者

How to redirect users using HTTP response

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 ...


Looks like you're missing at least a "?" between request.getRequestUri() and request.getQueryString(). You should url-encode the parameter as well, which you can use java.net.URLEncoder for.

Also, when doing redirects you need to prepend the context path: request.getContextPath().

Something like

String secondRedirectUrl = request.getRequestUri()+"?"+request.getQueryString(); 
String encodedSecondRedirectUrl = URLEncoder.encode(secondRedirectUrl, serverUrlEncodingPreferablyUTF8);
String firstRedirectUrl = request.getContextPath()+"/location/set.html?action=asklocation&redirectUrl="+encodedSecondRedirectUrl;
response.sendRedirect(firstRedirectUrl);

Personally, i'd rather solve the problem by storing a RequestDispatcher in the session and forwarding to it after the location has been set.


My first response will be to remove the / on your URL, something of this effect (to your code):

response.sendRedirect("location/set.html?action=asklocation&redirectUrl="+
            request.getRequestUri()+request.getQueryString());

If that doesn't work, add request.getContextPath() at the beginning of your url string, like so:

response.sendRedirect(request.getContextPath() + "/location/set.html?action=asklocation&redirectUrl="+request.getRequestUri()+request.getQueryString());

The Javadoc states:

If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜