The basic concept of Java Bean and the use of Bean in JSP
In the process of software development, business logic and presentation layer should be separated as far as possible, so as to achieve complete decoupling, which is the basic concept of software layered design. In JSP, Java beans are often used to realize the core business logic, and JSP pages are used in the presentation layer.
Features of Java Bean:
Support reflection mechanism: the reflection mechanism can be used to analyze how Java beans run.
Support event: event is a simple communication mechanism, which can be used to notify Java beans of corresponding information.
Support attributes: you can customize attributes and use standard tags to interact with JSP pages.
Support persistence: persistence means that Java beans can be saved and reloaded when needed.
Specifications to be followed:
The Java Bean class must be a public class.
The method provided to the JSP page call must be given public access permission.
The properties in the Java Bean class must provide public get and set methods for JSP page calls.
You must have a constructor without parameters.
In JSP pages, to correctly use beans, you should pay attention to the following three problems:
The Bean class is defined according to the specification, and the corresponding get and set methods of class properties are given.
Import the corresponding Bean class in the page.
Using in JSP pages
<
<
<jsp:useBean
>
>
>Tags use Bean classes
Two methods of Bean class deployment;
One is to deploy the Bean's Class file in the public directory of the Web server.
The other is to deploy the Class file in the directory of a specific project on the Web server. For example, ch09\web\WEB-INF\classes\com\eshore\pojo\User.class.
Scope of Bean:
The default is the Page range, that is, the Bean is valid on the current Page. When request is set, it indicates that the Bean is valid for the current request of the current user. When set to session, it means that the Bean is valid within the session range of the current user. When it is set to application, it means that the Bean is valid for all pages of the system, but refreshing the current interface is not an application.
Accessing Bean properties
Set Bean properties directly with expressions:
package com.eshore.pojo; import java.io.Serializable; public class Product implements Serializable{ private static final long serialVersionUID = 1L; private String product_id; //product ID private String product_name; //Product name private double price; //product price private String info; //Product information public Product() { //Nonparametric construction method } public String getProduct_id() { return product_id; } public void setProduct_id(String productId) { product_id = productId; } public String getProduct_name() { return product_name; } public void setProduct_name(String productName) { product_name = productName; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="product" class="com.eshore.pojo.Product" scope="page"/> <!DOCTYPE HTML > <html> <head> <title>set up Bean attribute</title> </head> <body> <!-- Set product name --> <jsp:setProperty name="product" property="product_name" value="struts Development tutorial"/> <br/>The product name is: <!-- Get product name --> <%--<%=product.getProduct_name() %>--%> <jsp:getProperty name="product" property="product_name"></jsp:getProperty> <!-- Set product number --> <jsp:setProperty name="product" property="product_id" value="111100123689"/> <br/>The product number is: <!-- Get product number --> <%--<%=product.getProduct_id() %>--%> <jsp:getProperty name="product" property="product_id"></jsp:getProperty> <!-- Set product price --> <% double price = 68.23; %> <jsp:setProperty name="product" property="price" value="<%=price+23.67 %>"/> <br/>The product price is: <!-- Get product price --> <%--<%=product.getPrice() %>--%> <jsp:getProperty name="product" property="price"></jsp:getProperty> <!-- Set product information --> <jsp:setProperty name="product" property="info" value="Struts Development tutorial is an introduction to how to use Struts Professional books......"/> <br/>The product information is: <!-- Get product information --> <%--<%=product.getInfo() %>--%> <jsp:getProperty name="product" property="info"></jsp:getProperty> </body> </html>
Set the Bean attribute value through the form parameter name:
Note to add the Tomacat package:
<%@ page language="java" import="java.util.*,com.eshore.pojo.Product" pageEncoding="UTF-8"%> <!-- Set parameter code --> <% request.setCharacterEncoding("UTF-8"); %> <!-- Import referenced bean --> <jsp:useBean id="product" class="com.eshore.pojo.Product" scope="page"/> <!DOCTYPE HTML > <html> <head> <title>Through form parameter setting Bean Attribute value</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> <form action="" method="post"> <br> Enter product name:<input name="product_name"/><br/> Enter product number:<input name="product_id"/><br/> Enter product price:<input name="price"/><br/> Enter product information:<input name="info"/><br/> <input type="submit" value="Submit"/> </form> <!-- set up product Attribute value for --> <jsp:setProperty property="*" name="product"/> <br/>The product name is: <!-- Get product name --> <%=product.getProduct_name() %> <br/>The product number is: <!-- Get product number --> <%=product.getProduct_id() %> <br/>The product price is: <!-- Get product price --> <%=product.getPrice() %> <br/>The product information is: <!-- Get product information --> <%=product.getInfo() %> </body> </html>
Set the Bean attribute value through the form parameter value:
<%@ page language="java" import="java.util.*,com.eshore.pojo.Product" pageEncoding="UTF-8"%> <!-- Set parameter code --> <% request.setCharacterEncoding("UTF-8"); %> <!-- Import referenced bean --> <jsp:useBean id="product" class="com.eshore.pojo.Product" scope="page"/> <!DOCTYPE HTML > <html> <head> <title>Set by form parameter value Bean Attribute value</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> <form action="" method="post"> <br> Enter product name:<input name="product_name1"/><br/> Enter product number:<input name="product_id1"/><br/> Enter product price:<input name="price1"/><br/> Enter product information:<input name="info1"/><br/> <input type="submit" value="Submit"/> </form> <!-- Set product name --> <jsp:setProperty name="product" property="product_name" param="product_name1"/> <br/>The product name is: <!-- Get product name --> <%=product.getProduct_name() %> <!-- Set product number --> <jsp:setProperty name="product" property="product_id" param="product_id1"/> <br/>The product number is: <!-- Get product number --> <%=product.getProduct_id() %> <!-- Set product price --> <jsp:setProperty name="product" property="price" param="price1"/> <br/>The product price is: <!-- Get product price --> <%=product.getPrice() %> <!-- Set product information --> <jsp:setProperty name="product" property="info" param="info1"/> <br/>The product information is: <!-- Get product information --> <%=product.getInfo() %> </body> </html>
Get properties: < < <jsp:getProperty > > >. There are examples in example 9.1.
Scope of Bean
request lifecycle of Bean
package com.eshore.pojo; import java.io.Serializable; public class Circle implements Serializable{ private static final long serialVersionUID = 1L; private double radius =1.0d; //radius private double circleArea = 0.0d; //Circular area private double circumference=0.0d; //Circumference public Circle() { //Parameter free construction method super(); // TODO Auto-generated constructor stub } //Property public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public double getCircleArea() { circleArea = Math.PI*radius*radius;//Set circle area return circleArea; } public void setCircleArea(double circleArea) { this.circleArea = circleArea; } public double getCircumference() { circumference = 2*Math.PI*radius;//Set circumference return circumference; } public void setCircumference(double circumference) { this.circumference = circumference; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="request"/> <!DOCTYPE HTML > <html> <head> <title>test scope by request</title> </head> <% //Get the circle radius obtained from the page. If not, the default is 1 String radius = request.getParameter("radius"); if(radius==null||radius.equals("")){ radius = "1"; } double rad = Double.parseDouble(radius); //Set circle radius circle.setRadius(rad); %> <body> <form action="" method="post"> Please enter the radius of the circle:<input name="radius"/><br/> <input type="submit" value="Submit"/><br/> Should Bean Class objects are:<%=circle.toString()%><br/> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> </form> </body> </html>
When request is set, it indicates that the Bean is valid for the current request of the current user.
Demonstrate the Page life cycle of a Bean:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="page"/> <!DOCTYPE HTML > <html> <head> <title>test scope by page</title> </head> <body> pageScope.jsp Page information:<br/> Should Bean Class objects are:<%=circle.toString()%><br/> Set this Bean The radius of the is 20: <% circle.setRadius(20); %> <!-- obtain Bean The property value of the Bean Valid only on current page --> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> <!-- Jump pageScope2.jsp page --> <form action="pageScope2.jsp" method="get"> <input type="submit" value="Jump pageScope2.jsp page"/><br/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="page"/> <!DOCTYPE HTML > <html> <head> <title>test scope by page</title> </head> <body> pageScope2.jsp Page information:<br/> Should Bean Class objects are:<%=circle.toString()%><br/> <!--The radius here is circle Class because the Bean Valid only on current page--> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> </body> </html>
Demonstrate the session lifecycle of a Bean:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="session"/> <!DOCTYPE HTML > <html> <head> <title>test scope by session</title> </head> <body> sessionScope.jsp Page information:<br/> Should Bean Class objects are:<%=circle.toString()%><br/> .toString()%><br/> Set this Bean The radius of the is 20: <% circle.setRadius(20); %> <!-- obtain Bean Attribute value for --> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> <!-- Jump sessionScope2.jsp page --> <form action="sessionScope2.jsp" method="get"> <input type="submit" value="Jump sessionScope2.jsp page"/><br/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="session"/> <!DOCTYPE HTML > <html> <head> <title>test scope by session</title> </head> <body> sessionScope2.jsp Page information:<br/> Should Bean Class objects are:<%=circle.toString()%><br/> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> </body> </html>
Although it jumps to the page, it is in the same session.
Demonstrate the application life cycle of Bean:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- Import referenced bean --> <jsp:useBean id="circle" class="com.eshore.pojo.Circle" scope="application"/> <!DOCTYPE HTML > <html> <head> <title>test scope by application</title> </head> <body> applicationScope.jsp Page information:<br/> application visit Bean Class objects are:<%=circle.toString()%><br/> obtain Bean Radius of:<jsp:getProperty property="radius" name="circle"/><br/> Set this Bean The radius of the is 30: <% circle.setRadius(30); %> <%--<jsp:setProperty name="circle2" property="radius" value="30"/>--%> <!-- obtain Bean Attribute value for --> <br/>The radius of the circle is:<jsp:getProperty property="radius" name="circle"/> <br/>The circumference of the circle is:<jsp:getProperty property="circumference" name="circle"/> <br/>The area of the circle is:<jsp:getProperty property="circleArea" name="circle"/> </body> </html>
Refresh the interface and find that the changes have been retained:
DAO design pattern
First create the table:
Create a db package under which a DBConnection class is established to establish a connection pool:
package com.eshore.db; import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { //Load the fixed Driver and URL of MySQL database. Mydb is the database where I build tables private static final String Driver = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/mydb"; private static final String USER = "root"; private static final String PASSWORD = "1234"; private Connection conn = null; public DBConnection() throws Exception { //Make a database connection try { Class.forName(Driver); //Loading database drivers with reflection this.conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (Exception e) { throw e; // Throw exception } } public Connection getConnection() { return this.conn; // Get database connection } public void close() throws Exception { // close database if (this.conn != null) { try { this.conn.close(); } catch (Exception e) { throw e; } } } }
Design DAO interface classes, create DAO packages, and create ProductDao classes:
package com.eshore.dao; import java.util.List; import com.eshore.pojo.Product; public interface ProductDao { /** *New data in database *@param product Data object to add *@return Add successful flag *@throws Exception If there is an exception, it will be thrown directly */ public boolean addProduct(Product product)throws Exception ; /** *Query all Product data *@param product_name Product name *@return All query results are returned. Each product represents a row of records in the table *@throws Exception If there is an exception, it will be thrown directly */ public List<Product> findAll(String product_name)throws Exception; /** * Query products according to product number *@param product_id Product number *@return vo object of the product *@throws Exception If there is an exception, it will be thrown directly */ public Product findByProductId(String product_id)throws Exception; }
Data operation implementation class, create ProductDaoImpl class in DAO:
package com.eshore.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.eshore.pojo.Product; public class ProductDaoImpl implements ProductDao { private Connection conn = null; // Database connection object private PreparedStatement pstmt = null; // Database operation object // Get the link of the database through the construction method public ProductDaoImpl(Connection conn) { this.conn = conn; } public boolean addProduct(Product product) throws Exception { boolean flag = false; // Define identity String sql = "insert into product(product_id,product_name,price,info) values(?,?,?,?)"; this.pstmt = this.conn.prepareStatement(sql);// Instantiate the PrepareStatement object this.pstmt.setString(1,product.getProduct_id());// Set product id this.pstmt.setString(2,product.getProduct_name());// Set product name this.pstmt.setDouble(3, product.getPrice());// Set product price this.pstmt.setString(4,product.getInfo());// Set product information if (this.pstmt.executeUpdate() > 0) { // The number of rows of the update record is greater than 0 flag = true; //Modification identification } this.pstmt.close(); // Close the PreparedStatement operation return flag; } public List<Product> findAll(String product_name) throws Exception { List<Product> list = new ArrayList<Product>();// Define a collection and receive the returned data String sql = "select product_id,product_name,price,info from product "; if(product_name!=null&&!"".equals(product_name)){ sql = "select product_id,product_name,price,info from product where product_name like? "; this.pstmt = this.conn.prepareStatement(sql);// Instantiate PreparedStatement this.pstmt.setString(1, "%" + product_name + "%");// Set the name of the product query }else{ this.pstmt = this.conn.prepareStatement(sql);// Instantiate PreparedStatement } ResultSet rs = this.pstmt.executeQuery();// Execute query operation Product product = null; while (rs.next()) { product = new Product();// Instantiate a new product object product.setProduct_id(rs.getString(1)); product.setProduct_name(rs.getString(2)); product.setPrice(rs.getDouble(3)); product.setInfo(rs.getString(4)); list.add(product); // Add a product object to the collection } this.pstmt.close(); return list; // Return all results } public Product findByProductId(String product_id) throws Exception { Product product = null; String sql = "select product_id,product_name,price,info from product where product_id=?"; this.pstmt = this.conn.prepareStatement(sql); this.pstmt.setString(1, product_id); // Set product number ResultSet rs = this.pstmt.executeQuery(); if (rs.next()) { product = new Product(); product.setProduct_id(rs.getString(1)); product.setProduct_name(rs.getString(2)); product.setPrice(rs.getDouble(3)); product.setInfo(rs.getString(4)); } this.pstmt.close(); return product; // If the query result is not found, null is returned, and the default value is null } }
In the data operation implementation class in the above code, there is no opening and connecting operation for the database, but the connected database is obtained by the construction method. The opening and closing of the database is completed by the business operation implementation class, and a service package is established, under which a ProductService class is established:
package com.eshore.service; import java.util.List; import com.eshore.dao.ProductDao; import com.eshore.dao.ProductDaoImpl; import com.eshore.db.DBConnection; import com.eshore.pojo.Product; public class ProductService implements ProductDao{ private DBConnection dbconn = null; // Define database connection classes private ProductDao dao = null; // Declare DAO objects // Instantiate the database connection and dao object in the construction method public ProductService() throws Exception { this.dbconn = new DBConnection(); this.dao = new ProductDaoImpl(this.dbconn.getConnection());// Instantiate the implementation class of ProductDao } public boolean addProduct(Product product) throws Exception { boolean flag = false; // identification try { if (this.dao.findByProductId(product.getProduct_id()) == null) {// If the inserted product number does not exist flag = this.dao.addProduct(product);// Add a new product information } } catch (Exception e) { throw e; } finally { this.dbconn.close(); } return flag; } public List<Product> findAll(String keyWord) throws Exception { List<Product> all = null; // Define the collection returned by the product try { all = this.dao.findAll(keyWord);// Call implementation method } catch (Exception e) { throw e; } finally { this.dbconn.close(); } return all; } public Product findByProductId(String product_id) throws Exception { Product product = null; try { product = this.dao.findByProductId(product_id); } catch (Exception e) { throw e; } finally { this.dbconn.close(); } return product; } }
Define the DAO factory class to obtain the business operation class. In subsequent clients, you can directly obtain the instance object of the DAO interface through the factory class, establish the factory package, and establish the DAOFactory class under the package:
package com.eshore.factory; import com.eshore.dao.ProductDao; import com.eshore.service.ProductService; public class DAOFactory { public static ProductDao getIEmpDAOInstance()throws Exception { return new ProductService();//Get business operation class } }
Add product class TestInsertProduct to the test:
package com.eshore.test; import com.eshore.factory.DAOFactory; import com.eshore.pojo.Product; public class TestInsertProduct { public static void main(String[] args){ Product product = null; try{ for(int i=0;i<5;i++){ product = new Product(); product.setProduct_id("350115001010"+i); product.setProduct_name("Water cup"+i); product.setPrice(100+i); product.setInfo("This is a beautiful quilt"+i); DAOFactory.getIEmpDAOInstance().addProduct(product); } }catch(Exception e){ e.printStackTrace(); e.printStackTrace(); } } }
Java program to run the test:
Calling DAO in JSP
Add product information in JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML > <html> <head> <title>Add product information</title> </head> <body> <form action="product_insert.jsp" method="post"> Product No.:<input name="product_id"/><br> Product Name:<input name="product_name"/><br> Product price:<input name="price"/><br> Product information:<textarea rows="" cols="" name="info"></textarea><br/> <input type="submit" value="add to"> <input type="reset" value="Reset"> </form> </body> </html>
<%@ page import="java.util.*,com.eshore.pojo.Product" pageEncoding="UTF-8"%> <%@ page import="com.eshore.factory.DAOFactory" %> <% request.setCharacterEncoding("utf-8");//Solve Chinese garbled code %> <!DOCTYPE HTML > <html> <head> <title>Execute add product</title> </head> <body> <% Product product = new Product(); //Instantiate Product object product.setProduct_id(request.getParameter("product_id")); product.setProduct_name(request.getParameter("product_name")); product.setPrice(Double.parseDouble(request.getParameter("price"))); product.setInfo(request.getParameter("info")); boolean flag = DAOFactory.getIEmpDAOInstance(). addProduct(product); //Perform the add operation if(flag){ %> <h4>Product information added successfully</h4> <% }else{ %> <h4>Failed to add product information</h4> <%} %> </body> </html>
Query product information in JSP:
<%@ page import="java.util.*,com.eshore.pojo.Product" pageEncoding="UTF-8"%> <%@ page import="com.eshore.factory.DAOFactory" %> <% request.setCharacterEncoding("utf-8");//Solve Chinese garbled code %> <!DOCTYPE HTML > <html> <head> <title>Query product list</title> </head> <body> <% String product_name = request.getParameter("product_name");// List<Product> list = DAOFactory.getIEmpDAOInstance().findAll(product_name); %> <form action="product_list.jsp" method="post"> Please enter product name:<input name="product_name"/> <input type="submit" value="Submit"> </form> <table border="1"> <tr> <td>Product number</td> <td>Product name</td> <td>product price</td> <td>Product information</td> </tr> <% for(int i=0;i<list.size();i++){ Product p = list.get(i); //Take out each product %> <tr> <td><%=p.getProduct_id() %></td> <td><%=p.getProduct_name() %></td> <td><%=p.getPrice() %></td> <td><%=p.getInfo() %></td> </tr> <%} %> </table> </body> </html>