Java EE. JSP Page Context

StartHere.jsp

                <%
                    //page context default scope is page.  it will not work on anything
                    //but the page.  The pageContext does allow access at other scopes, however
                    //set a page context attribute
                    pageContext.setAttribute("LostCode", "74185296");
                    //set a page context application attribute:
                    pageContext.setAttribute("SecretCode", "12345678", pageContext.APPLICATION_SCOPE);
                    //set a new session attribute
                    pageContext.setAttribute("SessionCode", "258369147", pageContext.SESSION_SCOPE);   
                   
                    //set a request attribute
                    request.setAttribute("AnotherCode", "55544433");
                   
                    //set a destination with a QS Param
                    String destination = "SecondPage.jsp?key=98765432";
                   
                    //try with redirect
                    response.sendRedirect(destination);
                           
                    //try with dispatcher:
                    //RequestDispatcher rd = request.getRequestDispatcher(destination);
                    //rd.forward(request,response);
                   
                    //use page context
                    //pageContext.forward works like RequestDispatcher:
                    //pageContext.forward(destination);
                %>

SecondPage.jsp

                <%
                    //application/servlet context from page context
                    String dbUIDFail = (pageContext.getAttribute("dbuserid", pageContext.APPLICATION_SCOPE) == null ? "bad" :
                                        (String)pageContext.getAttribute("dbuserid", pageContext.APPLICATION_SCOPE));
                   
                    String dbUIDSuccess = (application.getInitParameter("dbuserid") == null ? "bad" :
                                            application.getInitParameter("dbuserid"));
               
                    //session object from page context
                    String uid = (pageContext.getAttribute("uid", pageContext.SESSION_SCOPE) == null ? "bad" :
                                    (String)pageContext.getAttribute("uid", pageContext.SESSION_SCOPE));
               
                    String sessionCode = (pageContext.getAttribute("SessionCode", pageContext.SESSION_SCOPE) == null ? "bad" :
                                            (String)pageContext.getAttribute("SessionCode", pageContext.SESSION_SCOPE));
                   
                    //try to get secret code from page context
                    String scode = (pageContext.getAttribute("SecretCode", pageContext.APPLICATION_SCOPE) == null ? "bad" :
                                    (String)pageContext.getAttribute("SecretCode", pageContext.APPLICATION_SCOPE));
                           
                    //request param from page context
                    String acode = (pageContext.getAttribute("AnotherCode", pageContext.REQUEST_SCOPE) == null ? "bad" :
                                    (String)pageContext.getAttribute("AnotherCode", pageContext.REQUEST_SCOPE));
                           
                    //query string param from page context
                    String pcode = (pageContext.getAttribute("key", pageContext.REQUEST_SCOPE) == null ? "bad" :
                                    (String)pageContext.getAttribute("key", pageContext.REQUEST_SCOPE));
               
                    String pcode2 = request.getParameter("key");
                           
                    //try to get previously set page attribute
                    String lcode = (pageContext.getAttribute("LostCode") == null ? "bad" :
                                    (String)pageContext.getAttribute("LostCode"));
                           
                %>

Java EE. Declaration example

In JSP file. Declared values will be held even if user updates(F5) page

                <%!
                    Calendar gc = GregorianCalendar.getInstance();
                    String hour = String.format("%s", gc.get(Calendar.HOUR));
                    String min = String.format("%s", gc.get(Calendar.MINUTE));
                    String sec = String.format("%s", gc.get(Calendar.SECOND));
                    Random r = new Random(gc.getTimeInMillis());
                %>

Java EE. Simulate exeption

SimulateExeption.java(Servlet)

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int i = 10;
        int j = 0;
        int k = i/j;
        PrintWriter out = response.getWriter();
        out.println("The result is " + k);
    }

alwaysThrowsExeption.jsp
!pay attention to

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    errorPage="errorHandler.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bad Page</title>
</head>
<body>
    <jsp:forward page="/simulateException.do" />
</body>
</html>

ErrorHandler.jsp (shows error)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Our bad!</title>
</head>
<body>
    <%@ include file="header.jsp"%>
    <table style="width: 100%;">
        <tr>
            <td style="width: 25%; height: 80%;" valign="top"><%@ include
                    file="navbar.jsp"%></td>
            <td style="width: 75%; height: 80%;">
                <h1>An Error has occurred!</h1>
                <br> ${pageContext.exception.message}
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" />
</body>
</html>

Java EE. Global 404 error page

web.xml

  <jsp-config>
    <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
  </jsp-config>
  <error-page>
    <error-code>404</error-code>
    <location>/errorHandler.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/actionNotAllowed.jsp</location>
  </error-page>

Java EE. Expression language in example

By default in JSP, Expression Language is turned off:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to the World Manager</title>
</head>
<body>
    <%@ include file="header.jsp" %>
    <table style="width:100%;">
        <tr>
            <td style="width:25%;height:80%;" valign="top">
                <%@ include file="navbar.jsp" %>
            </td>
            <td style="width:75%;height:80%;">
                <h1>We don't know EL yet!</h1>
                <p>But if we did, this page would render it
                   here<br>
                   <br>
                   Hello <strong>${initParam.dbuserid}</strong>
                </p>
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" />
</body>
</html>

You can turn it on by isELIgnored=”true”

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    isELIgnored="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to the World Manager</title>
</head>
<body>
    <%@ include file="header.jsp" %>
    <table style="width:100%;">
        <tr>
            <td style="width:25%;height:80%;" valign="top">
                <%@ include file="navbar.jsp" %>
            </td>
            <td style="width:75%;height:80%;">
                <h1>We don't know EL yet!</h1>
                <p>But if we did, this page would render it
                   here<br>
                   <br>
                   Hello <strong>${initParam.dbuserid}</strong>
                </p>
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" />
</body>
</html>

Java EE. Error handling

errorHandler.jsp

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    errorPage="errorHandler.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bad Page</title>
</head>
<body>
    <%
        if (request.getParameter("notSetYet") == null)
        {
            throw new IllegalArgumentException("Not Set Yet is "
                + "Not Yet Set As Expected!");
        }
    %>
</body>
</html>

alwaysThrowsException.jsp

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
    content="text/html; charset=ISO-8859-1">
<title>Our bad!</title>
</head>
<body>
    <%@ include file="header.jsp" %>
    <table style="width:100%;">
        <tr>
            <td style="width:25%;height:80%;" valign="top">
                <%@ include file="navbar.jsp" %>
            </td>
            <td style="width:75%;height:80%;">
                <h1>An Error has occurred!</h1><br>
                <%
                    out.println(exception.getMessage());
                %>
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" />
</body>
</html>

Java EE. Scriptlet example

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="com.worldmanager.dbhelpers.*
            , com.worldmanager.dbmodels.*
            , java.sql.*"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to the World Manager</title>
</head>
<body>
    <%@ include file="header.jsp"%>
    <table style="width: 100%;">
        <tr>
            <td style="width: 25%; height: 80%;" valign="top"><%@ include
                    file="navbar.jsp"%></td>
            <td style="width: 75%; height: 80%;">
                <%-- We don't know how to use
                     expressions yet so we'
ll do it all here --%> <%
    //get the DBManager from context
    //DBManager dbm = (DBManager)getServletContext().getAttribute("WorldDBManager");
    //application --> getServletContext()
    DBManager dbm = (DBManager) application
            .getAttribute("WorldDBManager");

    //generate the output in a StringBuilder

    //java.lang not needed at import.
    StringBuilder sb = new StringBuilder("<html><body>");

    try {
        //connect to the db and open the connection
        if (!dbm.isConnected()) {
            if (!dbm.openConnection()) {
                //massive failure, log it
                sb.append("Could not connect to the database...");
            }
        }

        //ID NAME CountryCode District Population
        //get the cities into a table:
        sb.append("<table border=1>"
                + "<tr><td>ID</td><td>NAME</td><td>COUNTRY_CODE</td>"
                + "<td>DISTRICT</td><td>POPULATION</td></tr>");

        //TRUE MVC ERROR: the query should NOT be on the JSP page...
        String query = DBWorldQueries.getCitiesByDistrictByPopulation();
        //TRUE MVC ERROR: neither should creation of the result set...
        ResultSet rs = dbm.ExecuteResultSet(query);
        while (rs.next()) {
            int id = rs.getInt("ID");
            String name = rs.getString("NAME");
            String ctry = rs.getString("CountryCode");
            String dist = rs.getString("District");
            int pop = rs.getInt("Population");

            sb.append("<tr><td>" + id + "</td>" + "<td>" + name
                    + "</td>" + "<td>" + ctry + "</td>" + "<td>" + dist
                    + "</td>" + "<td>" + pop + "</td></tr>");
        }
        sb.append("</table>");
    } catch (Exception e) {
        sb.append("<h1>ERROR: " + e.getMessage() + "</h1>");
    }
    sb.append("</body></html>");

    //don't need to get the writer anymore...
    //response.setContentType("text/html");
    //PrintWriter out = response.getWriter();
    out.println(sb);
 %>
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" />
</body>
</html>

Java EE. JSP basics

JSPLife

Scriptlet = code
<% some code %>

Declarations
<%! …. %>

Expressions
<%= …. %>

EL – Expression Language
${ …. }

Tag libraries
<%@ taglibname prefix=”variable” uri:” …. ” %>
….

JSP actions:

jsp:include
jsp:forward
jsp:useBean
jsp:getProperty
jsp:setProperty

JAVA API Implicit Object
HttpServletRequest request
HttpServletReponse response
HttpSession session
ServletContext application
ServletConfig config
PrintWriter out
Throwable [Exception] Exception
PageContext pageContext
this [Object] page

Example of usage in real life:
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to world manager</title>
</head>
<body>
    <!-- include using a directive -->
    <%@ include file="header.jsp"%>
    <table style="width: 100%;">
        <tr>
            <td style="width: 75%; height: 80%;" valign="top"><%@ include
                    file="navbar.jsp"%></td>
            <td style="width: 75%; height: 80%;">
                <h1>Content will be here</h1>
            </td>
        </tr>
    </table>
    <jsp:include page="footer.jsp" /></body>
</html>

header.jsp

<h1>This site is awesome</h1>
<%-- replace with banner image --%>

navbar.jsp

<a href="index.jsp">HOME</a><br>
<a href="listCities.jsp">CITIES</a><br>
<a href="listCountries.jsp">COUNTRIES</a><br>

footer.jsp

Copyright &copy;2014
<a href="http://www.joerichard.net">My Blog</a>

Java EE. Session listeners

One of the examples of session listener use can be user tracking. This function will be counting how many users authorized now:
ActiveUserTracking.java

package company.citymanagerweb.sessionlisteners;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class ActiveUserTracking
 *
 */

@WebListener
public class ActiveUserTracking implements HttpSessionListener {
    private static int activeUsers;

    /**
     * Default constructor.
     */

    public ActiveUserTracking() {

    }

    /**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */

    public void sessionCreated(HttpSessionEvent hse) {
        System.out.println("A new Session was created");
        activeUsers++;
    }

    /**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */

    public void sessionDestroyed(HttpSessionEvent hse) {
        System.out.println("An existing Session was destroyed");
        activeUsers--;
    }

    public static int getActiveUserCount() {
        return activeUsers;
    }
}

This class helps to log what is happening behind the scenes:
SessionTrackingAndLogging.java

package company.citymanagerweb.sessionlisteners;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class SessionTrackingAndLogging
 *
 */

@WebListener
public class SessionTrackingAndLogging implements HttpSessionAttributeListener {

    /**
     * Default constructor.
     */

    public SessionTrackingAndLogging() {
        // instantiate log
    }

    /*
     * NOTE: as these are listeners, and we are simulating logging, the
     * attribute value will require a valid 'toString()' on the objects as we
     * aren't going to know what the object actually is (we could instanceof and
     * assign each to be more specific if we wanted).
     */

    /**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */

    public void attributeRemoved(HttpSessionBindingEvent hsbe) {
        // attribute removed from session
        System.out.printf("Attribute Removed from session: %s\t%s\n",
                hsbe.getName(), hsbe.getValue());
    }

    /**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */

    public void attributeAdded(HttpSessionBindingEvent hsbe) {
        // attribute added to session
        System.out.printf("Attribute Added to session: %s\t%s\n",
                hsbe.getName(), hsbe.getValue());
    }

    /**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */

    public void attributeReplaced(HttpSessionBindingEvent hsbe) {
        // attribute updated in session
        System.out.printf("Attribute Replaced in session: %s\t%s\n",
                hsbe.getName(), hsbe.getValue());
    }

}

This servlet shows how many users authorized currently:

package company.citymanagerweb.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import company.citymanagerweb.sessionlisteners.ActiveUserTracking;

/**
 * Servlet implementation class ShowActiveSessionCount
 */

@WebServlet("/showactivesessioncount.do")
public class ShowActiveSessionCount extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */

    public ShowActiveSessionCount() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //all we'll do here is just print out the active user count
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        int activeUsers = ActiveUserTracking.getActiveUserCount();
        out.println("<h1>Active Users: " + activeUsers + "</h1>");
        out.println("</body></html>");
    }
}