I am building a Spring MVC based application where I want to redirect user’s to specific portion of the site based on their browser.
I am using a Filter applied to /site/home.jsp to read the User-Agent to determine the browser type.
HttpServletRequest req = (HttpServletRequest) request;
String uaString = req.getHeader("User-Agent");
Further I want to redirect users as below:
- Firefox: redirect to /site/firefox/home.jsp
- IE: redirect to /site/ie/home.jsp
- Unknown: redirect to /site/UnsupportedBrowser.jsp
My confusion is what is the correct way to redirect the user from my BrowserDetector filter?
1) Simply redirect the user?
resp.sendRedirect("/AppName/site/ie/home.jsp");
2) Use an HTTP Temp redirect?
resp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
resp.setHeader("Location", "/AppName/site/ie/home.jsp");
3) Server side redirect?
RequestDispatcher request_Dispatcher=request.getRequestDispatcher("/ie/home.jsp");
request_Dispatcher.forward(request,response);
4) Any other correct way?
Idea number 3 is probably a bad idea, as it will most likely result in you having to perform this check for every request, which is inefficient (only slightly, but small inefficiencies can mount up).
Idea’s number 1 & 2 are also not the best approach, because both will result in a Temporary redirect (307) response, wheras what you probably want is a permanent redirect (301). This is because the browser in question will always be the same – FF and IE never share there list of permanent moves, so even if both browsers are used by the same client machine this will not cause a problem. You should use 301 for reasons of, again, efficiency – if the browser always goes directly to the correct place, it is less work for your server to do.
To sum up, I think idea 2 is the closest, but you should use this instead:
Keep in mind that User-Agent strings can be spoofed and cannot be 100% relied upon.
This is my personal opinion, YMMV…