Beruflich Dokumente
Kultur Dokumente
Java Technology
3- Servlets
Juan M. Gimeno, Josep M. Ribó
January, 2008
INDEX
Contents
1. Introduction.
2. HTTP protocol
3. Servlets
1
INDEX
3- Servlets. Contents
• Introduction to servlets
• Servlet API
– Servlet
– GenericServlet
– HttpServlet
– HttpServletRequest
– HttpServletResponse
– ServletContext
2
Intro. to Web applications in Java. 3- Servlets. Introduction INDEX
2.3 Servlets
What is a servlet
3
Intro. to Web applications in Java. 3- Servlets. Introduction INDEX
Servlet lifecycle
Notice that servlets are only loaded the first time they are
requested.
4
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
Servlet API
• Servlet
• HttpServlet
• HttpServletRequest
• HttpServletResponse
• ServletContext
• ...
5
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
The Servlet interface defines all the operations that must
be implemented by any servlet class
Usually, this interface is implemented by means of a class
that subclassifies the class HttpServlet
• Some methods:
– void init(ServletConfig config)
Called by the servlet container right after the servlet class has been
loaded and just before starting its operation
init is called just once during all the servlet life-cycle (i.e., it may
serve many requests but init is called only before serving the first
one)
6
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
– void destroy()
Called by the servlet container to indicate to a servlet that the
servlet is being taken out of service.
– java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and
copyright.
7
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
Defines a generic, protocol-independent servlet. To write
an HTTP servlet for use on the Web, extend HttpServlet
instead.
• Implements:
The interface Servlet
8
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
HttpServlet is an abstract class to manage HTTP
servlets (i.e., servlets written for the web)
HTTP servlets written by a programmer should subclassify
HttpServlet instead of GenericServlet
• Superclass:
GenericServlet
9
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Some methods:
– protected void service(HttpServletRequest req,
HttpServletResponse res)
It is the responsible for:
∗ managing the request sent by the client and for
∗ creating a response which will be sent back to the client.
However, both issues are not actually carried out in this operation.
Instead, the service operation receives standard HTTP requests
from the client and dispatches them to the doGet/doPost operati-
ons defined in this class (according to the HTTP request method:
GET or POST)
Usually, this operation is not overriden by the classes that
subclassify HttpServlet. The overriden operations are doGet
and doPost
10
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
11
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
It is an interface that provides methods to encapsulate the
details about http requests. It controls the access to the
request elements (remote URL, header, parameters...)
• Superinterface:
ServletRequest (request independent of the protocol)
• Some methods:
– String getRequestURI();
Returns the part of this request’s URL from the protocol name up
to the query string in the first line of the HTTP request.
– String getQueryString();
Returns the query string that is contained in the request URL after
the path.
– String getMethod();
Returns the name of the HTTP method with which this request
was made, for example, GET or POST.
– Enumeration getHeaderNames();
Returns an enumeration of all the header names this request
contains.
12
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
13
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
It is an interface that acts as a wrapper of the output
stream of a servlet and of its length and type.
• Superinterface:
ServletResponse (response independent of the protocol)
• Some methods:
– String setContentLength();
Sets the length of the content body in the response In HTTP
servlets, this method sets the HTTP Content-Length header.
14
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Some methods:
– void setAttribute(String name, Object obj);
Sets the object obj as a servlet context scope attribute accessible
with the given name
15
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
<web-app>
...
<context-param>
<param-name>parameterName</param-name>
<param-value>parameterValue</param-value>
<description> Again, some description </description>
</context-param>
...
</web-app>
16
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
– It is used to send initialization information from the
servlet container to the servlet itself
– In particular, to send servlet initialization parameters
• Some methods:
– ServletContext getServletContext()
– String getInitParameter(String name)
Returns a String containing the value of the named
initialization parameter, or null if the parameter does
not exist.
17
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
18
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
• Outline:
• Some methods:
– void forward(ServletRequest request, ServletResponse respo
Forwards a request from a servlet to another resource (servlet, JSP
file, or HTML file) on the server.
Example: The servlet that calls forward has managed the request.
Another servlet is called to generate the response to the client
This strategy is used when the MVC pattern is applied (see ****)
– void include(ServletRequest request, ServletResponse respo
Includes the content of a resource (servlet, JSP page, HTML file)
in the response.
When the included resource has been managed, the control returns
to the servlet that launches the include call
Useful to include headers, footers...
19
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
Use of RequestDispatcher:
...
}
dispatcher.forward(request, response);
Example:
20
Intro. to Web applications in Java. 3- Servlets. Servlet API INDEX
request.setAttribute("catalogue", cat);
dispatcher.forward(request,response);
21
Intro. to Web applications in Java. 3- Servlets. Example 1 INDEX
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.*;
22
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
This example reads any http request and sends the contents
of this request back to the client
23
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
24
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.*;
...(cont)
25
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
26
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
out.println("<p><b>2.Request header</b><br><br>");
enum=request.getHeaderNames();
while(enum.hasMoreElements())
{
st=(String) enum.nextElement();
out.println(st+" : "+request.getHeader(st));
}
out.println("<p><b>3.Request body:</b> <br><br>");
java.io.BufferedReader br=request.getReader();
String temp=br.readLine();
while (temp!=null)
{
out.println(temp);
temp=br.readLine();
}
br.close();
out.println(PAGE_BOTTOM);
} catch (Exception ex) { ex.printStackTrace(); }
}
}
27
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
Remarks:
BufferedReader br=request.getReader();
28
Intro. to Web applications in Java. 3- Servlets. Example 2 INDEX
29
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
<html>
<h1><b>Pactador automatic </b></h1>
<form action="http://localhost:8080/josepma/param"
method="get">
<b>Nom o pseudonim:</b>
<input name="nom" type="text" size=50>
<p>
<b>Pacte preferit (selecciona almenys 2 opcions):</b>
<input name="pacte" type="checkbox" value="psc">
PSC
<input name="pacte" type="checkbox" value="ciu">
CiU
<input name="pacte" type="checkbox" value="erc">
ERC
<input name="pacte" type="checkbox" value="icv">
ICV
<p> <p>
<input type="submit" value="Enviar"></textarea>
<input type="reset" value="Reiniciar"></textarea>
</form>
</html>
30
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
31
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
32
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
out.println (PAGE_TOP);
out.println("<b>Capture of the parameter names:</b>"
+"<br><br>");
enum=request.getParameterNames();
while(enum.hasMoreElements())
{
st=(String) enum.nextElement();
out.println("name="+st);
}
out.println("<b>Capture of the parameter values:"+
"</b><br><br>");
out.println("Parameter name= ’nom’----> Value="+
request.getParameter("nom"));
out.println("Parameter name= ’pacte’----> Values=");
partits=request.getParameterValues("pacte");
for(int i=0;i<partits.length;i++){
out.println("partit "+i+": "+partits[i]);
}
} catch (Exception ex) { ex.printStackTrace();}
}}
33
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
<form action="http://localhost:8080/josepma/param">
partits=request.getParameterValues("pacte");
for(int i=0;i<partits.length;i++){
out.println("partit "+i+": "+partits[i]);
}
34
Intro. to Web applications in Java. 3- Servlets. Example 3 INDEX
35
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
• Both the static and the dynamic elements of the web page
are managed by the same code
Static elements: Those elements that do not change in
the resulting page through different requests (e.g., page
headers and footers, table structure...)
Dynamic elements: Those elements that depends on the
parameters of the request and may change in different
requests (e.g., table contents)
36
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Idea:
Do not program servlets directly, but a JSP web page
37
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
hello.jsp
is the servlet
Translate into a servlet more recent than
hello.jsp−−> hello_jsp.java hello.jsp?
NO
Compile YES
hello_jsp.java−−>
hello_jsp.class
YES
send the request to
obj
38
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
<HTML>
<head>
<title> First JSP page </title>
</head>
<body>
<h3> First JSP page </h3>
<p>Hello......
<p>1+2=
<%
int p;
p=1+2;
%>
<%=p%>
</body>
</html>
39
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
• Filters
• Event listeners
Important:
You can skip these sections in a first reading.
40
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Filters
See:
• http://java.sun.com/products/servlet/Filters.html
41
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Event listeners
42
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Examples:
43
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
• An attribute event
Examples: A session/application attribute has been crea-
ted/modified/removed
44
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
The servlet API provides interfaces with methods to manage each one of the four
types of events:
ServletContext events HttpSession events
life-cycle evts intfc: ServletContextListener intfc: HttpSessionListener
mthd: contextDestroyed(), mthd: sessionCreated(),
mthd: contextInitialized() mthd: sessionDestroyed()
attrib. chge evts intfc: ServletContextAttributeListener intf:HttpSessionAttributeListener
mthd: attributeAdded() mthd: attributeAdded()
mthd: attributeRemoved() mthd: attributeRemoved()
mthd: attributeReplaced() mthd: attributeReplaced()
45
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
46
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
47
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Example
48
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
Steps:
49
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
50
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
ServletContext servletContext;
public SessionCounter()
{}
servletContext.setAttribute
("totalSessionCounter",new Integer(0)
servletContext.setAttribute
("activeSessionCounter",new Integer(0
servletContext.removeAttribute("totalSessionCounter")
servletContext.removeAttribute("activeSessionCounter"
}
51
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
servletContext.setAttribute("totalSessionCounter",
new Integer(totalSessions.intValue()+1)
servletContext.log("SESSION CREATION");
52
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
53
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
<listener>
<listener-class>SessionCounter</listener-class>
</listener>
54
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
55
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
(e.g.: getServletContext.setAttribute("MaxProducts",mp);
)
The servlet context is shared by all the servlets of a
(non-distributed) web application
– Extern resources
Connection to networks or databases
56
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
However:
– This does not prevent problems that arise from concur-
rent access to static or scoped attributes
– This interface has been deprecated
57
Intro. to Web applications in Java. 3- Servlets. Intro to JSP INDEX
References
• Servlet specification
http://java.sun.com/products/servlet/
• Servlet API
http://java.sun.com/products/servlet/2.2/javadoc/
58