What is the best way to pass objects between servlets and JSP - when do I use getAttribute and when do I use getParameter?

Serge Knystautas

request.getAttribute() is a server-side only mechanism of passing parameters between servlets and JSPs. request.getParameter() is normally a browser-side mechanism of passing parameters between servlets and JSPs. You can also use request.getParameter to pass parameters on a dynamic include within a servlet or JSP.

To pass parameters using request.getParameter(), construct a new URL that points to the target servlet or JSP and append a querystring with your parameters and embed this in an a href tag., e.g., http://myserver.com/target.jsp?param1=valu1&param2=value2. Then when the browser clicks the link, it invokes target.jsp, and target.jsp can retrieve the parameter values using request.getParameter("name1") and request.getParameter("name2"). You can also do a dynamic servlet include on another servlet or JSP, and pass a query string. This allows you to pass parameters server-side using request.getParameter(). Note that you can only pass Strings using request.getParameter().

To pass parameters using request.getAttribute(), you call request.setAttribute() with the appropriate parameter name and object, and then include or forward the request and response (using the RequestDispatcher or PageContext's convenience methods) to another servlet or JSP. You can pass objects using this method.

The best method really depends on how your architecture. Most parameters get passed via form-like parameters (the querystring) as the browser makes different requests. If you are using multiple pages to generate different pieces of a page and using includes and forward within the server, you should probably use request.getAttribute(). You can also use the HttpSession to pass objects between servlets and JSPs as the user moves around your site.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.