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 ...

Get Java Server Pages now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.