代码参照自定义MVC(二)的博客
https://blog.csdn.net/zuo_fan/article/details/103760319
代码演示:
book 实体类
package com.az.entity;
public class Book {
private int bid;
private String bname;
private float price;
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + 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(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
}
BookDao(写增删改查的方法类)
package com.hyf.dao;
import java.util.List;
import com.hyf.entity.Book;
import com.hyf.util.BaseDao;
import com.hyf.util.PageBean;
import com.hyf.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 true";
String bname = book.getBname();
int bid = book.getBid();
if(StringUtils.isNotBlank(bname)) {
sql +=" and bname like '%"+bname+"%'";
}
if(bid != 0) {
sql +=" and bid="+bid;
}
return super.executeQuery(sql, Book.class, pageBean);
}
/**
* 增
* @param book
* @return
* @throws Exception
*/
public int add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, new String[]{"bid","bname","price"}, book) ;
}
/**
* 修改
* @param book
* @return
* @throws Exception
*/
public int edit(Book book) throws Exception {
String sql = "update t_mvc_book set bname=? , price=? where bid=?";
return super.executeUpdate(sql, new String[]{"bname","price","bid"}, book) ;
}
/**
* 删除
* @param book
* @return
* @throws Exception
*/
public int del(Book book) throws Exception { String sql = "delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, new String[]{"bid"}, book);
}
}
}
BaseDao 用来处理所有的表的通用的增删改查的基类
package com.az.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 用来处理所有的表的通用的增删改查的基类
*
* @author zuo_fan
*
*/
public class BaseDao<T> {
/**
* @param sql
* 可能查不同的表,那么意味着sql语句是变化的,那么它是从子类处理好在传递到父类的
* @param clz
* 需要返回不同的对象集合 Book.class/Order.class
* @param pagebean
* 可能要分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql, Class clz, PageBean pagebean) throws Exception {
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
if(pagebean !=null && pagebean.isPagination()) {
// 分页代码
/*
* 1、分页是与pagebean中total,意味真需要查询数据库得到total赋值给pagebean
* 2、查询出符合条件的某一页的数据
*/
String countSql=getCountSql(sql);
ps=con.prepareStatement(countSql);
rs=ps.executeQuery();
if(rs.next()) {
pagebean.setTotal(rs.getInt(1));
}
// 进行拼接
String pageSql=getPageSql(sql,pagebean);
ps = con.prepareStatement(pageSql);
rs =ps.executeQuery();
}else {
ps = con.prepareStatement(sql);
rs =ps.executeQuery();
}
T t = null; // 泛型传过来的对象 进行实例化
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);
}
DBAccess.close(con, ps, rs);
return list;
}
public int executeUpdate(String sql,String []attrs,T t) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
// 获得类属性
Field f = null;
for (int i =0 ;i < attrs.length; i++) {
f = t.getClass().getDeclaredField(attrs[i]);
f.setAccessible(true);
ps.setObject(i+1, f.get(t));
System.out.println(attrs[i]);
}
int n = ps.executeUpdate();
DBAccess.close(con, ps, null);
return n;
}
private String getPageSql(String sql,PageBean pagebean) {
return sql + " limit "+pagebean.getStartIndex()+","+pagebean.getRows() ;
}
private String getCountSql(String sql) { // 获得总记录 查询的数据有多少数据
return "select count(1) from ("+sql+") t";
}
}
Action
package com.az.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器:
* 作用:具体处理用户请求的类(实现Action接口类)
*
* @author zuo_fan
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
ActionSupport 增强控制器
package com.az.framework;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 增强控制器
* 作用: 将一组操作数组放到一个子控制器去完成
*
* @author zuo_fan
*
*/
public class ActionSupport implements Action {
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从前台传递需要调用的方法名到后台,实现动态方法调用 url后面加 &methodName
String code =null;
String methodName = req.getParameter("methodName");
try {
Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
// 获得方法 返回值
code=(String) m.invoke(this, req,resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
}
ModelDriver 模型驱动接口
package com.az.framework;
/**
* 模型驱动接口
* 作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
* @author zuo_fan
*
*/
public interface ModelDriver<T> {
T getModel();
}
DispatcherServlet 中央控制器
package com.az.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的子控制器去处理业务
*
* 1、对存放子控制器action容器的增强
* 原来为了完成业务需求,需要不断修改框架的代码,这种设计是不合理的
* 处理方式:参照web.xml的实际方法,来完成中央控制器管理子控制器的动态配置
*
* 2、 处理结果码的跳转方式
* 达到简化代码
* 3、将基础操作放到一个子控制器
*
* 4、处理jsp传递到后台的参数配置
*
* 5、解决框架配置文件重名冲突的问题
*
* @author zuo_fan
*
*/
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -3841666976794538752L;
/**
* 用来存放 子控制器
*/
private ConfigModel configModel = null;
public void init() {
try {
String mvcXmlLocation = this.getInitParameter("mvcXmlLocation"); // 5.mvc 的默认地址
if(null == mvcXmlLocation || "" .equals(mvcXmlLocation)) {
mvcXmlLocation="/mvc.xml";
}
System.out.println(mvcXmlLocation);
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
System.out.println("url:"+url);
/* Action action = actionMap.get(url);*/
ActionModel actionModel = configModel.get(url);
try {
// 2 2如果客户没有配置 需要提示
if(actionModel == null) {
throw new RuntimeException("您还未配置子控制器来处理用户请求");
}
//1 类地址 进行实例化
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
//4加强
if(action instanceof ModelDriver) {
ModelDriver modelDriver = (ModelDriver) action;
Object model = modelDriver.getModel();
// 给 model 赋值了,那么意味这在调用add/del不在是空值
BeanUtils.populate(model, req.getParameterMap());
}
// 3加强
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if("false".equals(forwardModel.getRedirect())) {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else {
// 2注意:默认会缺损项目名 req.getContextPath()
resp.sendRedirect(req.getContextPath()+ forwardModel.getPath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
PageTag
package com.az.tag;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.az.util.PageBean;
public class PageTag extends BodyTagSupport {
private static final long serialVersionUID = 383258790166308355L;
private PageBean pageBean;
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
// 拼接下一次分页请求搜提交的分页表单
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
sb.append("<input type='hidden' name='page'> ");
Map<String, String[]> paMap = pageBean.getPaMap();
if(paMap != null && paMap.size()>0) {
Set<Entry<String, String[]>> entrySet = paMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
for(String value :entry.getValue() ) {
if(!"page".equals(entry.getKey())) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+value+"'>");
}
}
}
}
sb.append("</form>");
// 拼接分页条
sb.append("<div style='text-align: right; font-size: 12px;'>");
sb.append(" 每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 ");
sb.append(" <a href='javascript:gotoPage(1)'>首页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> ");
sb.append(" <input type='text' id='skipPage' style='text-align: center; font-size: 12px; width: 50px;'> ");
sb.append(" <a href='javascript:skipPage()'>Go</a>");
sb.append(" </div>");
// 拼接分页的javascript 代码
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append(" }");
sb.append(" function skipPage() { ");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){");
sb.append(" alert('请输入1~N的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append(" }");
sb.append("</script> ");
return sb.toString();
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
}
BookAction
package com.az.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.az.dao.BookDao;
import com.az.entity.Book;
import com.az.framework.ActionSupport;
import com.az.framework.ModelDriver;
import com.az.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriver<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
public String list(HttpServletRequest req,HttpServletResponse resp) {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
try {
List<Book> list = this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pagebean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
/**
* 跳转新增修改页面(新增修改是同一个)
* @param req
* @param resp
* @return
* @throws Exception
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
if(book.getBid() != 0) {
try {
Book b = this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (Exception e) {
e.printStackTrace();
}
}
return "edit";
}
/**
* 新增
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.del(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
public Book getModel() {
return book;
}
}
配置xml
<?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>web_mvc</display-name>
<!--解决乱码 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.hyf.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.hyf.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
h.xld
<?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>hyf 1.1 core library</description>
<display-name>hyf core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>c</short-name>
<uri>/hyf</uri>
<tag>
<name>page</name>
<tag-class>com.hyf.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
bookList.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/hyf" prefix="h"%>
<!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>书籍主页</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/book.action?methodName=list" method="post">
<!--用户设置查询 一页20条记录 -->
<!-- <input type="hidden" name="rows" value="20"/> -->
<!--用户设置不分页 -->
<!-- <input type="hidden" name="pagination" value="false"/> -->
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave">增加</a>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList}" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave&&bid=${b.bid }">修改</a>
<a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<h:page pageBean="${pagebean}"></h:page>
</body>
</html>
bookEdit.jsp
增加和修改数据类容的页面。
<%@ 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>编辑页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book.action?methodName=${book.bname == null ?'add' : 'edit'}" method="post">
bid: <input type="text" value="${book.bid}" name="bid"/><br>
bname:<input type="text" value="${book.bname}" name="bname"/><br>
price:<input type="text" value="${book.price}" name="price"/><br>
<button type="submit">确认</button>
</form>
</body>
</html>
config.properties获取数据库
#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql5
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/azuo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
图片结果显示:
增加
查询
修改