Search code examples
javastruts

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


Solution

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