How to redirect users using an HTTP response

I have a scenario where a user clicks on the restaurant link (to search for restaurants in a specific place). I have to check if the location is set or not. If it is not installed, I want to redirect it to a page that allows it to set the location, and then return to the search results filtered by the given location. I use response.sendRedirect(url)to redirect the user to the location page. But how can I send the redirect URL (i.e. the URL where I want to send the user after it's installed)?

I tried this:

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

but this does not work and error 404 is displayed; In addition, the URL generated in the browser does not look very good.

Please, if someone can solve the problem ...

+3
source share
2 answers

It looks like you are missing at least "?" between request.getRequestUri()and request.getQueryString(). You should also encode the URL that you can use java.net.URLEncoderfor.

In addition, when forwarding you need to add the path to the context: request.getContextPath().

Sort of

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 would rather solve the problem by storing RequestDispatcherin the session and redirecting it after the location was established.

+7
source

My first answer would be to delete /on your url, something like this (for your code):

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

, request.getContextPath() url, :

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

Javadoc :

'/' URI. '/' .

+1

Source: https://habr.com/ru/post/1779594/


All Articles