Sharing Data Between Servlets and JSP Pages
When you use servlets for request processing and JSP pages to render the user interface, you often need a way to let the different components access the same data. The model I recommend is having the servlet create beans and pass them to a JSP page for display.
As I described earlier, the
application scope is
just a JSP abstraction of
javax.servlet.ServletContext attributes.
Similarly, the request and session scopes are JSP abstractions for
attributes associated with
javax.servlet.ServletRequest and
javax.servlet.http.HttpSession, respectively. All
three classes provide setAttribute( )
,
getAttribute( ), and removeAttribute( ) methods. A
servlet uses the setAttribute( ) method to make a
bean available to a JSP
page. For instance, a servlet can create a bean, save it as a request
attribute, and then forward control to a JSP page like this:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String userName = request.getParameter("userName");
UserInfoBean userInfo = userReg.getUserInfo(userName);
request.setAttribute("userInfo", userInfo);
RequestDispatcher rd =
request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
}To the JSP page, the bean appears as a request scope variable. It can
therefore obtain the bean using the
<jsp:useBean> action and then access the
properties of the bean as usual, in this case using
<jsp:getProperty>
:
<h1>Welcome <jsp:useBean ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access