目錄
一、配置步驟
二、配置框架前三步
導入相應的jar
導入相應的Class
導入xml文件
三、優(yōu)化基本操作(增刪改)
1、基礎優(yōu)化
編寫實體類
編寫B(tài)ookDao類
優(yōu)化BookDao
JUnit測試
2、后臺優(yōu)化
3、前端優(yōu)化
一、配置步驟
- 將框架打成jar包,然后導入新工程,并且把框架的依賴jar包導入進去
- 將分頁標簽相關文件、及相關助手類導入
- 框架的配置文件添加、以及web.xml的配置-以后開源框架的使用從這一步開始
- 完成Book實體類及bookDao的編寫
- 完成通用的增刪改方法
- 完成BookAction
- 完成mvc.xml的配置
- 完成前臺代碼的編寫
二、配置框架前三步
導入相應的jar
導入之后我們選中所有的jar包===》右鍵===》Build Path===》Add to Build Path
導入相應的Class
導入xml文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.tgq.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>
測試我們的數(shù)據庫能否連接
三、優(yōu)化基本操作(增刪改)
1、基礎優(yōu)化
編寫實體類
package com.tgq.entity;
/**
* 實體類
*
* @author tgq
*
*/
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 + "]";
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
}
編寫B(tài)ookDao類
編寫增刪改查的方法
package com.tgq.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import com.tgq.entity.Book;
import com.tgq.util.BaseDao;
import com.tgq.util.DBAccess;
import com.tgq.util.PageBean;
import com.tgq.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book, PageBean pageBean) throws Exception {
String sql = "select * from t_mvc_book where 1=1 ";
String bname = book.getBname();
int bid = book.getBid();
// 判斷是否為空
if (StringUtils.isNotBlank(bname)) {
sql += " and bname like '%" + bname + "%'";
}
// 判斷前臺是否傳bid
if (bid != 0) {
sql += " and bid=" + bid;
}
return super.executeQuery(sql, Book.class, pageBean);
}
/**
* 增加Book的方法
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int addBook(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());
ps.setObject(3, book.getPrice());
return ps.executeUpdate();
}
/**
* 刪除Book的方法 ,根據id刪除
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int delBook(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=?";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
return ps.executeUpdate();
}
/**
* 修改Book的方法
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int updateBook(Book book) throws Exception {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBname());
ps.setObject(2, book.getPrice());
ps.setObject(3, book.getBid());
return ps.executeUpdate();
}
}
1、在增刪改的方法里面我們這兩行代碼是一樣的、重復的
Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql);
2、代碼邏輯是重復的===》sql占位符賦值
ps.setObject(1, book.getBid()); ps.setObject(2, book.getBname()); ps.setObject(3, book.getPrice());
怎么解決?BaseDao
進行一個通用的增刪改的方法/** * 通用的增刪改方法 * * @param sql * 數(shù)據庫sql語句 * @param t * 對應表的實體類 * @param attrs * 要修改的屬性值 * @return * @throws Exception * 萬能異常 */ public int executeUpdate(String sql, T t, String[] attrs) throws Exception { Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); //利用fori 下標來進行?的賦值 for (int i = 0; i < attrs.length; i++) { Field field = t.getClass().getDeclaredField(attrs[i]); // 打開權限 field.setAccessible(true); ps.setObject(i + 1, field.get(t)); } return ps.executeUpdate(); }
?
優(yōu)化BookDao
我們在BaseDao類里面增加了一個通用的增刪改的方法,我們在BookDao里面利用起來
/**
* 增加Book的方法
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int addBook(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, book, new String[] { "bid", "bname", "price" });
}
/**
* 刪除Book的方法 ,根據id刪除
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int delBook(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, book, new String[] { "bid" });
}
/**
* 修改Book的方法
*
* @param book
* 實體類
* @return
* @throws Exception
* 萬能異常
*/
public int updateBook(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" });
}
JUnit測試
?選中我們的類名===》ctrl+N===》JUnit Test Case===》選中頂部的New JUnit 4 test===》Next
勾選BookDao===》Finish?
BookDaoTest測試
package com.tgq.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import com.tgq.entity.Book;
import com.tgq.util.PageBean;
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testList() throws Exception {
Book book = new Book();
book.setBname("52");
PageBean pageBean = new PageBean();
// pageBean.setPage(2);
List<Book> list = bookDao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testAddBook() throws Exception {
Book book = new Book();
book.setBid(52);
book.setBname("5252");
book.setPrice(12f);
bookDao.addBook(book);
}
@Test
public void testDelBook() throws Exception {
Book book = new Book();
book.setBid(52);
bookDao.delBook(book);
}
@Test
public void testUpdateBook() throws Exception {
Book book = new Book();
book.setBid(52);
book.setBname("5252");
book.setPrice(19f);
bookDao.updateBook(book);
}
}
測試結果:
2、后臺優(yōu)化
我們新建一個web包,在里面新建一個BookAction類(class),繼承ActionSupport,實現(xiàn)
ModelDriver接口,編寫
package com.tgq.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tgq.dao.BookDao;
import com.tgq.entity.Book;
import com.tgq.util.PageBean;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
public class BookAction extends ActionSupport implements ModelDriver<Book> {
private Book book = new Book();
private BookDao bookDao = new BookDao();
// 查詢 bookList.jsp
public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Book> list = bookDao.list(book, pageBean);
req.setAttribute("list", list);
req.setAttribute("pageBean", pageBean);
return "list";
}
// 編輯界面跳轉 bookEdit.jsp
public String toEdit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
// 前提
if (book.getBid() != 0) {
List<Book> list = bookDao.list(book, null);// 不需要分頁
req.setAttribute("b", list.get(0));
}
return "toEdit";
}
// 增加 重定向到book.action?methodName=list
public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.addBook(book);
return "toEdit";
}
// 刪除
public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.delBook(book);
return "toEdit";
}
// 修改
public String update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.updateBook(book);
return "toEdit";
}
@Override
public Book getModel() {
return book;
}
}
我們編寫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
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>
<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="false" 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>
增加,修改的jsp界面。
判斷你點擊的是否是增加還是修改
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}"
<%@ 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
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、前端優(yōu)化
我們運行書籍列表
進行一個搜索,新增、修改、刪除
我們刪除ID:16、22
新增一個
ID:12
書籍名:圣墟12
價格:123?
修改ID:12
書籍名:圣墟1234
價格:12345
文章來源:http://www.zghlxwxcb.cn/news/detail-525832.html
希望對你們有用!!!文章來源地址http://www.zghlxwxcb.cn/news/detail-525832.html
到了這里,關于J2EE自定義mvc【框架配置及功能】的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!