CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

[Java Web] Request và Response dữ liệu trong JSP Servlet

Đăng lúc: 08:10 AM - 29/01/2024 bởi Charles Chung - 831

Trong bài viết này chúng ta sẽ tìm hiểu hai đối tượng Request và Response trong JSP Servlet, các cách gửi và nhận dữ liệu từ client lên Servlet và trả về kết quả cho Client.

Giới thiệu

Trong JSP Servlet thì Servlet là thành phần xử lý các yêu cầu của client. Servlet API cung cấp hai interface uqna trọng là HttpRequestServlet và HttpResponseServlet, trong đó đối tượng thuộc kiểu HttpRequestServlet sẽ chứa dữ liệu và đảm nhiệm việc nhận dữ liệu từ client gửi lên, đối tượng thuộc kiểu HttpResponseServlet sẽ chứa dữ liệu đảm nhiệm việc trả kết quả về cho client. Các bạn có thể tham khảo luồng xử lý Request và Response trong JSP Servlet qua hình dưới đây

Một số phương thức của đối tượng Request

Method

Description

public String getParameter(String name ) This method is used to obtain the value of a parameter by its name
public String[] getParameterValues(String name)   This methods returns an array of String containing all values of given parameter name. It is mainly used for to obtain values of a Multi selected listed box.
java.util.Enumeration getParameterNames() this java.util.Enumeration getParameterNames() returns an enumeration for all of the request parameter names
public int getContentLength() Returns the size of the requested entity for the data, or a -1 if not known.
public String getCharacterEncoding() Returns the characters set encoding for the input of this current request.
public String getContentType() Returns the Internet Media Type(IMT) of the requested entity of data, or null if not known to it

Một số phương thức của đối tượng Response

Methods

Description

String getCharacterEncoding() It returns the name of the MIME charset that was used in the body of the client response.
String getContentType() It returns the response content type. e.g. text, HTML etc.
 ServletOutputStream getOutputStream() This method returns a ServletOutputStream that may be used to write binary data to the response.
PrintWriter getWriter() The PrintWriter object is used to transmit character text to the client.
void setContentLength(int len) Sets the length of the response’s content body. This function sets the HTTP Content-Length header in HTTP servlets.
void setContentType(String type) Sets the type of the response data.
void setBufferSize(int size) specifies the recommended buffer size for the response’s body.
int getBufferSize() Returns the buffer size
void flushBuffer() Any material in the buffer will be forced to be written to the client.
boolean isCommitted() If the response has been committed, this method returns a boolean.
void setLocale(Locale loc) If the answer hasn’t been committed yet, it sets the response’s location.
void reset() Clears the buffer’s data, as well as the headers and status code. To acquire a comprehensive list of ways, go here.

Ví dụ: Tạo ứng dụng Dynamic Web Project, sau đó thực hiện các thao tác gửi request dạng GET và POST tới trang JSP hoặc Servlet, sau đó nhận dữ liệu từ request và hiển thị kết quả, màn hình trang index có giao diện như sau

Bước 1: Mở Eclipse -> Tạo ứng dụng Dynamic Web Project đặt tên "JSPServletSession02"

Bước 2: Convert project sang Maven

Bước 3: Tạo các trang JSP và Servlet theo cấu trúc mô tả bên dưới

- Trang index.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<body>
	<h1>Các cách gửi dữ liệu lên Web Server trong JSP Servet</h1>
	<p>
		Kích vào link để gửi request với GET method tới trang JSP: <a
			href="productdetail.jsp?id=68">Xem chi tiết sản phẩm</a>
	</p>
	<p>
		Kích vào link để gửi request với GET method tới Servlet: <a
			href="UserServlet?id=68&role=student">Xem chi tiết người dùng</a>
	</p>
	<h3>Gửi request từ form với GET method tới Servlet</h3>
	<form action="ProductServlet" method="get">
		Nhập tên cần tìm <input type="text" name="searchname" />
		<button>Tìm</button>
	</form>
	<h3>Gửi request từ form với POST method tới Servlet</h3>
	<form action="PersonServlet" method="post">
		<table>
			<tr>
				<td>Tên đăng nhập</td>
				<td><input type="text" name="username" /></td>
			</tr>
			<tr>
				<td>Mật khẩu</td>
				<td><input type="password" name="password" /></td>
			</tr>
			<tr>
				<td>Họ và tên</td>
				<td><input type="text" name="fullname" /></td>
			</tr>
			<tr>
				<td>Ngày sinh</td>
				<td><input type="date" name="birthday" /></td>
			</tr>
			<tr>
				<td>Điện thoại</td>
				<td><input type="text" name="phone" /></td>
			</tr>
			<tr>
				<td>Địa chỉ</td>
				<td><input type="text" name="address" /></td>
			</tr>
			<tr>
				<td><button>Đăng ký</button></td>
			</tr>
		</table>
	</form>
</body>

- Trang persondtail.jsp

1
2
3
4
5
6
7
8
9
<body>
<h1>THÔNG TIN NGƯỜI DÙNG</h1>
	<p>Tên đăng nhập: ${person.username}</p>
	<p>Họ và tên: ${person.fullname}</p>
	<p>Mật khẩu: ${person.password}</p>
	<p>Ngày sinh: ${person.birthday}</p>
	<p>Địa chỉ: ${person.address}</p>
	<p>Điện thoại: ${person.phone}</p>
</body>

- Lớp bkap.entity/Person.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Person {
	private String username;
	private String password;
	private String fullname;
	private Date birthday;
	private String phone;
	private String address;
	public Person() {
		// TODO Auto-generated constructor stub
	}
	public Person(String username, String password, String fullname, Date birthday, String phone, String address) {
		super();
		this.username = username;
		this.password = password;
		this.fullname = fullname;
		this.birthday = birthday;
		this.phone = phone;
		this.address = address;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getFullname() {
		return fullname;
	}
	public void setFullname(String fullname) {
		this.fullname = fullname;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

- Lớp bkap.servlets/PersonServlet.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String fullname=request.getParameter("fullname");
		Date birthday=null;
		try {
			birthday=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthday"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String address=request.getParameter("address");
		String phone=request.getParameter("phone");		
		Person p=new Person(username, password, fullname, birthday, phone, address);
		request.setAttribute("person", p);
		request.getRequestDispatcher("persondetail.jsp").forward(request, response);
	}

- Lớp bkap.servlets/ProductServlet.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		out.println("<html><head><title>Thông tin sản phẩm</title></head>");
		out.println("<body>");
		out.println("<h1>Bạn tìm sản phẩm có từ khóa: "+ request.getParameter("searchname")+"</h1>");
		out.println("</body>");
		out.println("</html>");
	}

- Lớp bkap.servlets/UserServlet.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		out.println("<html><head><title>Thông tin người dùng</title></head>");
		out.println("<body>");
		out.println("<h1>Mã số: "+ request.getParameter("id")+"</h1>");
		out.println("<h1>Vai trò: "+ request.getParameter("role")+"</h1>");
		out.println("</body>");
		out.println("</html>");
	}

Bước 4: Run và xem kết quả

Link tải source code

Video demo

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ