Monday, January 15, 2007

Client Redirection in Servlets

Being a huge supporter of projects like Struts, I'm used to using a forward from a servlet action to a jsp file. I guess I never really took the time to understand how struts would magically take my *.do url and forward it to another JSP page somewhere once all the fancy java was complete. As life usually goes, we end up eventually requiring a little dirt, as I did when I was trying to do a forward for a login servlet on a project that I was working on.

Initially I thought that the correct way to do this was to simply send the client a fancy 302 type http error such as what happens with the HttpServletResponse.sendRedirect(String) method. Where you send the client instructions on where to go next. The issue with this is that it creates some back and forth with the client and the client has to have access to the URL that you are redirecting it to. In alot of server configurations, this may not be possible, and sometimes you might lose control of the client on that server depending on load balancing config, etc.

I thought that the struts way of doing it was much more elegant, so I did a little research and found out about the RequestDispatcher object that basically does all the forwarding on the server side instead of going back to the client. This way, you have access to the original request object and you don't have to go back to the client to continue with the app.

Redirect Method:

httpServletResponse.sendRedirect("/anotherPage.htm");

RequestDispatch Method:

request.getRequestDispatcher("/anotherPage.htm").forward();

No comments: