views:

29

answers:

1

Hi guys,

I am having a weird problem here, and I am really stuck, need to get this work badly.

so i have a page say index.jsp with a link say "a href=servlet?action=viewMenu". when I click on this link it will go to doGet() on my servlet and here is the code in my servlet.

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                 String action = request.getParameter("action");
                   if(action.equals("viewMenu")){
                        address = "/viewAdminMenu.jsp";
                   }
                RequestDispatcher dispatcher = request.getRequestDispatcher(address);
                dispatcher.forward(request,response);
     }

So the above code works fine but after request forwarding, my browser shows the url as

localhost/project/servlet?action=viewMenu. (with http:// in the beginning)

I don't want the above url as I could not set the basic authentication with tomcat, what I need is

localhost/project/viewAdminMenu.jsp (with http:// in the beginning)

I have tried to find information about this but haven't been able to figure it out.

Any help will be very much appreciated.

+2  A: 

If you want the browser to go to a different URL, you'll need to tell it to redirect, rather than doing a forward in the server. See the sendRedirect() method of HttpServletResponse.

Forward

  • a forward is performed internally by the servlet
  • the browser is completely unaware that it has taken place, so its original URL remains intact
  • any browser reload of the resulting page will simple repeat the original request, with the original URL

Redirect

  • a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
  • a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
  • redirect is marginally slower than a forward, since it requires two browser requests, not one
  • objects placed in the original request scope are not available to the second request

(From Java Practices.)

martin clayton
I see, thanks so much, I think I could sort out the problem from here. Thanks
eds
@eds if the answer worked for you, mark it as accepted
Bozho
Btw, I have one more question, sendRedirect does not seems to work with request.setAttribute. is there any work around for this?
eds
@eds - you might consider asking that as a separate question (I think it's a good one, and I can't see an obvious duplicate). Two options, which may well not be suitable in your case, might be 1) use HttpSession - then attributes can persist between calls. 2) send the attributes as part of the redirect URL, and modify your servlets to read them.
martin clayton