当前位置:网站首页>User defined MVC usage & addition, deletion, modification and query

User defined MVC usage & addition, deletion, modification and query

2022-07-23 11:27:00 _ Leaf1217

Catalog

One 、 Configure customization MVC Environmental Science

Two 、 Compilation of general additions, deletions and modifications

3、 ... and 、 To write Dao Method layer

Four 、 To write Action Receive requests and process

5、 ... and 、 Configuration framework xml file

6、 ... and 、 The front-end code


One 、 Configure customization MVC Environmental Science

In the previous articles, we have built our own MVC frame ,

In this article, let's configure and use it together !

1.1  hold MVC The relevant code is marked jar package

choice mvc Right click the relevant package --->Export---> Search for java---> choice JAR File--->Next

Browse Choose the directory you want to save and name it --->Finish Just fine

1.2  Import the project

We then put the generated jar Import the package into the new project ---> And import the relevant dependent packages ---> Then import the relevant files of our paging tags and helper classes ;

---> Create another source folder :Source Folder

---> stay conf The configuration file of the frame is placed in the folder Leaf.xml---> And then web.xml The file configuration is good :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>J2EE_mvc_crud</display-name>
  <servlet>
  	<servlet-name>mvc</servlet-name>
  	<servlet-class>com.leaf.mvc.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>configLocation</param-name>
  		<param-value>/Leaf.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

---> Finally, we will put those tool classes we have written before, such as PageBean、BeasDao And so on ;

After this step, our environment configuration is completed ! You can start entity classes and Dao Layer is written ~~~ 


Two 、 Compilation of general additions, deletions and modifications

The entity class has three attributes :bid、bname、price, Write simple , There's not much to explain here , Put the code directly :

Entity class :Book--->

package com.leaf.entity;

/**
 *  Entity class : Books 
 * @author Leaf
 *
 * 2022 year 6 month 21 Japan   Afternoon 6:39:18
 */
public class Book {
	
	private int bid;// Book number 
	private String bname;// Book name 
	private float price;// Book price 

	public int getBid() {
		return bid;
	}

	public void setBid(int bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}
	
	public Book() {

	}
	public Book(int bid, String bname, float price) {
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}
	
}

Let's start writing a general tool class for adding, deleting and modifying :

	/**
	 *  Additions and deletions 
	 * @param sql SQL sentence 
	 * @param t  Generic , Put the corresponding entity class .
	 * @param attrs  Property name 
	 * @return  Number of rows affected 
	 * @throws Exception  Exception thrown 
	 */
	public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
		Connection con = DBHelper.getConnection();
		PreparedStatement ps = con.prepareStatement(sql);
		// take t The corresponding value of an attribute of is added to ps In the object 
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			// Open access 
			f.setAccessible(true);
			ps.setObject(i + 1, f.get(t));
		}
		return ps.executeUpdate();
	}

above attrs Array passing is the related attributes of the entity class to be operated ;

Common tool classes are encapsulated and repeated 、 Code that can be shared ,

It greatly reduces the amount of code we develop later 、 Improve development efficiency .


3、 ... and 、 To write Dao Method layer

When our general additions, deletions, modifications and queries are encapsulated, we can start to write our database access layer ,

For the general method of paging query, please refer to my article : General query & Paging code __Leaf1217 The blog of -CSDN Blog _ Query code

We encapsulate duplicate code into common tool classes , After writing the general addition, deletion, modification and search method, the code is simplified ,

Put the code here :

package com.leaf.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.leaf.entity.Book;
import com.leaf.util.BaseDao;
import com.leaf.util.DBHelper;
import com.leaf.util.PageBean;
import com.leaf.util.StringUtils;

/**
 *  Database access layer : The book list 
 * @author Leaf
 *
 * 2022 year 6 month 29 Japan   In the morning 8:49:08
 */
public class BookDao extends BaseDao<Book> {
	
	// Inquire about 
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql = "select * from t_mvc_book where 1=1 ";
		String bname = book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql += " and bname like '%"+bname+"%'";
		}
		int bid = book.getBid();
		if(bid != 0) {
			sql += " and bid = "+ bid;
		}
		return super.executeQuery(sql, pageBean, rs -> {
			List<Book> list = new ArrayList<>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt(1), rs.getString(2), rs.getFloat(3)));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		});
	}
	
	// increase 
	public int add(Book book) throws Exception {
		String sql = "insert into t_mvc_book values(?,?,?)";
		return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	
	// Delete 
	public int del(Book book) throws Exception {
		String sql = "delete from t_mvc_book where bid = ?";
		return super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	// modify 
	public int edit(Book book) throws Exception {
		String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
		return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}
	
}

Four 、 To write Action Receive requests and process

At this time, we can start to write our request processing class BookAction

package com.leaf.web;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.leaf.dao.BookDao;
import com.leaf.entity.Book;
import com.leaf.mvc.ActionSupport;
import com.leaf.mvc.ModelDriven;
import com.leaf.util.PageBean;

public class BookAction extends ActionSupport implements ModelDriven<Book> {
	
	private Book book = new Book();
	private BookDao bd = new BookDao();
	
	@Override
	public Book getModel() {
		return book;
	}
	
	// increase 
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bd.add(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Jump to the query interface 
		return "toList";
	}
	
	// Delete 
	public String del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bd.del(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Jump to the query interface 
		return "toList";
	}
	
	// modify 
	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bd.edit(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Jump to the query interface 
		return "toList";
	}
	
	// Inquire about 
	public String list(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// Instantiation PageBean
			PageBean pageBean = new PageBean();
			// initialization 
			pageBean.setRequest(req);
			List<Book> list = bd.list(book, pageBean);
			if(list.size()==0) {
				// No content found 
				List<Book> list2 = bd.list(new Book(), pageBean);
				// Query all 
				req.setAttribute("list", list2);
			}
			else {
				req.setAttribute("list", list);
			}
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Execute query display 
		return "list";
	}
	
	// Jump to the new or edit page 
	public String preEdit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int bid = book.getBid();
			if(bid != 0) {
				// Pass on bid Go backstage , There is only one piece of data , That means list There is only one in the set 
				List<Book> list = bd.list(book, null);
				req.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// Jump to the edit page 
		return "toEdit";
	}

}

5、 ... and 、 Configuration framework xml file

When the above classes are written , We need to configure the framework xml The file !

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<action path="/Book" type="com.leaf.web.BookAction">
		<forward name="list" path="/Book.jsp" redirect="false" />
		<forward name="toEdit" path="/BookEdit.jsp" redirect="false" />
		<forward name="toList" path="/Book.action?methodName=list" redirect="true" />
	</action>
</config>

6、 ... and 、 The front-end code

All the code in the background will be written here , The code of the front desk is also attached here :

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--  introduce L label  -->
<%@ taglib prefix="l" uri="http://jsp.leaf.com" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
	href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
	rel="stylesheet">
<script
	src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title> Book homepage </title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}

</style>
</head>
<body>
	<form class="form-inline" action="${pageContext.request.contextPath }/Book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname" placeholder=" Please enter the name of the book ">
		</div>
		&nbsp;
		<a href="${pageContext.request.contextPath }/Book.action?methodName=preEdit" class="btn btn-primary mb-2"> newly added </a>
		&nbsp;
		<button type="submit" class="btn btn-primary mb-2"> Inquire about </button>
	</form>

	<table class="table table-striped">
		<thead>
			<tr>
				<th scope="col"> Books ID</th>
				<th scope="col"> Book title </th>
				<th scope="col"> Price </th>
				<th scope="col"> operation </th>
			</tr>
		</thead>
		<tbody>
		<!--  Loop traversal  -->
		<l:forEach items="${list }" var="b">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
				<td>
					<a href="${pageContext.request.contextPath }/Book.action?methodName=preEdit&bid=${b.bid }"> edit </a>
					<a onclick="return confirm(' Are you sure you want to delete this book ?')" href="${pageContext.request.contextPath }/Book.action?methodName=del&bid=${b.bid }"> Delete </a>
				</td>
			</tr>
		</l:forEach>
		</tbody>
	</table>
	
	<!--  Pagination label  -->
	<l:page pageBean="${pageBean }"></l:page>
	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${empty b ? " New books " : " Edit books " } page </title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/Book.action?methodName=${empty b ? "add" : "edit" }" method="post">
		<center>
			<h3>${empty b ? " New books " : " Edit books " }</h3>
			<table>
				<tr>
					<td> Book number :</td>
					<td>
						<input ${empty b ? "" : "readonly" } type="text" name="bid" value="${b.bid }">
					</td>
				</tr>
				<tr>
					<td> Book name :</td>
					<td>
						<input type="text" name="bname" value="${b.bname }">
					</td>
				</tr>
				<tr>
					<td> Book price :</td>
					<td>
						<input type="text" name="price" value="${b.price }">
					</td>
				</tr>
			</table><br>
			<input type="submit" value="${empty b ? " increase " : " modify " }" style="cursor: pointer;">
			&nbsp;
			<a href="Book.action?methodName=list" style="text-decoration: none;"> Cancel </a>
		</center>
	</form>
</body>
</html>

 

We run :

Be careful : Be sure to submit :method="post"

原网站

版权声明
本文为[_ Leaf1217]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230538038857.html