You are on page 1of 54

Servlet

ThS Vn Thin Hong


Mc ch
Cung cp kin thc nn tng v Servlet.
Cc i tng c bn s dng trong servlet.
Cch vit mt chng trnh n gin s dng
servlet.


Servlet trong kin trc J2EE
Thun li ca Servlet
B th vin Servlet chun v c h tr rt nhiu
th vin khc: JDBC, EJB, JavaMail.
S dng a nn.
S dng ton b th vin ca ngn ng Java.
Mt s web s dng Java
Google, Custom technology,some Java
Yahoo, PHP & Java
MySpace, Java
YouTube, Flash, Python, Java
Ebay, Java
AOL, Java
Servlet l g?
public class ExampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.setContentType(text/html);
out.println(Hello !<BR>);
Date rightNow = new Date();
out.println(The time is: + rightNow);
}
}
Servlet lm g?
Nhn client request
Ly thng tin t request
X l nghip v hoc pht sinh ni dung
(bng cch truy cp database, triu gi EJB,
..).
To v gi response ti client hoc chuyn
request ti mt trang servlet hoc JSP
khc.

Request v Response
Request l g?
Thng tin c gi t client ti server.
Ngi to request
D liu ngi dng nhp vo.
HTTP header
Response l g?
Thng tin c gi n client t server.
Text(html, plain) or binary(image) data.
HTTP headers, cookies,

HTTP
HTTP request gm c
Header
Mt phng thc
Get
Post
Put
Header
D liu request
Client request thng dng nht l
HTTP GET & HTTP POST
B th vin Servlet
Gi javax.servlet c cha 7 interfaces, 3
class v 2 exception.
7 interface:
RequestDispatcher
Servlet
ServletConfig
ServletContext
ServletRequest
ServletResponse
SingleThreadModel
B th vin Servlet
3 classe
GenericServlet
ServletInputStream
ServletOutputStream
2 exception
ServletException
UnavailableException

B th vin Servlet
Kin trc Servlet
YourOwnServlet
HttpServlet
Generic Servlet
Servlet
service(ServletRequest,
ServletResponse)
doGet(HttpServletRequest ,
HttpServletResponse)
doPost(HttpServletRequest
HttpServletResponse)
doPut
doTrace

Vng i ca Servlet
Browser
HTTP Request
HTTP Response
HTTP
Server
Servlet
Container
Static
Content
Servlet
Vng i ca Servlet
GET index.html HTTP/1.0
Cc bc thc hin Servlet
1. To lp tha k HttpServlet
2. Vit phng thc doGet()
3. HttpServletRequest
getParameter("paramName")
4. HttpServletResponse
Thit lp kiu ni dung.
Ly i tng PrintWriter.
Gi text v client thng qua PrintWriter.
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello World</title></head>\n");
out.println("<body>");
out.println("<h2>" + new java.util.Date() + "</h2>\n");
out.println("<h1>Hello World</h1>\n</body></html>"); }
}
HelloWorld.java
Cu hnh Server
<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
web.xml
myApp/WEB-INF/classes/HelloWorld.class
Ly thng tin t truy vn -
Request
V d HTTP Request
GET /default.asp HTTP/1.0
Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */*
Accept-Language: en
Connection: Keep-Alive
Host: magni.grainger.uiuc.edu
User-Agent: Mozilla/4.04 [en] (WinNT; I ;Nav)
Cookie:SITESERVER=ID=8dac8e0455f4890da220ada8b76f;
ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM
Accept-Charset: iso-8859-1,*,utf-8
Ly d liu
S dng i tng HttpServletRequest
Ly gi tr thng tin phn header hdr :
getHeader("hdr").
Ly tt c cc tn bin cha thng tin trong
Header: getHeaderNames()
Cc phng thc cho cc thng tin c t khc:
getCookies, getContentLength, getContentType,
getMethod, getProtocol,
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse
response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println(
"<html><head><title>" + title + "</title></head><body>\n"
+ "<h1>" + title+ "</h1>\n"
+ "<h2>Request Method: "+request.getMethod()+"</h2>"
+ "<h2>Request URI: "+request.getRequestURI()+"</h2>"
+ "<h2>ServletPath: "+request.getServletPath()+"</h2>"
+ "<h2>Request Protocol: "+request.getProtocol()+"</h2>"
+ "<table border=\"1\">\n"
+ "<tr><th>Header Name</th><th>Header Value</th></tr>");
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
out.println("<tr><td>" + headerName + "</td>"
+"<td>"+request.getHeader(headerName)+"</td></tr>");
}
out.println("</table>\n</body></html>");
}

public void doPost(HttpServletRequest request,HttpServletResponse
response) throws ServletException, IOException {
doGet(request, response);
}
}
}
Nhp d liu t Form
S dng HTML form gi d liu ln
Server.
<form action= method=> </form>
action: a ch trang web nhn d liu x l.
method: phng thc gi d liu ln trang web x
l Server (V d: get hoc post).

V d phng thc GET
<form method="get"
action="http://www.google.com/search">
<p><input name="q" type="text" />
<input type="submit" />
<input type="reset" />
</p>
</form>

http://www.google.com/search?q=servlets

<form method="post"
action="http://www.google.com/search">
<p><input name="q" type="text" />
<input type="submit" />
<input type="reset" />
</p>
</form>
V d phng thc POST
POST /search HTTP/1.1
Host: www.google.com

Content-type: application/x-www-form-urlencoded
Content-length: 10
<empty-line>
q=servlets
Google doesnt
support POST!
Ly gi tr gi ln t Client
Ly gi tr thng qua tn bin x:
req.getParameter("x")
req l i tng req.
Ly nhiu gi tr ca mt bin:
req.getParameterValues("x")
Ly cc tn bin gi ln t client.
req.getParameterNames()

<html><head><title>Sending Parameters</title>
<style type="text/css">
p{display:table-row} span{display:table-cell; padding:0.2em}
</style></head><body>

<h1>Please enter the parameters</h1>
<form action="SetColors" method="get">
<p>Background color:
<span><input type="text" name="bgcolor"/></span></p>
<p>Font color:
<span><input type="text" name="fgcolor"/> </span> </p>
<p>Font size:
<span><input type="text" name="size"/></span></p>
<h2>
<input type="submit" value="Submit Parameters"/></h2>
</form>

</body></html> parameters.html
public class SetColors extends HttpServlet {
public void doGet(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String bg = request.getParameter("bgcolor");
String fg = request.getParameter("fgcolor");
String size = request.getParameter("size");
(tip theo)
SetColors.java
out.println("<html><head><title>Set Colors Example"
+"</title></head>");

out.println("<body style=\"color:" + fg +
";background-color:" + bg + ";font-size:"+ size + "px\">");
out.println("<h1>Set Colors Example</h1>");
out.println("<p>You requested a background color " + bg + "</p>");
out.println("<p>You requested a font color " + fg + "</p>");
out.println("<p>You requested a font size " + size + "</p>");

out.println("</body></html>");
} SetColors.java
(tip theo)
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
Khng c s khc nhau trong cch dc d liu ca
phng thc POST so vi GET.

<form
action="http://www.mscs.mu.edu:9080/praveen/servlet/H
elloWorldExample"
method="post">
Nhn d liu t phng thc Post
Gi tr d liu v Client -
Response
HTTP Response
Response bao gm:
Status line: phin bn, m trng thi, thng ip trng
thi.
Response headers
Empty line
Content
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 89
Server: Apache-Coyote/1.1

<HTML><HEAD><TITLE>HELLO
WORLD</TITLE></HEAD>
<BODY><H1>Hello World
</H1></BODY></HTML>
Thit lp thng tin trng thi p tr
S dng phng thc HttpServletResponse :
- setStatus(int sc)
S dng khng c li.
- sendError(sc), sendError(sc, message)
S dng khi c li. V d: 400 (yu cu khng tm thy)
The server may return a formatted message
- sendRedirect(String location)
Chuyn sang trang khc.
Thit lp Response Status
Lp HTTPServletResponse c nhng bin s
nguyn tnh l m trng thi.
V d:
SC_OK(200), SC_NOT_MODIFIED(304),
SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400)
M 200 (OK) l mc nh.

Thit lp Response Headers
S dng HTTPServletResponse :
- setHeader(String hdr, String value), setIntHeader(String hdr,
int value)
- Vd: response.setHeader(Refresh, 10;url=http://127.0.0.1/foo.html);
- addHeader(String hdr, String value), addIntHeader(String hdr,
int value)
Cho php vit gi tr hin c.


Cc Response Header ring
Lp HTTPServletResponse cung cp setters
cho mt s header ring:
- setContentType
- setContentLength
T ng thit lp khi ni dung c in vo b
m response.
- setDateHeader
- setCharacterEncoding
Mt s phng thc Header khc
containsHeader(String header)
Kim tra mt header tn ti hay cha.
addCookie(Cookie)
sendRedirect(String url)
Khng vit vo response sau khi gi
sendError hoc sendRedirect
B m p ca i tng Response
Servlet



server
Buffer


client
setBufferSize
getBufferSize
isComitted
flushBuffer
reset
resetBuffer
request
response
Mt s phng thc h tr
HTTP
Phng thc HEAD
Mc nh khi doHead c thc hin khi
thc hin hm doGet.
Kch thc ca phn thn s c tnh ton
v a vo header.
OPTIONS v TRACE
doOptions tr li cc phng thc h tr hm.
GET, HEAD, TRACE, OPTIONS
doTrace tr li thng tin truy vn ca chnh n by li.
Cc phng thc ny thng khng c vit .
Mt s phng thc khng h tr
Mc nh, cc phng thc doPost, doGet, doPut v
doDelete tr li li 405 vi thng ip:
HTTP method XXX is not supported by this URL
Thng thng, ch s dng phng thc doGet v
doPost
Vng i Servlet
Servlet Class
Calling the
init method
Servlet
Instance
Deal with requests:
call the
service method
Destroy the Servlet:
call the
destroy method
Garbage
Collection
ServletConfig
Thit lp Servlet
Phng thc init c tham s kiu ServletConfig.
ServletConfig c phng thc c cc tham
s thit lp t web.xml
thit lp, vit phng thc init()
(nhng khng i vi init(ServletConfig) ).
<web-app>

<servlet>
<servlet-name>InitExample</servlet-name>
<servlet-class>ServletInit</servlet-class>
<init-param>
<param-name>login</param-name>
<param-value>snoopy</param-value>
</init-param>
</servlet>

</web-app>
A web.xml Example
public class ServletInit extends HttpServlet {
String _login = null;
Calendar _initTime = null;
public void init() throws ServletException {
_login = this.getInitParameter("login");
_initTime = new GregorianCalendar();
}
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><head><title>Initialization</title><body><h2>"
+ "I am the Servlet of <i>" + _login+ "</i><br/>"
+ "I was initialized at " + _initTime.get(Calendar.HOUR_OF_DAY)
+ ":"+ _initTime.get(Calendar.MINUTE)
+ ":"+ _initTime.get(Calendar.SECOND)
+ "</h2></body></html>"); }} ServletInit.java
Hy Servlet
Server loi b Servlet khi:
Server shutdown.
Servlet khng hot ng trong thi gian di.
server cn gii phng ti nguyn.
Trc khi gii phng, phng thc destroy()
c gi.
C th s dng xa, ng kt ni c s d liu.
The Servlet Context
i tng ServletContext
i tng ServletContext biu din ng dng Web
khi Servlet sng.
Ch c mt ServletContext ng vi mt ng dng.
Ly i tng ServletContext s dng phng thc
getServletContext()
C th lu i tng d liu vo ServletContext.
V d: ServiceCount
public class CounterServlet extends HttpServlet {

public void init() throws ServletException {
Integer counter =
(Integer)getServletContext().getAttribute("counter");

if(counter == null) {
getServletContext().setAttribute("counter",new Integer(0));
}
}
public void doGet(HttpServletRequest req,HttpServletResponse
res) throws ServletException, IOException {

PrintWriter out = res.getWriter();
res.setContentType("text/html");
int counter = 0;
synchronized(this) {
counter = ((Integer)getServletContext().
getAttribute("counter")).intValue();
getServletContext().
setAttribute("counter",new Integer(++counter));
}
out.println("<html><head><title>Counter</title><body><h1>"
+ "[" + counter + "]</h1></body></html>");
}}
ContextListener
i tng ContextListener c gi khi cc s kin
thit lp v pht hy c gi.
initialization
destruction
Do vy, c th s dng ContextListener thc
hin cc nhim v thit lp hoc kt thc ng dng.
thc hin vic Listener ny:
Ci t giao din ServletContextListener.
ng k listener vi server.


Cheating with Service Count
public class CounterInitializer implements
ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().
setAttribute("counter",new Integer(1000));
}

public void contextDestroyed(ServletContextEvent sce) {}
}
<web-app>
<listener>
<listener-class>CounterInitializer</listener-class>
</listener>
</web-app>
Cu hi

You might also like