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.ụ
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
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
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, …
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()
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ậ ữ ệ ừ ươ ứ
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
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));
}
}
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>