Bài giảng Công nghệ Java - Bài 2: Servlet - Nguyễn Hữu Thể

Nội dung

▪ Servlet and Architecture

▪ Interface Servlet and the Servlet Life Cycle

▪ HttpServlet Class

▪ HttpServletRequest Interface

▪ HttpServletResponse Interface

▪ Project Servlet in Eclipse

▪ HTTP get Requests

▪ HTTP get Requests Containing Data

▪ HTTP post Requests

▪ Redirecting Requests to Other Resources

▪ Welcome Files

pdf 41 trang yennguyen 1240
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Công nghệ Java - Bài 2: Servlet - Nguyễn Hữu Thể", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

Tóm tắt nội dung tài liệu: Bài giảng Công nghệ Java - Bài 2: Servlet - Nguyễn Hữu Thể

Bài giảng Công nghệ Java - Bài 2: Servlet - Nguyễn Hữu Thể
1CÔNG NGHỆ JAVA
Bài 2: Servlet
Nguyễn Hữu Thể
2Nội dung
▪ Servlet and Architecture
▪ Interface Servlet and the Servlet Life Cycle
▪ HttpServlet Class
▪ HttpServletRequest Interface 
▪ HttpServletResponse Interface 
▪ Project Servlet in Eclipse
▪ HTTP get Requests
▪ HTTP get Requests Containing Data 
▪ HTTP post Requests 
▪ Redirecting Requests to Other Resources 
▪ Welcome Files
3Servlet and Architecture
− Servlets: chạy trên Web server hoặc Application server.
− Tầng trung gian giữa HTTP Client với các Database hoặc các 
ứng dụng trên HTTP server.
− Ưu điểm Servlets:
▪ Hiệu năng tốt. Tính bảo mật cao (dựa trên Java). Độc lập trên nền tảng.
▪ Thư viện Java, giao tiếp với Applet, Database hoặc phần mềm khác.
4Servlet Package
− Java Servlets sử dụng các lớp Java => Run bởi Web Server.
− Các gói thư viện hỗ trợ:
▪ javax.servlet 
▪ javax.servlet.http
− Servlet được biên dịch giống như các lớp khác trong Java. 
− Các interface và các lớp trong API Servlet 
▪ Servlet, 
▪ GenericServlet, 
▪ HttpServlet, 
▪ ServletRequest, 
▪ ServletResponse, 
5Servlet Life Cycle
1. Servlet được khởi tạo bằng cách gọi phương thức init()
2. Phương thức service() được gọi để xử lý yêu cầu của client.
3. Servlet được hủy bằng phương thức destroy()
4. Cuối cùng, servlet được thu thập bởi bộ sưu tập rác của JVM.
6Interface Servlet
Method Description
public void init(ServletConfig config)
initializes the servlet. It is the life 
cycle method of servlet and 
invoked by the web container only 
once.
public void service(ServletRequest 
request,ServletResponse response)
provides response for the incoming 
request. It is invoked at each 
request by the web container.
public void destroy()
is invoked only once and indicates 
that servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo()
returns information about servlet 
such as writer, copyright, version 
etc.
7Method Detail – init()
public void init(ServletConfig config) throws ServletException 
▪ Phương thức init() được gọi chỉ một lần để khởi tạo servlet.
▪ Khi gọi servlet, một thể hiện duy nhất của mỗi servlet sẽ 
được tạo ra, với mỗi yêu cầu của người dùng tạo ra một 
luồng mới được trao cho doGet hoặc doPost. 
▪ Parameters: 
• config - a ServletConfig object containing the servlet's 
configuration and initialization parameters 
8Method Detail – service()
public void service(ServletRequest req, ServletResponse res) 
throws ServletException, java.io.IOException 
▪ Phương thức chính để thực hiện nhiệm vụ. Web server gọi 
phương thức service() để xử lý các yêu cầu đến từ client và trả 
về kết quả.
▪ Máy chủ tạo ra 1 Thread mới khi nhận được 1 yêu cầu cho 1
servlet, và gọi phương thức service(). 
▪ Phương thức service() kiểm tra kiểu yêu cầu HTTP (GET, 
POST, PUT, DELETE, v.v.) và gọi các phương thức doGet, 
doPost, doPut, doDelete,...
▪ Parameters: 
• req - the ServletRequest object that contains the client's request 
• res - the ServletResponse object that contains the servlet's response 
9Method Detail – getServletConfig()
public ServletConfig getServletConfig() 
▪ Returns a ServletConfig object, which contains 
initialization and startup parameters for this servlet. 
▪ Returns: 
• the ServletConfig object that initializes this servlet
10
Method Detail – getServletInfo()
public java.lang.String getServletInfo() 
▪ Returns information about the servlet, such as author, 
version, and copyright. 
▪ The string that this method returns should be plain text and 
not markup of any kind (such as HTML, XML, etc.).
▪ Returns: 
• a String containing servlet information
11
Method Detail - destroy
public void destroy() 
▪ Chỉ được gọi một lần ở giai đoạn cuối trong vòng đời 
Servlet. 
▪ Giúp servlet đóng các kết nối tới Database, dừng thread,
thực hiện các hoạt động cleanup.
▪ Sau khi destroy() được gọi, đối tượng servlet này được 
đánh dấu cho Garbage Collector.
12
HttpServlet Class
− Servlets kế thừa từ lớp HttpServlet. 
− Hai loại HTTP requests phổ biến nhất là get và post. 
− Lớp HttpServlet định nghĩa phương thức doGet và doPost để 
respond và requests từ client. 
− Được gọi bởi servlet container khi request đến server. 
13
HttpServlet Class
public abstract class HttpServlet extends GenericServlet 
implements java.io.Serializable
− Cung cấp lớp trừu tượng để tạo một HTTP servlet phù hợp.
− Lớp con của HTTPServlet phải ghi đè ít nhất một trong các 
phương thức sau:
▪ doGet, nếu servlet hỗ trợ HTTP GET requests 
▪ doPost, cho HTTP POST requests 
▪ doPut, cho HTTP PUT requests 
▪ doDelete, cho HTTP DELETE requests 
▪ init và destroy, để quản lý tài nguyên được giữ
▪ getServletInfo: servlet cung cấp thông tin về chính nó
14
HttpServlet Class
Method Summary
protected voiddoDelete(HttpServletRequest req, HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a DELETE request.
protected voiddoGet(HttpServletRequest req, HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a GET request.
protected voiddoHead(HttpServletRequest req, HttpServletResponse resp) 
Receives an HTTP HEAD request from the protected 
service method and handles the request.
protected voiddoOptions(HttpServletRequest req, 
HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a OPTIONS request.
protected voiddoPost(HttpServletRequest req, HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a POST request.
15
HttpServlet Class
Method Summary
protected voiddoPut(HttpServletRequest req, HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a PUT request.
protected voiddoTrace(HttpServletRequest req, HttpServletResponse resp) 
Called by the server (via the service method) to allow a 
servlet to handle a TRACE request.
protected longgetLastModified(HttpServletRequest req) 
Returns the time the HttpServletRequest object was last 
modified, in milliseconds since midnight January 1, 1970
protected voidservice(HttpServletRequest req, HttpServletResponse resp) 
Receives standard HTTP requests from the public 
service method and dispatches them to the doXXX methods 
defined in this class.
voidservice(ServletRequest req, ServletResponse res) 
Dispatches client requests to the protected service 
method.
16
HttpServletRequest Interface
− String getParameter( String name )
▪ Value of a parameter sent to the servlet as part of a get or 
post request. The name argument represents the parameter 
name.
− Enumeration getParameterNames()
▪ Returns the names of all the parameters sent to the servlet 
as part of a post request.
− String[] getParameterValues( String name )
▪ For a parameter with multiple values, this method returns 
an array of strings containing the values for a specified 
servlet parameter.
− Cookie[] getCookies()
▪ Returns an array of Cookie objects stored on the client by 
the server. Cookie objects can be used to uniquely identify
clients to the servlet.
17
HttpServletRequest Interface 
− HttpSession getSession( boolean create )
▪ Returns an HttpSession object associated with the client's 
current browsing session. 
− String getLocalName()
▪ Gets the host name on which the request was received.
− String getLocalAddr()
▪ Gets the Internet Protocol (IP) address on which the request 
was received.
− int getLocalPort()
▪ Gets the Internet Protocol (IP) port number on which the 
request was received.
18
HttpServletResponse Interface 
− void addCookie( Cookie cookie )
▪ Add a Cookie to the header of the response to the client. 
− ServletOutputStream getOutputStream()
▪ Obtains a byte-based output stream for sending binary data 
to the client.
− PrintWriter getWriter()
▪ Obtains a character-based output stream for sending text 
data (usually HTML formatted text) to the client.
19
HttpServletResponse Interface 
− void setContentType( String type )
▪ Specifies the content type of the response to the browser. 
▪ For examples, content type "text/html", "image/gif",... 
− String getContentType()
▪ Gets the content type of the response.
20
Project Servlet trong Eclipse
21
Project Servlet trong Eclipse
− File WelcomeServlet.java sau khi biên dịch thành file 
WelcomeServlet.class được lưu trong thư mục build/class/
22
Project Servlet trong Eclipse
− Class java lưu trong thư mục src
23
Project Servlet trong Eclipse
− Trang html, jsp lưu trong thư mục WebContent
24
Project Servlet trong Eclipse
− File web.xml lưu trong thư mục WEB-INF
25
Project Servlet trong Eclipse
− Run: right click file html / Run as/ Run on Server
26
HTTP get Requests
− HTTP get request is to retrieve the content of a URL. 
public class WelcomeServlet extends HttpServlet 
{ 
// process "get" requests from clients 
protected void doGet( HttpServletRequest request, 
HttpServletResponse response ) throws 
ServletException, IOException {
//
}
} 
27
HTTP get Requests
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
public WelcomeServlet() { // }
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("A Simple Servlet Example");
out.println("");
out.println("");
out.println("Welcome to Servlets!");
out.println("");
out.println("");
out.close();} 
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
HTTP get Requests
WelcomeServlet.java
28
HTTP get Requests
WelcomeServlet.class
29
Web.xml
30
HTTP get Requests Containing Data 
import java.io.*;
import javax.*;
import javax.servlet.*;
@WebServlet("/WelcomeServlet2")
public class WelcomeServlet2 extends HttpServlet {
public WelcomeServlet2() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {
String firstName = request.getParameter("firstname");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("Processing get requests with data");
out.println("");
out.println("");
out.println("Hello " + firstName + ",");
out.println("Welcome to Servlets!");
out.println("");
out.println("");
out.close(); 
}
}
31
HTTP get Requests Containing Data 
32
HTTP get Requests Containing Data 
33
web.xml 
34
HTTP post Requests 
import java.io.*;
import javax.*;
import javax.servlet.*;
@WebServlet("/WelcomeServlet3")
public class WelcomeServlet3 extends HttpServlet {
public WelcomeServlet3() { super(); }
protected void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {
String firstName = request.getParameter( "firstname" ); 
response.setContentType( "text/html" );
PrintWriter out = response.getWriter(); 
out.println( "" ); 
out.println( "" );
out.println( "Processing post requests with data" );
out.println( "" );
out.println( "" );
out.println( "Hello " + firstName + "," );
out.println( "Welcome to Servlets!" );
out.println( "" );
out.println( "" );
out.close(); 
} 
}
HTTP post Requests 
35
HTTP post Requests 
36
Redirecting Requests to Other Resources 
37
Redirecting Requests to Other Resources 
38
Redirecting Requests to Other Resources 
39
Welcome Files
− Welcome files to be loaded when the request URL is not mapped 
to a servlet. 
− These files are typically HTML or JSP. 
− Welcome files are defined using the welcome-file-list. 
− welcome-file-list contains one or more welcome-file. 
− The following welcome-file-list element indicates that 
index.html and index.htm.
index.html 
index.htm 
40
Welcome Files
41
Welcome Files

File đính kèm:

  • pdfbai_giang_cong_nghe_java_bai_2_servlet_nguyen_huu_the.pdf