Upload
tuan-nguyen
View
2.232
Download
0
Embed Size (px)
DESCRIPTION
Lập Trình Mạng Nâng Cao - Servlet
Citation preview
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 & JavaMySpace, JavaYouTube, Flash, Python, JavaEbay, JavaAOL, 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 requestLấy thông tin từ requestXử 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 classeGenericServlet ServletInputStream ServletOutputStream
2 exception ServletException UnavailableException
Bộ thư viện Servlet
Kiến trúc Servlet
YourOwnServlet
HttpServlet
Generic Servlet
Servletservice(ServletRequest,
ServletResponse)
doGet(HttpServletRequest , HttpServletResponse)
doPost(HttpServletRequest HttpServletResponse)
doPutdoTrace
…
Vòng đời của Servlet
Browser
HTTP Request
HTTP Response
HTTPServer
Servlet Container
StaticContent
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ế HttpServlet2. Viết đè phương thức doGet()3. HttpServletRequest
getParameter("paramName")
4. HttpServletResponseThiế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>
</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");
(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 OKContent-Type: text/htmlContent-Length: 89Server: 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
serverBuffer
client
setBufferSizegetBufferSizeisComittedflushBufferresetresetBuffer
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 Countpublic 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