Custom MVC Architecture [Part 2]

Table of contents

I. Introduction

2. Export custom MVC framework package

3. Use a custom MVC framework package

4. Optimize the addition, deletion, modification, query layer and Servlet

 1. Optimize the addition, deletion, modification and query layer

 2. Optimize addition, deletion, modification and query of Servlet code

5. Case Practice

1. Configure the PageTag custom label

2. jsp page environment construction

3. Case presentation


I. Introduction

In the previous article, we have optimized the three major problems of sub-controller initialization, code redundancy of jump pages, and entity encapsulation of request parameters. At present, our custom MVC can meet most of the needs. Let me introduce Lead everyone to use our custom MVC framework package and the optimization of CRUD operations.

(I will upload all the following codes to CSDN, welcome to download or read the first two blogs)

2. Export custom MVC framework package

First of all, before using it, we must first export the custom MVC we wrote to the jar file.

Step 1: Find the package about custom MVC

 Our framework and model packages

Step 2: Right-click Export to export

Step 3: Select the JAR file file

Step 4: Choose the location you need to store and save it, just click Finish

 In this way, the custom MVC framework package we wrote is ready! !

3. Use a custom MVC framework package

①Create a web project and import the required rack packages (especially the rack packages we wrote ourselves)

②Create a toolkit (utils) and import the required files

 

Note: Here it is best to test our database helper class (DBAccess), whether the connection to the database is successful 

③Import our mvc.xml sub-control configuration file

It is best to create a new Source Folder resource package to save

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/book" type="com.zking.web.BookAction">
		<forward name="list" path="/bookList.jsp" redirect="false" />
		<forward name="toList" path="/book.action?methodName=list"
			redirect="true" />
		<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
	</action>

</config>

The xml configuration file here is different from that of the custom MVC architecture [中], because there are three cases for adding, deleting, modifying and querying operations, the first query interface, the second modifying the initialization data interface, and the third adding, deleting and modifying operations after execution Call the list method to synchronize the data first and then echo.

④The web.xml file manually configures the central controller (DispatchServlet)

<?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>xmymvc_crud</display-name>
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>com.zking.framework.DispatchServlet</servlet-class>
    <init-param>
      <param-name>configurationLocation</param-name>
      <param-value>/mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

Kind tips:

Because we used to annotate the central controller (DispatchServlet) to intercept the servlet request and complete the initial configuration, but now the central controller (DispatchServlet) is something in the rack package, so we need to manually configure the xml file that needs to be parsed (/mvc.xml).

4. Optimize the addition, deletion, modification, query layer and Servlet

 1. Optimize the addition, deletion, modification and query layer

Create database entities and dao packages

Entity class

package com.zking.entity;

public class Book {
	private int bid;
	private String bname;
	private float 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;
	}
	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}
	
}

Here we can optimize our Dao layer code, and integrate additions, deletions, and changes into one code.

        Common routines for adding, deleting, modifying and checking
        1. Establishing links
        2. Predefined objects PreparedStatement
        3. Setting placeholders? Value of
        4.pst.executeUpdate();

So we can optimize the repeated code and thinking

BaseDao (general CRUD)

package com.zking.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.zking.entity.Book;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

/**
 * 所有Dao层的父类
 * 	BookDao
 * 	UserDao
 * 	OrderDao
 * 	...
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
	/**
	 * 通用的增删改方法
	 * @param book
	 * @throws Exception
	 */
	public void executeUpdate(String sql, T t, String[] attrs) throws Exception {
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		/*
		 * 思路:
		 * 	1.从传进来的t中读取属性值
		 *  2.往预定义对象中设置了值
		 */
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			pst.setObject(i+1, f.get(t));
		}
		pst.executeUpdate();
	}
	
	/**
	 * 通用分页查询
	 * @param sql
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{
		List<T> list = new ArrayList<T>();
		Connection con = DBAccess.getConnection();;
		PreparedStatement pst = null;
		ResultSet rs = null;
		
		if(pageBean != null && pageBean.isPagination()) {
			String countSQL = getCountSQL(sql);
			pst = con.prepareStatement(countSQL);
			rs = pst.executeQuery();
			if(rs.next()) {
				pageBean.setTotal(String.valueOf(rs.getObject(1)));
			}
			
			String pageSQL = getPageSQL(sql,pageBean);
			pst = con.prepareStatement(pageSQL);
			rs = pst.executeQuery();
		}else {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
		}
		
		
		while (rs.next()) {
			T t = clz.newInstance();
			Field[] fields = clz.getDeclaredFields();
			for (Field f : fields) {
				f.setAccessible(true);
				f.set(t, rs.getObject(f.getName()));
			}
			list.add(t);
		}
		return list;
	}

	/**
	 * 将原生SQL转换成符合条件的总记录数countSQL
	 * @param sql
	 * @return
	 */
	private String getCountSQL(String sql) {
		return "select count(1) from ("+sql+") t";
	}

	/**
	 * 将原生SQL转换成pageSQL
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSQL(String sql,PageBean pageBean) {
		return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows();
	}
}

BookDao inherits from BaseDao

package com.zking.dao;

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

import com.zking.entity.Book;
import com.zking.util.BaseDao;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

public class BookDao extends BaseDao<Book>{
	
	public void add(Book book) throws Exception {
		String sql = "insert into t_mvc_book values(?,?,?)";
		super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	
	public void edit(Book book) throws Exception {
		String sql = "update t_mvc_book set bname = ?, price = ? where bid = ?";
		super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}
	
	public void delete(Book book) throws Exception {
		String sql = "delete from t_mvc_book where bid = ?";
		super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	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+"%'";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}
	
}

 2. Optimize addition, deletion, modification and query of Servlet code

Create a Servlet that inherits ActionSupport and implements ModelDriver<entity that needs to be operated>

package com.zking.web;

import java.util.List;

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

import com.zking.dao.BookDao;
import com.zking.entity.Book;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;


/**
 * @author Java方文山
 *
 */
public class BookAction extends ActionSupport implements ModelDriver<Book>{
	private Book book = new Book();
	private BookDao bookDao = new BookDao();
	@Override
	public Book getModel() {
		return book;
	}
	
	
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bookDao.add(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	public String list(HttpServletRequest req, HttpServletResponse resp) {
		try {
			PageBean pageBean = new PageBean();
			pageBean.setPagination(true);
			pageBean.setRequest(req);
			List<Book> list = bookDao.list(book,pageBean);
			req.setAttribute("books", list);
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "list";
	}
	
	public String delete(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bookDao.delete(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bookDao.edit(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	/**
	 * 跳转到新增修改页面
	 * @param req
	 * @param resp
	 * @return
	 */
	public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			/*
			 * 如果是跳转修改页面,那么需要做bid条件的精准查询
			 */
			if(book.getBid() != 0) {
				List<Book> list = bookDao.list(book, null);
				req.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toEdit";
	}
}
As mentioned earlier, we have three jump situations, so we also have three return values ​​(note that the xml file is configured)

5. Case Practice

1. Configure the PageTag custom label

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

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    
  <description>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>zking</short-name>
  <uri>http://jsp.veryedu.cn</uri>
  
  
  <tag>
    <name>page</name>
    <tag-class>com.zking.tag.PageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>pageBean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

Put it in the web-inf directory

2. jsp page environment construction

HomepagebookList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>书籍列表</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>
	<c:if test="${empty  pageBean}">
		<jsp:forward
			page="${pageContext.request.contextPath }/book.action?methodName=list"></jsp:forward>
	</c:if>


	<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="请输入书籍名称">
			<!-- 			<input name="rows" value="20" type="hidden"> -->
			<!-- 不想分页 -->
			<input name="pagination" value="true" type="hidden">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
		<a class="btn btn-primary mb-2"
			href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增</a>
	</form>

	<table class="table table-striped ">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach var="b" items="${books }">
				<tr>
					<td>${b.bid }</td>
					<td>${b.bname }</td>
					<td>${b.price }</td>
					<td><a
						href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a>
						<a
						href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a>
					</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	
	<z:page pageBean="${pageBean }"></z:page>

</body>
</html>

Modify/add page bookEdit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>	
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>	
<!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>书籍新增/修改</title>
</head>
<body>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
		书籍ID:<input type="text" name="bid" value="${b.bid }"><br>
		书籍名称:<input type="text" name="bname" value="${b.bname }"><br>
		书籍价格:<input type="text" name="price" value="${b.price }"><br>
		<input type="submit">
	</form>


</body>
</html>

3. Case presentation

Seeing this, I believe you must have your own unique understanding of custom MVC! !

So far, the custom MVC trilogy is over! !

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131526598