Servlet/JSP CSC 667/867, Spring 2006 Dr. Ilmi Yoon
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 1/44
Servlet/JSP
CSC 667/867, Spring 2006
Dr. Ilmi Yoon
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 2/44
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 tocreate dynamic web pages
• Using Java servlets provides a platform-independent replacement for CGI scripts.
• Servlets can be embedded in many differentservers because the servlet API, which youuse to write servlets, assumes nothing aboutthe server's environment or protocol.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 3/44
The Advantages of Servlets OverTraditional CGI
• Efficiency– CGI invoking
• Overhead of starting a new process can dominate theexecution time.
• For N simultaneous request, the same code is loadedinto memory N times.
• When terminated, lose cache computation, DBconnection & ..
– 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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 4/44
The Advantages of Servlets OverTraditional 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 youare familiar with Java already.
• Easy to implement DB connection pooling & resource-sharing optimization.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 5/44
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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 6/44
Simple Exampleimport 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>");}}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 7/44
Client Interaction
• When a servlet accepts a call from aclient, 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 backto the client.
• ServletRequest and ServletResponseare interfaces defined by the javax.servlet package.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 8/44
The ServletRequest
Interface• The ServletRequest interface allows the servletaccess 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 andthe server that received it.
– The input stream, ServletInputStream. Servlets use theinput stream to get data from clients that use applicationprotocols such as the HTTP POST and PUT methods.
• Interfaces that extend ServletRequest interfaceallow the servlet to retrieve more protocol-specificdata. For example, the HttpServletRequest interfacecontains methods for accessing HTTP-specific header
information.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 9/44
The ServletResponse Interface
• The ServletResponse interface gives theservlet 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 throughwhich the servlet can send the reply data.
• Interfaces that extend theServletResponse interface give the servletmore protocol-specific capabilities.– For example, the HttpServletResponse
interface contains methods that allow the
servlet to manipulate HTTP-specific header
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 10/44
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>");
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 11/44
Request Information Example SourceCode-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);}}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 12/44
Request Header Example
R t H E S
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 13/44
Request Hea er Examp e SourceCode
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()) {=
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 15/44
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"); }
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 16/44
Request Parameters Source
Code –2/2public 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);}}}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 17/44
Additional Capabilities of
HTTP Servlets• Cookies are a mechanism that a servletuses to have clients hold a small amount ofstate-information associated with the
user. Servlets can use the information in acookie as the user enters a site (as a low-security user sign-on,for example), as theuser navigates around a site (as a
repository of user preferences forexample), or both.• HTTP servlets also have objects that
provide cookies. The servlet writer uses
the cookie API to save data with the client
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 19/44
Cookies Source Code – 1/2import 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);}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 20/44
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);}}}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 21/44
Servlet References• For an excellent tutorial on java servletssee:
http://www.javasoft.com/docs/books/tutorial/servlets/index.html
• The java Servlet API can be found at:
http://java.sun.com/products/servlet/index.html
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 22/44
Session Capabilities• Session tracking is a mechanism thatservlets use to maintain state about aseries of requests from the sameuser(that is, requests originating from thesame browser) across some period of time.
• session-tracking capabilities. The servlet
writer can use these APIs to maintainstate between the servlet and the clientthat persists across multiple connectionsduring some time period.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 24/44
Sessions Source Code –1/2import 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 infoDate created = new Date(
session.getCreationTime());
Date accessed = new
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 25/44
Sessions Source Code –2/2out.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);}}}
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 26/44
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 HTMLpage, so all tuning of the page must be done ina Java program that needs to be re-compiled
• Java Server Pages (JSP)
– use HTML and XML tags to design the page andJSP scriplet tags to generate dynamic content(Easier for separation between designer &developer)
– use Java Beans and useful built-in objects formore convinience
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 27/44
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 automaticallyrepeats the whole life cycle.
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 28/44
Introduction• A Java Servlet is a Java program that is runon the server– There are Java classes for retrieving HTTP
requests and returning HTTP responses
• A Java Servlet must return an entire HTMLpage, so all tuning of the page must be done ina 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 andJSP scriplet tags to generate dynamic content
– use Java Beans, which are reusable componentsthat are invoked by scriplets
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 29/44
How to Use JSPs with a
Form• Start writing a jsp source file, creating an html formand giving each form element a name
• Write the Bean in a .java file, defining properties, get
and set methods corresponding to the form elementnames• 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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 30/44
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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 31/44
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”
S iptin
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 32/44
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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 33/44
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 codefragment
• <% for(int I = 0; I < 10; I++) {out.println(“<B> Hello World: “ + I); } %>
S d d A i
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 34/44
Standard Actions
• <jsp:useBean> : associates an instance of a java
object with a newly declard scripting variable ofthe 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 aBean instance property, converted to a string, intothe implicit out object– <jsp:getProperty name=“beanid”
property=“propertyName” />
• <jsp:param>– <jsp:param name=“paramname” value=“paramvalue” />
• <jsp:include> :Include static or dynamic
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 35/44
• <jsp:include> :Include static or dynamic(jsp) pages with optional parameters topass 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 dispatchof the current request to a staticresource, jsp pages or java servlet in thesame context as the current page.– <jsp:forward page=“url” />
– <jsp:include page=“urlSpec”>
<jsp:param name paramname” value=“value”> </ s :forward>
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 36/44
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 accessiblefrom pages processing requests that are in the samesession as the one in which they were created
• Application - objects with application scope are
accessible from pages processing requests that are inthe same application as the one in which they werecreated
• All the different scopes behave as a single namespace
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 37/44
Implicit Objects
• These objects do not need to be declared orinstantiated by the JSP author, but are provided bythe 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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 38/44
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>
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 39/44
Namehandler.javapackage hellopublic 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 wantthe data processed by the object specified in the<jsp:useBean> tag
• Response.jsp<h1>hello, <jsp:getProperty name=mybean
property=username /></h1>
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 40/44
Example Elements
• JSP directive passes information to the jspengine; directives are enclosed in <%@ and %>
• Fixed template data , typically html or xml,are passed through
• Jsp actions , or tags, e.g. jsp:useBean taginstantiates the Clock JavaBean on the server
• Expressions , anything between <%== and %> is
evaluated by the jsp engine; e.g. the values ofthe Day and Year attributes of the Clockbean are returned as strings
• Scriplet is a small program written in a Java
subset; e.g. determining whether it is AM orPM
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 41/44
Jsp Action tags• jsp:useBean, declares the usage of aninstance 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
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 42/44
Number guess - Browser
Output
xamp es an e r
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 43/44
xamp es, an e rtranslations
• numguess.jsp
• Email11 – JSP/JDBC example
• Sql11 – JDBC example• Cart9 – taglib example
Why Servlet/JSP?
7/29/2019 csc667_Lec06_2
http://slidepdf.com/reader/full/csc667lec062 44/44
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 6million, or NASDAQ?
• Performance? Scalability? Reliability?