Transcript Document
Servlet/JSP
CSC 667/867, Spring 2006
Dr. Ilmi Yoon
What are Java Servlets
• An alternate form of server-side computation
that uses Java
• The Web server is extended to support an
API, and then Java programs use the API to
create dynamic web pages
• Using Java servlets provides a platformindependent replacement for CGI scripts.
• Servlets can be embedded in many different
servers because the servlet API, which you
use to write servlets, assumes nothing about
the server's environment or protocol.
The Advantages of Servlets Over
Traditional CGI
• Efficiency
– CGI invoking
• Overhead of starting a new process can dominate the
execution time.
• For N simultaneous request, the same code is loaded
into memory N times.
• When terminated, lose cache computation, DB
connection & ..
– Servlet
• JVM stays running and handles each request using
Java thread.
• Only a single copy is loaded into memory
• Straightforward to store data between requests
The Advantages of Servlets Over
Traditional CGI
• Convinient
– CGI invoking
• Easy to install and setup
– Servlet
• Provides an extensive infrastructure for
automatically parsing and decoding HTML form data,
reading and setting HTTP headers, handling cookies,
tracking sessions and other utilities.
• No need to learn new programming languages if you
are familiar with Java already.
• Easy to implement DB connection pooling & resourcesharing optimization.
Servlet Life Cycle
• Initialization
– the servlet engine loads the servlet’s *.class
file in the JVM memory space and initializes
any objects
• Execution
– when a servlet request is made,
• a ServletRequest object is sent with all information
about the request
• a ServletResponse object is used to return the
response
• Destruction
– the servlet cleans up allocated resources and
shuts down
Simple Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");out.println("</html>");}}
Client Interaction
• When a servlet accepts a call from a
client, it receives two objects:
– A ServletRequest, which encapsulates
the communication from the client to the
server.
– A ServletResponse, which encapsulates
the communication from the servlet back
to the client.
• ServletRequest and ServletResponse
are interfaces defined by the
javax.servlet package.
The ServletRequest
Interface
• The ServletRequest interface allows the servlet
access to:
– Information such as the names of the parameters passed in
by the client, the protocol (scheme) being used by the client,
and the names of the remote host that made the request and
the server that received it.
– The input stream, ServletInputStream. Servlets use the
input stream to get data from clients that use application
protocols such as the HTTP POST and PUT methods.
• Interfaces that extend ServletRequest interface
allow the servlet to retrieve more protocol-specific
data. For example, the HttpServletRequest interface
contains methods for accessing HTTP-specific header
information.
The ServletResponse Interface
• The ServletResponse interface gives the
servlet methods for replying to the client.
It:
– allows the servlet to set the content length and
MIME type of the reply.
– provides an output stream,
ServletOutputStream, and a Writer through
which the servlet can send the reply data.
• Interfaces that extend the
ServletResponse interface give the servlet
more protocol-specific capabilities.
– For example, the HttpServletResponse
interface contains methods that allow the
servlet to manipulate HTTP-specific header
Request Information Example Source Code-1/2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestInfo extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request Information Example
</title>");
out.println("</head>");out.println("<body>");
Request Information Example Source
Code-2/2
out.println("<h3>Request Information Example</h3>");
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " +request.getProtocol());
out.println("PathInfo: " + request.getPathInfo());
out.println("Remote Address: " +
request.getRemoteAddr());
out.println("</body>");out.println("</html>"); }
/* We are going to perform the same operations for POST
requests as for GET methods, so this method just sends the request
to the doGet method.*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ doGet(request, response);}}
Request Header Example
Request Header Example Source
Code
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestHeaderExample extends
HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Enumeration e =
request.getHeaderNames();
while (e.hasMoreElements()) {
Request Parameters
Request Parameters Source Code 1/2
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestParamExample extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse
response)
throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("GET Request. No Form Data
Posted"); }
Request Parameters Source
Code –2/2
public void doPost(HttpServletRequest request,
HttpServletResponse res)
throws IOException, ServletException
{ Enumeration e = request.getParameterNames();
PrintWriter out = res.getWriter ();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getParameter(name);
out.println(name + " = " + value);}}}
Additional Capabilities of
HTTP Servlets
• Cookies are a mechanism that a servlet
uses to have clients hold a small amount of
state-information associated with the
user. Servlets can use the information in a
cookie as the user enters a site (as a lowsecurity user sign-on,for example), as the
user navigates around a site (as a
repository of user preferences for
example), or both.
• HTTP servlets also have objects that
provide cookies. The servlet writer uses
the cookie API to save data with the client
Cookies
Cookies Source Code – 1/2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
// print out cookies
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];String name = c.getName();
String value = c.getValue();
out.println(name + " = " + value);}
Cookies Source Code –
2/2
// set a cookie
String name = request.getParameter
("cookieName");
if (name != null && name.length() > 0) {
String value =
request.getParameter("cookieValue");
Cookie c = new Cookie(name, value);
response.addCookie(c);}}}
Servlet References
• For an excellent tutorial on java servlets
see:
http://www.javasoft.com/docs/books/tutorial/servl
ets/index.html
• The java Servlet API can be found at:
http://java.sun.com/products/servlet/index.html
Session Capabilities
• Session tracking is a mechanism that
servlets use to maintain state about a
series of requests from the same
user(that is, requests originating from the
same browser) across some period of time.
• session-tracking capabilities. The servlet
writer can use these APIs to maintain
state between the servlet and the client
that persists across multiple connections
during some time period.
Sessions
Sessions Source Code –1/2
import java.io.*; import java.util.*;
import javax.servlet.*; import javax.servlet.http.*;
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session =
request.getSession(true);
// print session info
Date created = new Date(
session.getCreationTime());
Date accessed = new
Sessions Source Code –2/2
out.println("ID " + session.getId());
out.println("Created: " + created);
out.println("Last Accessed: " + accessed);
String dataName =
request.getParameter("dataName");
if (dataName != null && dataName.length() > 0)
{String dataValue =
request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);}
// print session contents
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) { String name =
String)e.nextElement();
value = session.getAttribute(name).toString();
out.println(name + " = " + value);}}}
What is JSP?
• A Java Servlet is a Java program that is run
on the server
– There are Java classes for retrieving HTTP
requests and returning HTTP responses
• A Java Servlet must return an entire HTML
page, so all tuning of the page must be done in
a Java program that needs to be re-compiled
• Java Server Pages (JSP)
– use HTML and XML tags to design the page and
JSP scriplet tags to generate dynamic content
(Easier for separation between designer &
developer)
– use Java Beans and useful built-in objects for
more convinience
JSP Life Cycle
•
•
•
•
•
•
JSP page (MyFirstJSP.jsp)
-> Translated to Servle (MyFirstJSP.servlet)
-> Compiled to class (MyFirstJSP.class)
-> Loaded into memory (Initialization)
-> Execution (repeats)
-> Destruction
• Any change in JSP page automatically
repeats the whole life cycle.
Introduction
• A Java Servlet is a Java program that is run
on the server
– There are Java classes for retrieving HTTP
requests and returning HTTP responses
• A Java Servlet must return an entire HTML
page, so all tuning of the page must be done in
a Java program that needs to be re-compiled
On the other hand
• Java Server Pages (JSP)
– use HTML and XML tags to design the page and
JSP scriplet tags to generate dynamic content
– use Java Beans, which are reusable components
that are invoked by scriplets
How to Use JSPs with a
Form
• Start writing a jsp source file, creating an html form
and giving each form element a name
• Write the Bean in a .java file, defining properties, get
and set methods corresponding to the form element
names
• Return to the jsp source file, add a <jsp:useBean> tag
to locate an instance
• Add a <jsp:setProperty> tag to set properties in the
Bean from the html form
• Add a <jsp:getProperty> tag to retrieve the data from
the Bean
• If more processing is required, use the request
object from within a scriplet
What do JSPs contain?
• Template data
– Everything other than elements (eg. Html tags)
• Elements
– based on XML syntax
• <somejsptag attribute name=“atrribute value”> BODY
</somejsptag>
– Directives
– Scripting
• Declarations
• Scriptles
• Expressions
– Standard Actions
Directives
• <%@ directivename attribute=“value”
attribute=“value” %>
• The page directive
– <%@ page ATTRIBUTES %>
– language, import, Buffer, errorPage,…
– <%@ page languange=“java”
import=“java.rmi.*,java.util.*” %>
• The include directive
– <%@ include file=“Filename” %>
– the static file name to include (included at
translation time)
• The taglib directive
– <% taglib uri=“taglibraryURI” prefix=“tagPrefix”
Scripting
(Declaration, Expressions,
Scriptlets)
• <%! . . %> declares variables or methods
–
–
–
–
–
define class-wide variables
<%! int i = 0; %>
<%! int a, b; double c: %>
<%! Circle a = new Circle(2.0); %>
You must declare a variable or method in a jsp
page before you use it
– The scope of a declaration is the jsp file,
extending to all includes
• <%= . . %> defines an expression and casts
the result as a string
Scripting II
• <%= . . %> can contain any language expression,
but without a semicolon, e.g.
• <%= Math.sqrt(2) %>
• <%= items[I] %>
• <%= a + b + c %>
• <%= new java.util.Date() %>
• <% . . %> can handle declarations (page scope),
expressions, or any other type of code
fragment
• <% for(int I = 0; I < 10; I++) {
out.println(“<B> Hello World: “ + I);
} %>
Standard Actions
• <jsp:useBean> : associates an instance of a java
object with a newly declard scripting variable of
the same id
– <jsp:useBean id=“name”
scope=“page|request|session|application”
class=“className” />
• <jsp:setProperty>
– <jsp:setProperty name=“beanid” property=“*” />
• <jsp:getProperty> :action places the value of a
Bean instance property, converted to a string, into
the implicit out object
– <jsp:getProperty name=“beanid”
property=“propertyName” />
• <jsp:param>
– <jsp:param name=“paramname” value=“paramvalue” />
• <jsp:include> :Include static or dynamic
(jsp) pages with optional parameters to
pass to the included page.
– <jsp:include page=“filename” />
– <jsp:include page=“urlSpec”>
<jsp:param name paramname” value=“value”>
</jsp:include>
• <jsp:forward> : allows the runtime dispatch
of the current request to a static
resource, jsp pages or java servlet in the
same context as the current page.
– <jsp:forward page=“url” />
– <jsp:include page=“urlSpec”>
<jsp:param name paramname” value=“value”>
</jsp:forward>
JSP and Scope
• Page - objects with page scope are accessible only
within the page where they are created
• Request - objects with request scope are accessible
from pages processing the same request where they
were created
• Session - ojbects with session scope are accessible
from pages processing requests that are in the same
session as the one in which they were created
• Application - objects with application scope are
accessible from pages processing requests that are in
the same application as the one in which they were
created
• All the different scopes behave as a single name
space
Implicit Objects
• These objects do not need to be declared or
instantiated by the JSP author, but are provided by
the container (jsp engine) in the implementation class
• request Object (javax.servlet.ServletRequest)
• response Object (javax.servlet.ServletResponse)
• session Object (javax.servlet.http.HttpSession)
• application Object
• out Object
• config Object
• page Object
• pageContext Object (javax.servlet.jsp.PageContext)
• exception
Hellouser.jsp
<%@ page import=hello.NameHandler %>
<jsp:useBean id=mybean scope=page
class=hello.NameHandler />
<jsp:setProperty name=myBean property=“*” />
<html><head><title>hello user</title></head>
<body>
<h1>My name is Duke. What’s yours?</h1>
<form method=get>
<input type=text name=username><br>
<input type=submit value=submit>
</form>
<% if ( request.getParameter(username) != null) {
%><%@ include file=response.jsp %> <% } %></body>
Namehandler.java
package hello
public class NameHandler {
private String username;
public NameHandler() { username = null; }
public void setUsername ( String name) {
username=name; }
public String getusername() { return username; }
}
• Note: omit the action attribute for <form> if you want
the data processed by the object specified in the
<jsp:useBean> tag
• Response.jsp
<h1>hello, <jsp:getProperty name=mybean
property=username /></h1>
Example Elements
• JSP directive passes information to the jsp
engine; directives are enclosed in <%@ and %>
• Fixed template data, typically html or xml,
are passed through
• Jsp actions, or tags, e.g. jsp:useBean tag
instantiates the Clock JavaBean on the server
• Expressions, anything between <%== and %> is
evaluated by the jsp engine; e.g. the values of
the Day and Year attributes of the Clock
bean are returned as strings
• Scriplet is a small program written in a Java
subset; e.g. determining whether it is AM or
PM
Jsp Action tags
• jsp:useBean, declares the usage of an
instance of a java Bean component
• jsp:setProperty, sets the value of a
property in a Bean
• jsp:getProperty, gets the value of a Bean
instance property, converts it to a string
• jsp:include is a jsp directive causing the
associated file to be included
• jsp tags ARE case sensitive
Number guess - Browser
Output
JSP Examples, and their
translations
•
•
•
•
numguess.jsp
Email11 – JSP/JDBC example
Sql11 – JDBC example
Cart9 – taglib example
Why Servlet/JSP?
What is an Enterprise
Application?
•
•
•
•
Reliable
Scaleable
Maintainable
Manageable
– If you are developing an Enterprise Application
for DELL whose daily transction is more than 6
million, or NASDAQ?
• Performance? Scalability? Reliability?