SE452: Lecture 4 (Sessions/Intro to JSP)

Contents [0/16]

Overview of Today's Class [1/16]
Maintaining State [2/16]
Cookies [3/16]
Cookie API [4/16]
Sessions [5/16]
The Session Tracking API [6/16]
The Session API [7/16]
JavaServer Pages [8/16]
An example - The Servlet [9/16]
An example - The JSP [10/16]
Deploying JSPs [11/16]
JSP to Servlet Conversion [12/16]
JSP elements [13/16]
Predefined variables [14/16]
Generated Code: Details [15/16]
Homework [16/16]

Overview of Today's Class [1/16]

Maintaining State

Introduce JSPs

Maintaining State [2/16]

Maintaining State

How can you maintain state?

State must either be completely part of the request (hidden or form fields or cookies), or maintained on the server

Cookies [3/16]

Defined in RFC 2109

A cookie is basically a small piece of information stored by a web browser on the local client.

Browsers are expected to only support 20 cookies per Web server, 300 total, and can be limited to 4kb each

Cookies are returned to the server as HTTP request headers

Cookies are used on the web for a number of purposes:

If used properly, not a security risk

Problems with Cookies:

As a developer, you cannot depend on them completely

Cookie API [4/16]

public Cookie(java.lang.String name, java.lang.String value)
        

Creates a Cookie

public void setMaxAge(int expiry)
         

Set to age in seconds when Cookie expires, 0 deletes it

negative value deletes it when browser exits

getters/setters for Name, Value, Path, Domain, etc.

Cookies are returned by the browser to the server if the Domain and Path match the server

Getting Cookies from the request

public Cookie[] getCookies()

Adding Cookies to the response

public void addCookie(Cookie cookie)

Sessions [5/16]

In web applications, the concept of a session is used to put consecutive requests and responses in context

Implicit in a session are the following concepts:

The concept of session tracking allows stateful information to be stored on the server and associated with a specific client

Since HTTP is stateless, the identification of a specific session is needed in each request

This can be accomplished using:

The Session Tracking API [6/16]

The Java Servlets API includes support for session tracking

The interface HttpSession encapsulates the session information

The session is stored on the server

Tracking is performed using Cookies or URL-rewriting and is transparent to the servlet

The scope of an HTTPSession is the entire webapp

The session persists until it expires on the server, or it is expired in code

Programming issues:

The Session API [7/16]

In the HttpServletRequest class:

HttpSession getSession()
HttpSession getSession( boolean create)
        

Returns the current HttpSession associated with this request, or if there is no current session and create is true, returns a new session.

Default: create is true

String getRequestedSessionId()
        

Returns the session ID.


In the HttpServletResponse class:

String encodeURL( String url)
        

Encodes the specified URL by including the session ID in it, or If encoding is not needed, returns the URL unchanged.


The HttpSession class:

void setAttribute( String name,Object value)
        

Binds an object to the specified name in this session.

Object getAttribute( String name)
        
void removeAttribute( String name)
        
String getId()
        

Returns the session ID.

Enumeration getAttributeNames()
        

Returns an Enumeration of string objects containing the names of all the objects bound to this session.

long getCreationTime()
        

Returns the time when this session was created in ms since the epoch

long getLastAccessedTime()
        

Returns the last time the client sent a request associated with this session.

int getMaxInactiveInterval()
        
void setMaxInactiveInterval( int interval)
        
void invalidate()
        

Invalidates this session and unbinds any objects in this session.

boolean isNew()
        

JavaServer Pages [8/16]

Why JSPs?

Advantages of using JSPs

Disadvantages of using JSPs

However, if done correctly, all the problems with JSPs can be taken care of, and they are preferred to using servlets for presentation.

An example - The Servlet [9/16]

Remember Lecture 2?


import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet2 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello Servlet</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("The time is <i>" + new Date() + "</i>" );
        out.println("</body>");
        out.println("</html>");
        out.close();
    } 
}
        

An example - The JSP [10/16]

<html>
    <head>
      <title>Hello JSP</title>
    </head>
    <body>
      <h1>Hello World</h1>
      The time is <%= new java.util.Date() %>
    </body>
</html>

Deploying JSPs [11/16]

Basically, treat a JSP like an HTML file. You can place it anywhere inside the document root of your webapp.

Do not copy your JSPs into the WEB-INF directory if you want to access them directly, since they cannot be accessed there via their name. When you are using a JSP with a Servlet, you can do this. More on this later

Example:

Copy Hello2.jsp to "tomcat home"/webapps/ROOT and Invoke http://localhost:8080/Hello2.jsp

When using a war file, just include the JSP in the directory where you want to access it, make the war file, and deploy. You should be able to see the changes when the servlet engine reloads the war file

JSP to Servlet Conversion [12/16]

So how does a JSP actually work?

It is turned into a special kind of servlet. The code is generated by a JSP compiler, which generates Java code out of it. This is the java code that will be run while you test your JSPs. Sometimes, you'll need to take a look a the code to understand what his happening

Tomcat places the intermediate .java files in "tomcat_root"/work/Catalina/localhost/"webapp name".

Tomcat retains the .java source by default. This will vary by servlet container implementation, some require you to turn a debug option on to save source

Here is the code for the example above:

import javax.servlet.jsp.*;

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static java.util.Vector _jspx_dependants;

  public java.util.List getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;


    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("<html>\n    ");
      out.write("<head>\n      ");
      out.write("<title>Hello JSP");
      out.write("</title>\n    ");
      out.write("</head>\n    ");
      out.write("<body>\n      ");
      out.write("<h1>Hello World");
      out.write("</h1>\n      The time is ");
      out.write(String.valueOf( new java.util.Date() ));
      out.write("\n    ");
      out.write("</body>\n");
      out.write("</html>\n");
    } catch (Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (pageContext != null) pageContext.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
}
        

Based on what you already know about Servlets, what do you think of the time writing this as a JSP has saved you? We'll look at some more detail on other convenient things done for you by the JSP compiler later. If you study this code above, you can probably figure most of them out without the specification!

JSP elements [13/16]

Expressions

Scriptlets

Declarations

Comments

Escaping in JSPs

In scripting elements

In template text

In attributes

Predefined variables [14/16]

In JSPs, a number of variables are created for you.

All of these are predefined and can be used inside your JSP.

Generated Code: Details [15/16]

The generated code is in the format:


        
        import package.name;

        class _jsp XXX extends SuperClass {
                <Declaration Section>
                public void _jspService(...) {
                        <Implicit Objects Section>
                        <Main Section>
                }
        }
        
        

A declaration: Verbatim copy to the <Declaration Section>

Template data: Statement fragment in the <Main Section>

A scriptlet: Verbatim copy to the <Main Section>

An expression: Statement in the <Main Section>

An action: Statement fragment in the <Main Section> to declare and create objects, and invoke the action handler.

Homework [16/16]

Goal: To gain familiarity with the Session API and to learn how to write some simple JSPs

  1. Part A: Create a Servlet that creates a session. You could have the Servlet only create a session when a successful login is achieved, or create a session by default with any request. Store some data in the session, and show that the data is persisted across requests by redisplaying the data in a subsequent request. This can be done by either using two different HTML forms, or providing links to the user in the Servlet response.
  2. Part B: Create a JSP that displays dynamic data when invoked. This means that the content should depend on something that is available in the request. For example, depending on what one of the request headers are from the client, you could display different data. Or, you could create a JSP that submits a form to itself and displays a response based on the form submission.

Supply the application as a deployable war file. Test deploying it before submitting it to make sure you have the format right. Place the source files for the servlet in a src directory in the war file.

Grading Breakdown:

ItemPoints
Part A - configuration (web.xml)10
Part A - Proper use of session APIs30
Part A - Coding style, javadoc10
Part B - concept and implementation30
Part B - Coding style10
Proper Submission10
Total:100


Revised: 10/5/2003