How to use PageContext


Web tier: servlets, JSP, Web frameworks: How to use PageContext

  1. How to use PageContext (1 messages)

    Hi all,
    It's not clear to me how PageContext can be used. If I understand well it has a very limited scope, that is if I move from one jsp to another what I store in the page context gets lost...........can it be used only for intermediate processing page data? (like Controllers)

    Threaded Messages (1)

  2. How to use PageContext[ Go to top ]

    The PageContext object is implicity defined as 'pageContext' in JSP and JSP tag libraries. Usually, pageContext is useful for storing and retrieving objects by string name (like a hashmap) within a single JSP, accessible within a JSP and any tag library it uses. For example, I have a database connection tag (only to find out one already existed on that creates a connection and stores it in pageContext making it accessible to my other tag libraries.

    For example:

    <mytag:connection id="con" dataSourceRef="mydsn" />

    In my tag library code, I store the connection in pageContext mapped to the id string:

    public void setId(String id) { = id;

    public void setDataSourceRef(String dataSourceRef) {
        this.dataSourceRef = dataSourceRef;

    public int doStartTag() throws JspException {
        try {
            // getting connection from data source
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(this.dataSourceRef);
            Connection con = ds.getConnection();
            // storing connection in pageContext
            pageContext.setAttribute(, con);

        } catch (Exception ex) {
            // err sorry lazy right now =p

    Now I can access the connection in the JSP:

      Connection con = (Connection)pageContext.getAttribute("con");

    Or in another taglib in the same JSP:

    <mytag:closeConnection id="con" />

    There are also ways to define the scope of the pageContext object (i.e. request, session, application), but I usually use the implicit HttpServletRequest, HttpSession, and ServletContext objects (request, session, application =p).
    I suggest you read the servlet API doc for more information.

    Hope this helps!