j2ee: Intro to JSP

Contents [0/20]

Overview of Today's Class [1/20]
Review/Logistics [2/20]
JavaServer Pages [3/20]
JSP history [4/20]
An example - The Servlet [5/20]
An example - The JSP [6/20]
Deploying JSPs [7/20]
JSP to Servlet Conversion [8/20]
Generated Code: Details [9/20]
JSP elements [10/20]
JSP/Servlet Differences [11/20]
Implicit Objects and their Scope [12/20]
JSP Directives [13/20]
JSP Actions [14/20]
JavaBeans [15/20]
JavaBean basics [16/20]
Using JavaBeans in JSPs [17/20]
Using JavaBeans in JSPs, manipulating data [18/20]
Webapp components [19/20]
Request Dispatching [20/20]

Overview of Today's Class [1/20]

Introduction

Review

Logistics

Introduce JSPs

On Thursday

Review/Logistics [2/20]

HTTP

HTML forms, GET vs. POST

Servlet API

Session tracking, Request/Response

The four scopes for objects in a webapp

WAR file format, creating a webapp, deploying to a container, development pratices

Servlet lifecycle

Thread safety, the servlet engine


Logistics

Your cd has JWSDP - this has JSTL 1.0. JBoss has Tomcat 5.0, this is enough for you to complete the assignment and develop most of what we will cover in the next two lectures. You may wish to download Tomcat 5.0 separately for convenience, since the Tomcat console is a bit more convenient than JBoss's (in my opinion). Tomcat, JSTL 1.1, and Struts 1.2.4 are all available from http://jakarta.apache.org/site/binindex.cgi . This link will direct you to a mirror for the downloads. More on these next lecture.

JavaServer Pages [3/20]

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.

JSP history [4/20]

JSPs were initially created just after the Servlet specification was released.

JSP 2.0 is considered a major upgrade, thus the whole number release.

Provides

An example - The Servlet [5/20]

The basic "Hello World" servlet


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 [6/20]

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

We'll break down the parts of a JSP soon

Deploying JSPs [7/20]

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 from there via their name. When you are using a JSP with a Servlet, you can do this. This is an excellent way to implement security on your pages. 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 [8/20]

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, for example, places the intermediate .java files in "tomcat_root"/work/Catalina/localhost/"webapp name".

JBoss places these in "jboss home"/server/default/work/jboss.web/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

Tomcat, by default, places the JSP code in the org.apache.jsp package.

Here is the code that is generated by Tomcat 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!

Generated Code: Details [9/20]

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.

JSP elements [10/20]

Now, we'll break down JSPs into some detail

Actions

Expressions

Scriptlets

Declarations

Comments

Escaping in JSPs

In scripting elements

In template text

In attributes

Next lecture, we'll look a bit at the Expression Language as well.

JSP/Servlet Differences [11/20]

Servlets

JSPs

Note that you can run all the JSP steps manually outside of the servlet container if you wish. This can be helpful when doing debugging of some JSP problems, but most likely you'll want to just use the Tomcat defaults which are set up for development.

Implicit Objects and their Scope [12/20]

Objects can be manipulated in JSP.

Objects exist in different scopes:

Remember, and object created inside a method would only have scope in that method as well. In Java, we also limit scope by using the { }

An object with a given scope is accessible to pages that are in the same scope as the page where the object was created. (more on this later)

Certain objects are created implicitly for each page by the container:

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

request

response

pageContext

session

application

out

config

page

exception

JSP Directives [13/20]

Directives are page dependent properties that are passed on to the JSP container

3 Types

Syntax:<%@ directive { attr="value" }* %>

Page

Syntax:<%@ page page_directive_attr_list %>

        page_directive_attr_list ::= { language="java"}
        { extends="className" } - JSP base class
        { import="importList" } 
            -java.lang.*, javax.servlet.*, javax.servlet.jsp.* and javax.servlet.http.*
        { session="true|false" } 
            - whether the page participates in a session
        { buffer="none| 8kb |sizekb" }
        { autoFlush="true|false" } 
            -illegal to make buffer = none when autoflush is false
        { isThreadSafe="true|false" }
        { info="info_text" }
        { errorPage="error_url" }
        { isErrorPage="true|false" }
        { contentType="ctinfo" } - "text/html"
        { pageEncoding="peinfo" } - "ISO-8859-1"
        

Taglib

Syntax:<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

Example:

        <%@ taglib uri="http://www.mycompany.com/supertags" prefix="myco" />
            ...
            <myco:TagName>
            ...
            </myco:TagName>
        

Include

Syntax:<%@ include file="relativeURLspec" %>

Example:

        <%@ include file="copyright.html" %>
        

Requests the inclusion of the file at translation time

JSP Actions [14/20]

Special tags that affect the out stream and use, modify, or create objects

Standard Actions

        <jsp:forward>
        <jsp:include>
        <jsp:param>
        <jsp:plugin>
        <jsp:params>
        <jsp:fallback>
        <jsp:useBean>
        <jsp:getProperty>
        <jsp:setProperty>
        
        <jsp:attribute>
        <jsp:element>
        <jsp:body>
        <jsp:invoke>
        <jsp:doBody>
        <jsp:text>
        <jsp:output>
        

The last 7 will be discussed once we learn about custom tag libraries

Custom actions: created with tag libraries

forward

Syntax : <jsp:forward page="relativeURLspec" />

include

Syntax:

        <jsp:include page="urlSpec" flush="true|false"/>
        

and

        <jsp:include page="urlSpec" flush="true|false">
            { <jsp:param .... /> }*
        </jsp:include>
        

Include a resource at request time, or a request with parameters

param

Used with include and foward and params elements

Syntax:

        <jsp:param name="name" value="value" />
        

plugin

replaces the tag with either an <object> or <embed> tag as needed by the user agent to display an applet or similar plugin properly. The params and fallback actions are used to provide for passing parameters to the plugin and providing feedback to the user if the plugin failed to load.

Example:

        <jsp:plugin type=applet code="Molecule.class" 
		codebase="/html" >
            <jsp:params>
		<jsp:param
			name="molecule"
			value="molecules/benzene.mol"/>
            </jsp:params>
            <jsp:fallback>
		<p> unable to start plugin </p>
            </jsp:fallback>
        </jsp:plugin>
        

JavaBeans [15/20]

Definition (from the spec):
"A Java Bean is a reusable software component that can be manipulated visually in a builder tool."

For this class, used to encapsulate some validation logic, as well as data for the presentation layer

Beans are just Java classes that follow various conventions and design patterns and can make use of the java.beans.* classes and interfaces

Learn more about JavaBeans at http://java.sun.com/products/javabeans/

Beans will vary in functionality, but can support:

JavaBean basics [16/20]

Need a zero argument constructor

All fields should be private with Accessors for public access to variables

        Type value;
        public Type getValue() { return value; }
        public void setValue(Type value) {
                this.value = value;
        }
        
        boolean value;
        public boolean isValue() { return value; }
        public void setValue(boolean value) {
                this.value = value;
        }
        
        Type[] value;
        public Type[] getValue() { return value; }
        public void setValue(Type value[]) {
                this.value = value;
        }
        public Type getValue(int i) { 
                return value[i]; 
        }
        public void setValue(int i, Type v) {
                value[i] = v;
        }
        

Property names begin with lower case

Property names are capitilized in the getter/setter methods

Acronyms are in all CAPS

Examples:

These conventions will have to be followed to use Beans in JSPs properly

Using JavaBeans in JSPs [17/20]

Declaring the Bean

<jsp:useBean> action

Locates or instantiates a bean with a specified name and scope.

Syntax:

        <jsp:useBean id="name" scope="page|request|session|application" typeSpec />
        
        typeSpec ::= class="className" |
        class="className" type="typeName" |
        type="typeName" class="className" |
        beanName="beanName" type="typeName" |
        type="typeName" beanName="beanName" |
        type="typeName" 
        

class must be assignable to type if both are declared

If the useBean has a body, it is of the form:

        <jsp:useBean id="name" scope="page|request|session|application" typeSpec >
        body
        </jsp:useBean>
        

The body will be invoked if the Bean is created.

Typically, the body will contain either scriptlets or jsp:setProperty tags that will modify the object created in the useBean tag

The contents of the body are not restricted.

Semantics:

  1. Attempt to locate a bean based on id and scope.
  2. Define a variable with the given id in the current scope of the specified type or class.
  3. If the bean is found in the specified scope
  4. If the bean is not found in the specified scope

Using JavaBeans in JSPs, manipulating data [18/20]

You can also manipulate JavaBeans using the get/setProperty actions

getProperty

Example:

        <jsp:getProperty name="user" property="name" />
        

Syntax:

        
        <jsp:getProperty name="name" property="propertyName" />
        

Value is obtained using toString() method

setProperty

Bean referred to in name must be defined in a useBean tag

Example:

Setting from request parameters

        
        <jsp:setProperty name="request" property="*" />
        <jsp:setProperty name="user" property="user" param="username" />
        

Setting from a value

        
        <jsp:setProperty name="results" property="row" value="<%= i+1 %>" />
        

Syntax:

        
        <jsp:setProperty name="beanName" prop_expr />
        prop_expr ::=
        property="*" |
        property="propertyName"|
        property="propertyName" param="parameterName"|
        property="propertyName" value="propertyValue"
        

propertyValue ::= string

Webapp components [19/20]

Primary components

The interaction between these three will allow the JSP and Servlet to communicate efficiently and in a maintainable way

More on JavaBeans later

Request Dispatching [20/20]

Often, when building a web application, you want to forward processing to another component. Or, you might want to include the processing of another component in the current response.

In order to do this using the Servlet API, we need to use a Request Dispatcher. This is retrieved from the ServletContext.

        public RequestDispatcher getRequestDispatcher(String path)
        

The RequestDispatcher is created based on the path used to obtain it (must begin with a "/"). This is a context relative resource.

        public void forward(ServletRequest request,
                    ServletResponse response)
        public void include(ServletRequest request,
                    ServletResponse response)            
        

Forwarding is usually used when one servlet (or JSP) processes the request, and the other processes the response. Include is a resource for doing server side includes (allowing other servlets to do part of the request handling or response generation

We need to understand Request Dispatching in order to integrate Servlets and JSPs properly.


Revised: 10/2/2004