Sử dụng thẻ jsp:useBean trong jsp!

Sử dụng thẻ này sẽ tiết kiện rất nhiều thời gian trong việc viết code nếu đối tượng nhiều thuộc tính.
(Lưu ý đặc biệt quan trọng khi sử dụng thẻ này là các thuộc tính của lớp thực thể phải giống “name” trong các thẻ jsp)
Ví dụ:

Lớp thực thể:

package entity;
public class Details {
	public Details() {
    }
    private String username;
    private int age;
    private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

Jsp:



<html>
<head><title>
useBean, getProperty and setProperty example
</title></head>
<form action="userdetails.jsp" method="post"> 
User Name: <input type="text" name="username"><br> 
<!--name này phải giống thuộc tính lớp thực thể-->
User Password: <input type="password" name="password"><br> 
User Age: <input type="text" name="age"><br> 
<input type="submit" value="register"> 
</form> 
</html>


Sử dụng thẻ jsp:useBean (userdetails.jsp)



<jsp:useBean id="userinfo" class="entity.Details"></jsp:useBean>
 <!--id của thẻ jsp:useBean này phải giống name với các thẻ jsp:setProperty,
jsp:getProperty, nó đại hiện cho lớp thực thể Details. * là set/get hết các thuộc tính-->
<jsp:setProperty property="*" name="userinfo"/> <!--setProperty * thì lớp thực thể 
đã được set toàn bộ dữ liệu trong đối tượng (userinfo) từ giao diện nhập vào.-->
You have enterted below details:<br> 
<jsp:getProperty property="username" name="userinfo"/><br> <!--Lấy dữ liệu ra-->
<jsp:getProperty property="password" name="userinfo"/><br> 
<jsp:getProperty property="age" name="userinfo" /><br>


Input:
https://i0.wp.com/beginnersbook.com/wp-content/uploads/2013/11/useBean-output1.png
Output:
https://i0.wp.com/beginnersbook.com/wp-content/uploads/2013/11/useBean-output2.png