SlideShare une entreprise Scribd logo
1  sur  54
Servlet
ThS Văn Thiên Hoàng
M c đíchụ
Cung c p ki n th c n n t ng v Servlet.ấ ế ứ ề ả ề
Các đ i t ng c b n s d ng trong servlet.ố ượ ơ ả ử ụ
Cách vi t m t ch ng trình đ n gi n sế ộ ươ ơ ả ử
d ng servlet.ụ
Servlet trong ki n trúc J2EEế
Thu n l i c a Servletậ ợ ủ
B th vi n Servlet chu n và đ c h tr r tộ ư ệ ẩ ượ ỗ ợ ấ
nhi u th vi n khác: JDBC, EJB, JavaMail.ề ư ệ
S d ng đa n n.ử ụ ề
S d ng toàn b th vi n c a ngôn ng Java.ử ụ ộ ư ệ ủ ữ
M t s web s d ng 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 làm gì?
Nh n client requestậ
L y thông tin t requestấ ừ
X lý nghi p v ho c phát sinh n i dungử ệ ụ ặ ộ
(b ng cách truy c p database, tri u g iằ ậ ệ ọ
EJB, ..).
T o và g i response t i client ho c chuy nạ ở ớ ặ ể
request t i m t trang servlet ho c JSPớ ộ ặ
khác.
Request và Response
Request là gì?
Thông tin đ c g i t client t i server.ượ ở ừ ớ
• Ng i t o requestườ ạ
• D li u ng i dùng nh p vào.ữ ệ ườ ậ
• HTTP header
Response là gì?
Thông tin đ c g i đ n client t server.ượ ở ế ừ
• Text(html, plain) or binary(image) data.
• HTTP headers, cookies, …
HTTP
HTTP request g m cóồ
Header
M t ph ng th cộ ươ ứ
• Get
• Post
• Put
• Header
D li u requestữ ệ
Client request thông d ng nh t làụ ấ
HTTP GET & HTTP POST
B th vi n Servletộ ư ệ
Gói javax.servlet có ch a 7ứ interfaces, 3
class và 2 exception.
7 interface:
RequestDispatcher
Servlet
ServletConfig
ServletContext
ServletRequest
ServletResponse
SingleThreadModel
B th vi n Servletộ ư ệ
3 classe
GenericServlet
ServletInputStream
ServletOutputStream
2 exception
ServletException
UnavailableException
B th vi n Servletộ ư ệ
Ki n trúc Servletế
YourOwnServlet
HttpServlet
Generic Servlet
Servlet
service(ServletRequest,
ServletResponse)
doGet(HttpServletRequest ,
HttpServletResponse)
doPost(HttpServletRequest
HttpServletResponse)
doPut
doTrace
…
Vòng đ i c a Servletờ ủ
Browser
HTTP Request
HTTP Response
HTTP
Server
Servlet
Container
Static
Content
Servlet
Vòng đ i c a Servletờ ủ
GET index.html HTTP/1.0
Các b c th c hi n Servletướ ự ệ
1. T o l p th a k HttpServletạ ớ ừ ế
2. Vi t đè ph ng th c doGet()ế ươ ứ
3. HttpServletRequest
getParameter("paramName")
4. HttpServletResponse
Thi t l p ki u n i dung.ế ậ ể ộ
L y đ i t ng PrintWriter.ấ ố ượ
G i text v client thông 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
C u hình 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
L y thông tin t truy v n -ấ ừ ấ
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
L y d li uấ ữ ệ
S d ng đ i t ngử ụ ố ượ HttpServletRequest
L y giá tr thông tin ph n headerấ ị ầ hdr :
getHeader("hdr").
L y t t c các tên bi n ch a thông tin trongấ ấ ả ế ứ
Header: getHeaderNames()
Các ph ng th c cho các thông tin đ c t khác:ươ ứ ặ ả
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);
}
}
}
Nh p d li u t Formậ ữ ệ ừ
S d ng HTML form đ g i d li u lênử ụ ể ở ữ ệ
Server.
<form action=… method=…> …</form>
• action: đ a ch trang web nh n d li u đ x lý.ị ỉ ậ ữ ệ ể ử
• method: ph ng th c g i d li u lên trang webươ ứ ở ữ ệ
x lý Server (Ví d :ử ở ụ get ho cặ post).
Ví d ph ng th c 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 ph ng th c 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 doesn’t
support POST!
L y giá tr g i lên t Clientấ ị ở ừ
L y giá tr thông qua tên bi nấ ị ế x:
req.getParameter("x")
req là đối tượng req.
L y nhi u giá tr c a m t bi n:ấ ề ị ủ ộ ế
req.getParameterValues("x")
L y các tên bi n g i lên 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>
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");
(ti p 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
(ti p theo)ế
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
Không có s khác nhau trong cách d c d li u c aự ọ ữ ệ ủ
ph ng th cươ ứ POST so v iớ GET.
<form
action="http://www.mscs.mu.edu:9080/praveen/servlet/H
elloWorldExample"
method="post"> …
Nh n d li u t ph ng th c Postậ ữ ệ ừ ươ ứ
G i tr d li u v Client -ở ả ữ ệ ề
Response
HTTP Response
Response bao g m:ồ
 Status line: phiên b n, mã tr ng thái, thông đi pả ạ ệ
tr ng thái.ạ
 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>
Thi t l p thông tin tr ng thái đáp trế ậ ạ ả
S d ng ph ng th cử ụ ươ ứ HttpServletResponse :
- setStatus(int sc)
• S d ng không có l i.ử ụ ỗ
- sendError(sc), sendError(sc, message)
• S d ng khi có l i. Ví d : 400 (yêu c u không tìm th y)ử ụ ỗ ụ ầ ấ
• The server may return a formatted message
- sendRedirect(String location)
• Chuy n sang trang khác.ể
Thi t l p Response Statusế ậ
L pớ HTTPServletResponse có nh ng bi n sữ ế ố
nguyên tĩnh là mã tr ng thái.ạ
Ví d :ụ
SC_OK(200), SC_NOT_MODIFIED(304),
SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400)
Mã 200 (OK) là m c đ nh.ặ ị
Thi t l p Response Headersế ậ
S d ngử ụ 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 phép vi t đè giá tr hi n có.ế ị ệ
Các Response Header riêng
L pớ HTTPServletResponse cung c p settersấ
cho m t s header riêng:ộ ố
- setContentType
- setContentLength
• T đ ng thi t l p khi n i dung đ c đi n vào bự ộ ế ậ ộ ượ ề ộ
đ m response.ệ
- setDateHeader
- setCharacterEncoding
M t s ph ng th c Header khácộ ố ươ ứ
• containsHeader(String header)
Ki m tra m t header đã t n t i hay ch a.ể ộ ồ ạ ư
• addCookie(Cookie)
• sendRedirect(String url)
Không vi t vào response sau khi g iế ọ
sendError ho cặ sendRedirect
B đ m đáp c a đ i t ng Responseộ ệ ủ ố ượ
Servlet
server
Buffer
client
setBufferSize
getBufferSize
isComitted
flushBuffer
reset
resetBuffer
request
response
M t s ph ng th c h trộ ố ươ ứ ỗ ợ
HTTP
Ph ng th c HEADươ ứ
M c đ nh khiặ ị doHead đ c th c hi n khiượ ự ệ
th c hi n hàmự ệ doGet.
Kích th c c a ph n th n s đ c tính toánướ ủ ầ ầ ẽ ượ
và đ a vào header.ư
OPTIONS và TRACE
doOptions tr l i các ph ng th c h tr hàm.ả ạ ươ ứ ỗ ợ
GET, HEAD, TRACE, OPTIONS
doTrace tr l i thông tin truy v n c a chính nó đ b y l i.ả ạ ấ ủ ể ẩ ỗ
Các ph ng th c này th ng không đ c vi t đè.ươ ứ ườ ượ ế
M t s ph ng th c không h trộ ố ươ ứ ỗ ợ
M c đ nh, các ph ng th cặ ị ươ ứ doPost, doGet, doPut
và doDelete tr l i l iả ạ ỗ 405 v i thông đi p:ớ ệ
HTTP method XXX is not supported by this URL
Thông th ng, ch s d ng ph ng th cườ ỉ ử ụ ươ ứ doGet và
doPost
Vòng đ 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
Thi t l p Servletế ậ
Ph ng th cươ ứ init có tham s ki uố ể
ServletConfig.
ServletConfig có ph ng th c đ c các thamươ ứ ọ
s thi t l p tố ế ậ ừ web.xml
Đ thi t l p, vi t đè ph ng th cể ế ậ ế ươ ứ init()
(nh ng không đ i v iư ố ớ 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
H y Servletủ
Server lo i b Servlet khi:ạ ỏ
Server shutdown.
Servlet không ho t đ ng trong th i gian dài.ạ ộ ờ
server c n gi i phóng tài nguyên.ầ ả
Tr c khi gi i phóng, ph ng th cướ ả ươ ứ destroy()
đ c g i.ượ ọ
Có th s d ng đ xóa, đóng k t n i c s dể ử ụ ể ế ố ơ ở ữ
li u.ệ
The Servlet Context
Đ i t ng ServletContextố ượ
Đ i t ngố ượ ServletContext bi u di n ng d ng Webể ễ ứ ụ
khi Servlet s ng.ố
Ch có m t ServletContext ng v i m t ng d ng.ỉ ộ ứ ớ ộ ứ ụ
L y đ i t ng ServletContext s d ng ph ngấ ố ượ ử ụ ươ
th cứ getServletContext()
Có th l u đ i t ng d li u vào 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 t ngố ượ ContextListener đ c g i khi các sượ ọ ự
ki n thi t l p và phát h y đ c g i.ệ ế ậ ủ ượ ọ
initialization
destruction
Do v y, có th s d ng ContextListener đ th cậ ể ử ụ ể ự
hi n các nhi m v thi t l p ho c k t thúc ngệ ệ ụ ế ậ ặ ế ứ
d ng.ụ
Đ th c hi n vi c Listener này:ể ự ệ ệ
Cài đ t giao di nặ ệ ServletContextListener.
Đăng ký listener v i 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>
Câu h iỏ

Contenu connexe

Tendances

Ebook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoEbook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoTrung Thanh Nguyen
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkPhuoc Nguyen
 
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPTBài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPTMasterCode.vn
 
Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Ham Chơi
 
Bai4 basic jsp_4474
Bai4 basic jsp_4474Bai4 basic jsp_4474
Bai4 basic jsp_4474Ham Chơi
 
Bat dau hoc lap trinh asp
Bat dau hoc lap trinh aspBat dau hoc lap trinh asp
Bat dau hoc lap trinh aspLam To
 
DVMS tạo module joomla 2.5
DVMS tạo module joomla 2.5DVMS tạo module joomla 2.5
DVMS tạo module joomla 2.5dvms
 
Bai3 basic servlets_956
Bai3 basic servlets_956Bai3 basic servlets_956
Bai3 basic servlets_956Ham Chơi
 
Bai tap java_script-html-2016
Bai tap java_script-html-2016Bai tap java_script-html-2016
Bai tap java_script-html-2016viethoang89
 
Tu hoc javascript
Tu hoc javascriptTu hoc javascript
Tu hoc javascriptzingoncmu2
 
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPTBÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPTMasterCode.vn
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java scripthieusy
 
Giao trinh java_script (1)
Giao trinh java_script (1)Giao trinh java_script (1)
Giao trinh java_script (1)duynamit
 
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầuTài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầuLel Đặng Văn
 

Tendances (20)

Jsp java bean
Jsp   java beanJsp   java bean
Jsp java bean
 
Bai 09 Basic jsp
Bai 09 Basic jspBai 09 Basic jsp
Bai 09 Basic jsp
 
JSP and Database
JSP and DatabaseJSP and Database
JSP and Database
 
Ebook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng caoEbook học Javascript cơ bản tới nâng cao
Ebook học Javascript cơ bản tới nâng cao
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPTBài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
Bài 7: Thư viện jQuery và thư viện jQuery UI - Giáo trình FPT
 
Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952
 
Bai4 basic jsp_4474
Bai4 basic jsp_4474Bai4 basic jsp_4474
Bai4 basic jsp_4474
 
Bat dau hoc lap trinh asp
Bat dau hoc lap trinh aspBat dau hoc lap trinh asp
Bat dau hoc lap trinh asp
 
DVMS tạo module joomla 2.5
DVMS tạo module joomla 2.5DVMS tạo module joomla 2.5
DVMS tạo module joomla 2.5
 
Bai3 basic servlets_956
Bai3 basic servlets_956Bai3 basic servlets_956
Bai3 basic servlets_956
 
Javascript and dom_html
Javascript and dom_htmlJavascript and dom_html
Javascript and dom_html
 
Zing osapi v1.3.3
Zing osapi v1.3.3Zing osapi v1.3.3
Zing osapi v1.3.3
 
Bai tap java_script-html-2016
Bai tap java_script-html-2016Bai tap java_script-html-2016
Bai tap java_script-html-2016
 
Tu hoc javascript
Tu hoc javascriptTu hoc javascript
Tu hoc javascript
 
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPTBÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
BÀI 3 Làm việc với JAVASCRIPT và JQUERY - Giáo trình FPT
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
 
Giao trinh java_script (1)
Giao trinh java_script (1)Giao trinh java_script (1)
Giao trinh java_script (1)
 
Giao Trinh Jquery
Giao Trinh JqueryGiao Trinh Jquery
Giao Trinh Jquery
 
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầuTài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
 

En vedette

Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng CaoBài 1: Web Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng CaoTuan Nguyen
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp
 
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajax
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajaxSức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajax
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajaxTuyet Tam
 
Bài 12: JSF-2 - Lập Trình Mạng Nâng Cao
Bài 12:  JSF-2 - Lập Trình Mạng Nâng CaoBài 12:  JSF-2 - Lập Trình Mạng Nâng Cao
Bài 12: JSF-2 - Lập Trình Mạng Nâng CaoTuan Nguyen
 
[Cntt] bài giảng java khtn hcm
[Cntt] bài giảng java   khtn hcm[Cntt] bài giảng java   khtn hcm
[Cntt] bài giảng java khtn hcmHong Phuoc Nguyen
 
Vận dụng kiến thức lập trình web vào môi trường thực tế
Vận dụng kiến thức lập trình web vào môi trường thực tếVận dụng kiến thức lập trình web vào môi trường thực tế
Vận dụng kiến thức lập trình web vào môi trường thực tếVKhang Yang
 
VCP 21- VMWare VPC 6
VCP 21- VMWare VPC 6VCP 21- VMWare VPC 6
VCP 21- VMWare VPC 6Tuan Nguyen
 
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPT
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPTBài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPT
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPTMasterCode.vn
 
tài liệu Mã nguồn mở Lap trình shells
tài liệu Mã nguồn mở  Lap trình shellstài liệu Mã nguồn mở  Lap trình shells
tài liệu Mã nguồn mở Lap trình shellsThuyet Nguyen
 
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPT
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPTBài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPT
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPTMasterCode.vn
 
Presentation on leadership
Presentation on leadershipPresentation on leadership
Presentation on leadershipsd college
 
Leadership concepts and theories
Leadership concepts and theoriesLeadership concepts and theories
Leadership concepts and theoriesalaguraja76
 

En vedette (13)

Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng CaoBài 1: Web Cơ Bản - Lập Trình Mạng Nâng Cao
Bài 1: Web Cơ Bản - Lập Trình Mạng Nâng Cao
 
Security Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toanSecurity Bootcamp 2013 - Lap trinh web an toan
Security Bootcamp 2013 - Lap trinh web an toan
 
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajax
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajaxSức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajax
Sức mạnh của jsf 2, phần 3 xử lý sự kiện, java script và ajax
 
Bài 12: JSF-2 - Lập Trình Mạng Nâng Cao
Bài 12:  JSF-2 - Lập Trình Mạng Nâng CaoBài 12:  JSF-2 - Lập Trình Mạng Nâng Cao
Bài 12: JSF-2 - Lập Trình Mạng Nâng Cao
 
[Cntt] bài giảng java khtn hcm
[Cntt] bài giảng java   khtn hcm[Cntt] bài giảng java   khtn hcm
[Cntt] bài giảng java khtn hcm
 
Vận dụng kiến thức lập trình web vào môi trường thực tế
Vận dụng kiến thức lập trình web vào môi trường thực tếVận dụng kiến thức lập trình web vào môi trường thực tế
Vận dụng kiến thức lập trình web vào môi trường thực tế
 
VCP 21- VMWare VPC 6
VCP 21- VMWare VPC 6VCP 21- VMWare VPC 6
VCP 21- VMWare VPC 6
 
Linux LPI Bacis
Linux LPI BacisLinux LPI Bacis
Linux LPI Bacis
 
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPT
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPTBài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPT
Bài 2: Các khái niệm trong CSDL quan hệ - Giáo trình FPT
 
tài liệu Mã nguồn mở Lap trình shells
tài liệu Mã nguồn mở  Lap trình shellstài liệu Mã nguồn mở  Lap trình shells
tài liệu Mã nguồn mở Lap trình shells
 
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPT
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPTBài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPT
Bài 1: Tổng quan về cơ sở dữ liệu - Giáo trình FPT
 
Presentation on leadership
Presentation on leadershipPresentation on leadership
Presentation on leadership
 
Leadership concepts and theories
Leadership concepts and theoriesLeadership concepts and theories
Leadership concepts and theories
 

Similaire à Bài 3: Servlet - Lập Trình Mạng Nâng Cao

Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnSon Nguyen
 
E learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHPE learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHPelearninglabvn
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-zManhh Nguyễn
 
Net06 asp.net applications & state management
Net06 asp.net applications & state managementNet06 asp.net applications & state management
Net06 asp.net applications & state managementhoangnguyentien
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnAsahina Infotech
 
PHP.pdf
PHP.pdfPHP.pdf
PHP.pdfTinPh6
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoPhaolo Pham
 
Tai lieu-huong dan ajax
Tai lieu-huong dan ajaxTai lieu-huong dan ajax
Tai lieu-huong dan ajaxtraitimvohon
 
Tai lieu-huong dan ajax
Tai lieu-huong dan ajaxTai lieu-huong dan ajax
Tai lieu-huong dan ajaxKim Hyun Hai
 

Similaire à Bài 3: Servlet - Lập Trình Mạng Nâng Cao (20)

Ch06
Ch06Ch06
Ch06
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
 
Php day4
Php day4Php day4
Php day4
 
Ung dun web chuong 2
Ung dun web  chuong 2Ung dun web  chuong 2
Ung dun web chuong 2
 
E learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHPE learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHP
 
Bai th08 php voi csdl
Bai th08 php voi csdlBai th08 php voi csdl
Bai th08 php voi csdl
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
 
chuong_02.ppt
chuong_02.pptchuong_02.ppt
chuong_02.ppt
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-z
 
Net06 asp.net applications & state management
Net06 asp.net applications & state managementNet06 asp.net applications & state management
Net06 asp.net applications & state management
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
 
PHP.pdf
PHP.pdfPHP.pdf
PHP.pdf
 
Java script
Java scriptJava script
Java script
 
Dsd05 02a-xml-rpca
Dsd05 02a-xml-rpcaDsd05 02a-xml-rpca
Dsd05 02a-xml-rpca
 
JavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng CaoJavaEE Basic_Chapter4: Servlet Nâng Cao
JavaEE Basic_Chapter4: Servlet Nâng Cao
 
Asp
AspAsp
Asp
 
Ajax
AjaxAjax
Ajax
 
Ung dung web chuong 5
Ung dung web  chuong 5Ung dung web  chuong 5
Ung dung web chuong 5
 
Tai lieu-huong dan ajax
Tai lieu-huong dan ajaxTai lieu-huong dan ajax
Tai lieu-huong dan ajax
 
Tai lieu-huong dan ajax
Tai lieu-huong dan ajaxTai lieu-huong dan ajax
Tai lieu-huong dan ajax
 

Bài 3: Servlet - Lập Trình Mạng Nâng Cao

  • 2. M c đíchụ Cung c p ki n th c n n t ng v Servlet.ấ ế ứ ề ả ề Các đ i t ng c b n s d ng trong servlet.ố ượ ơ ả ử ụ Cách vi t m t ch ng trình đ n gi n sế ộ ươ ơ ả ử d ng servlet.ụ
  • 3. Servlet trong ki n trúc J2EEế
  • 4. Thu n l i c a Servletậ ợ ủ B th vi n Servlet chu n và đ c h tr r tộ ư ệ ẩ ượ ỗ ợ ấ nhi u th vi n khác: JDBC, EJB, JavaMail.ề ư ệ S d ng đa n n.ử ụ ề S d ng toàn b th vi n c a ngôn ng Java.ử ụ ộ ư ệ ủ ữ M t s web s d ng Javaộ ố ử ụ Google, Custom technology,some Java Yahoo, PHP & Java MySpace, Java YouTube, Flash, Python, Java Ebay, Java AOL, Java
  • 5. 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); } }
  • 6. Servlet làm gì? Nh n client requestậ L y thông tin t requestấ ừ X lý nghi p v ho c phát sinh n i dungử ệ ụ ặ ộ (b ng cách truy c p database, tri u g iằ ậ ệ ọ EJB, ..). T o và g i response t i client ho c chuy nạ ở ớ ặ ể request t i m t trang servlet ho c JSPớ ộ ặ khác.
  • 7. Request và Response Request là gì? Thông tin đ c g i t client t i server.ượ ở ừ ớ • Ng i t o requestườ ạ • D li u ng i dùng nh p vào.ữ ệ ườ ậ • HTTP header Response là gì? Thông tin đ c g i đ n client t server.ượ ở ế ừ • Text(html, plain) or binary(image) data. • HTTP headers, cookies, …
  • 8. HTTP HTTP request g m cóồ Header M t ph ng th cộ ươ ứ • Get • Post • Put • Header D li u requestữ ệ Client request thông d ng nh t làụ ấ HTTP GET & HTTP POST
  • 9. B th vi n Servletộ ư ệ Gói javax.servlet có ch a 7ứ interfaces, 3 class và 2 exception. 7 interface: RequestDispatcher Servlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel
  • 10. B th vi n Servletộ ư ệ 3 classe GenericServlet ServletInputStream ServletOutputStream 2 exception ServletException UnavailableException
  • 11. B th vi n Servletộ ư ệ
  • 12. Ki n trúc Servletế YourOwnServlet HttpServlet Generic Servlet Servlet service(ServletRequest, ServletResponse) doGet(HttpServletRequest , HttpServletResponse) doPost(HttpServletRequest HttpServletResponse) doPut doTrace …
  • 13. Vòng đ i c a Servletờ ủ Browser HTTP Request HTTP Response HTTP Server Servlet Container Static Content Servlet
  • 14. Vòng đ i c a Servletờ ủ GET index.html HTTP/1.0
  • 15. Các b c th c hi n Servletướ ự ệ 1. T o l p th a k HttpServletạ ớ ừ ế 2. Vi t đè ph ng th c doGet()ế ươ ứ 3. HttpServletRequest getParameter("paramName") 4. HttpServletResponse Thi t l p ki u n i dung.ế ậ ể ộ L y đ i t ng PrintWriter.ấ ố ượ G i text v client thông qua PrintWriter.ở ề
  • 16. 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
  • 17. C u hình 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
  • 18. L y thông tin t truy v n -ấ ừ ấ Request
  • 19. 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
  • 20. L y d li uấ ữ ệ S d ng đ i t ngử ụ ố ượ HttpServletRequest L y giá tr thông tin ph n headerấ ị ầ hdr : getHeader("hdr"). L y t t c các tên bi n ch a thông tin trongấ ấ ả ế ứ Header: getHeaderNames() Các ph ng th c cho các thông tin đ c t khác:ươ ứ ặ ả getCookies, getContentLength, getContentType, getMethod, getProtocol, …
  • 21. 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>");
  • 22. 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); } } }
  • 23. Nh p d li u t Formậ ữ ệ ừ S d ng HTML form đ g i d li u lênử ụ ể ở ữ ệ Server. <form action=… method=…> …</form> • action: đ a ch trang web nh n d li u đ x lý.ị ỉ ậ ữ ệ ể ử • method: ph ng th c g i d li u lên trang webươ ứ ở ữ ệ x lý Server (Ví d :ử ở ụ get ho cặ post).
  • 24. Ví d ph ng th c 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
  • 25. <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 ph ng th c 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 doesn’t support POST!
  • 26. L y giá tr g i lên t Clientấ ị ở ừ L y giá tr thông qua tên bi nấ ị ế x: req.getParameter("x") req là đối tượng req. L y nhi u giá tr c a m t bi n:ấ ề ị ủ ộ ế req.getParameterValues("x") L y các tên bi n g i lên t client.ấ ế ở ừ req.getParameterNames()
  • 27. <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> parameters.html
  • 28. 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"); (ti p theo)ế SetColors.java
  • 29. 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 (ti p theo)ế
  • 30. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } Không có s khác nhau trong cách d c d li u c aự ọ ữ ệ ủ ph ng th cươ ứ POST so v iớ GET. <form action="http://www.mscs.mu.edu:9080/praveen/servlet/H elloWorldExample" method="post"> … Nh n d li u t ph ng th c Postậ ữ ệ ừ ươ ứ
  • 31. G i tr d li u v Client -ở ả ữ ệ ề Response
  • 32. HTTP Response Response bao g m:ồ  Status line: phiên b n, mã tr ng thái, thông đi pả ạ ệ tr ng thái.ạ  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>
  • 33. Thi t l p thông tin tr ng thái đáp trế ậ ạ ả S d ng ph ng th cử ụ ươ ứ HttpServletResponse : - setStatus(int sc) • S d ng không có l i.ử ụ ỗ - sendError(sc), sendError(sc, message) • S d ng khi có l i. Ví d : 400 (yêu c u không tìm th y)ử ụ ỗ ụ ầ ấ • The server may return a formatted message - sendRedirect(String location) • Chuy n sang trang khác.ể
  • 34. Thi t l p Response Statusế ậ L pớ HTTPServletResponse có nh ng bi n sữ ế ố nguyên tĩnh là mã tr ng thái.ạ Ví d :ụ SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400) Mã 200 (OK) là m c đ nh.ặ ị
  • 35. Thi t l p Response Headersế ậ S d ngử ụ 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 phép vi t đè giá tr hi n có.ế ị ệ
  • 36. Các Response Header riêng L pớ HTTPServletResponse cung c p settersấ cho m t s header riêng:ộ ố - setContentType - setContentLength • T đ ng thi t l p khi n i dung đ c đi n vào bự ộ ế ậ ộ ượ ề ộ đ m response.ệ - setDateHeader - setCharacterEncoding
  • 37. M t s ph ng th c Header khácộ ố ươ ứ • containsHeader(String header) Ki m tra m t header đã t n t i hay ch a.ể ộ ồ ạ ư • addCookie(Cookie) • sendRedirect(String url) Không vi t vào response sau khi g iế ọ sendError ho cặ sendRedirect
  • 38. B đ m đáp c a đ i t ng Responseộ ệ ủ ố ượ Servlet server Buffer client setBufferSize getBufferSize isComitted flushBuffer reset resetBuffer request response
  • 39. M t s ph ng th c h trộ ố ươ ứ ỗ ợ HTTP
  • 40. Ph ng th c HEADươ ứ M c đ nh khiặ ị doHead đ c th c hi n khiượ ự ệ th c hi n hàmự ệ doGet. Kích th c c a ph n th n s đ c tính toánướ ủ ầ ầ ẽ ượ và đ a vào header.ư
  • 41. OPTIONS và TRACE doOptions tr l i các ph ng th c h tr hàm.ả ạ ươ ứ ỗ ợ GET, HEAD, TRACE, OPTIONS doTrace tr l i thông tin truy v n c a chính nó đ b y l i.ả ạ ấ ủ ể ẩ ỗ Các ph ng th c này th ng không đ c vi t đè.ươ ứ ườ ượ ế
  • 42. M t s ph ng th c không h trộ ố ươ ứ ỗ ợ M c đ nh, các ph ng th cặ ị ươ ứ doPost, doGet, doPut và doDelete tr l i l iả ạ ỗ 405 v i thông đi p:ớ ệ HTTP method XXX is not supported by this URL Thông th ng, ch s d ng ph ng th cườ ỉ ử ụ ươ ứ doGet và doPost
  • 43. Vòng đ 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
  • 44. Thi t l p Servletế ậ Ph ng th cươ ứ init có tham s ki uố ể ServletConfig. ServletConfig có ph ng th c đ c các thamươ ứ ọ s thi t l p tố ế ậ ừ web.xml Đ thi t l p, vi t đè ph ng th cể ế ậ ế ươ ứ init() (nh ng không đ i v iư ố ớ init(ServletConfig) ).
  • 46. 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
  • 47. H y Servletủ Server lo i b Servlet khi:ạ ỏ Server shutdown. Servlet không ho t đ ng trong th i gian dài.ạ ộ ờ server c n gi i phóng tài nguyên.ầ ả Tr c khi gi i phóng, ph ng th cướ ả ươ ứ destroy() đ c g i.ượ ọ Có th s d ng đ xóa, đóng k t n i c s dể ử ụ ể ế ố ơ ở ữ li u.ệ
  • 49. Đ i t ng ServletContextố ượ Đ i t ngố ượ ServletContext bi u di n ng d ng Webể ễ ứ ụ khi Servlet s ng.ố Ch có m t ServletContext ng v i m t ng d ng.ỉ ộ ứ ớ ộ ứ ụ L y đ i t ng ServletContext s d ng ph ngấ ố ượ ử ụ ươ th cứ getServletContext() Có th l u đ i t ng d li u vào ServletContext.ể ư ố ượ ữ ệ
  • 50. 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)); } }
  • 51. 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>"); }}
  • 52. ContextListener Đ i t ngố ượ ContextListener đ c g i khi các sượ ọ ự ki n thi t l p và phát h y đ c g i.ệ ế ậ ủ ượ ọ initialization destruction Do v y, có th s d ng ContextListener đ th cậ ể ử ụ ể ự hi n các nhi m v thi t l p ho c k t thúc ngệ ệ ụ ế ậ ặ ế ứ d ng.ụ Đ th c hi n vi c Listener này:ể ự ệ ệ Cài đ t giao di nặ ệ ServletContextListener. Đăng ký listener v i server.ớ
  • 53. 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>