54
Servlet ThS Văn Thiên Hoàng

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

Embed Size (px)

DESCRIPTION

Lập Trình Mạng Nâng Cao - Servlet

Citation preview

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

Servlet

ThS Văn Thiên Hoàng

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

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.

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

Servlet trong kiến trúc J2EE

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

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

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

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); }}

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

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.

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

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, …

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

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

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

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

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

Bộ thư viện Servlet

3 classeGenericServlet ServletInputStream ServletOutputStream

2 exception ServletException UnavailableException

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

Bộ thư viện Servlet

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

Kiến trúc Servlet

YourOwnServlet

HttpServlet

Generic Servlet

Servletservice(ServletRequest,

ServletResponse)

doGet(HttpServletRequest , HttpServletResponse)

doPost(HttpServletRequest HttpServletResponse)

doPutdoTrace

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

Vòng đời của Servlet

Browser

HTTP Request

HTTP Response

HTTPServer

Servlet Container

StaticContent

Servlet

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

Vòng đời của Servlet

GET index.html HTTP/1.0

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

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.

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

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

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

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

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

Lấy thông tin từ truy vấn - Request

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

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

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

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, …

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

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>");

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

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); }}}

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

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).

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

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

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

<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!

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

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()

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

<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

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

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

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

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)

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

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

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

Gởi trả dữ liệu về Client - Response

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

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<

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

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.

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

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.

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

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ó.

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

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

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

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

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

Bộ đệm đáp của đối tượng Response

Servlet

serverBuffer

client

setBufferSizegetBufferSizeisComittedflushBufferresetresetBuffer

request

response

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

Một số phương thức hỗ trợ HTTP

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

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.

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

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 đè.

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

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

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

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

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

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) ).

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

<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

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

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

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

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.

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

The Servlet Context

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

Đố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.

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

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)); }}

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

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>");}}

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

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.

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

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>

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

Câu hỏi