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.
you can use
and in other jsp file you can using method
getAttribute()
like thisThis page says it well, also addressing the difference between parameters and attributes: http://www.xyzws.com/Servletfaq/what-is-the-difference-between-the-request-attribute-and-request-parameter/1
As it is said in one of the comments, you can't pass arguments to a different JSP (within the same request) as if it was a function.
The best thing you can do is to create one (or several) java beans that encapsulate the parameters with its attributes. Then, add those beans as request attributes before invoking the JSP. In the JSP you can reference the values held by those beans using EL expressions like
${myBean.myParameter}
without the need of additional java code in the JSP. This how common MVC frameworks for java do it.Notice that if just need to access the parameters that triggered that request/response processing, you can access them with expressions like
${param.myParam}
.EDIT
Sorry for not adding any link before. An EL expression is... an expression contained between the symbols
${
and}
(or#{
and}
- but take case as those are different kinds of EL expressions). El expressions allow the JSP developer to access data stored in the request, session or application context (other frameworks may add more contexts to that basic set) without the need of Java code. When writing JSP we must avoid using<% ... %>
and just use code that is intended to render output to the view rather than heavy data processing. Follow the link about best practices to obtain more background about it.There are, mainly, to big groups of EL expressions and I can't explain everything in a SO post but I recommend you to follow this link.
Adding variables, or objects (java beans) to the request or any other scope is fairly simple. To add a bean to the request you do:
request.setAttribute("myBeanName", myBean);
. Something similar with the other contexts. The Java EE tutorial will explain better that than me and after it you should be able to understand the JavaEE characteristics.