How to pass arguments to .jsp file when using javax.servlet.RequestDispatcher.include()?



I’m using the Model/View/Controller style of building web apps by routing an incoming HttpRequest to a Controller Servlet written in Java and then when the Servlet is finished, having it render back a View using a .jsp file. (This is very much the Rails style.)

Doing this requires a line like this at the end of the Controller Servlet:

getServletContext().getRequestDispatcher("/Bar.jsp").include(req, res);

The main problem is I want to pass arguments to Bar.jsp just as if it were a function that I am calling. If this is not possible, I end up putting lots of Java at the top of Bar.jsp to find out everything that Bar.jsp needs to render itself, which is rather ugly.

Other web frameworks provide a way to do this, so it seems that there must be a way to do it with Servlets. In particular I am working in Java Google App Engine.

Answer

you can use

request.setAttribute("attributeName",attributeValue);

and in other jsp file you can using methodgetAttribute() like this

request.getAttributeNames();
request.getAttribute("attributeName");


Source: stackoverflow