前言:前面俩次跟大家分享了mvc框架的编写,今天用框架来实现增删查改的功能
思维导图
?
一、对相关配置文件的优化
步骤:在java Resources新建一个source folder文件夹(注意该文件夹与原有的src文件夹同级)把我们导出的.jar文件放进去
配置好我们的.xml文件 代码如下(跟我们前面的config.xml内容是一样的)
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.zking.web.StudentAction">
<forward name="list" path="/index.jsp" redirect="false" />
<!-- 增删改操作之后要再一次查询数据库的新的数据做展示 -->
<forward name="toList" path="/book.action?methodName=list" redirect="true" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
</action>
</config>
在中央控制器要进行判断
public void init() throws ServletException {
try {
//configModel = ConfigModelFactory.build();
//配置的文件位置:web.xml
String configurationLocation = this.getInitParameter("configurationLocation");
if(configurationLocation==null ||"".equals(configurationLocation)) {
configurationLocation="/zking.xml";
}
configModel = ConfigModelFactory.build(configurationLocation);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
运行结果
二,通用的增删查改1
1.建立一个dao包里面编写一个基础dao类(里面写所有的通用方法)代码如下所示
package com.dff.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.List;
import com.dff.util.DBAccess;
import com.dff.util.PageBean;
public class BaseDao<T> {
public interface CallBack<T>{
public List<T> forEach(ResultSet rs) throws Exception;
}
/**
* 通用的增删改
* @param sql 具体的增删改sql
* @param t 具体要操作的表对应的实体类
* @param attrs 具体操作的表的某些字段对应的实体类属性
* @throws Exception
*/
public void executeUpdate(String sql,T t,String[] attrs) throws Exception {
//把参数传进来
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
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();
}
/**
* 1.通用分页两个基本要素
* 1.1 需要知道满足条件的条目数
* 1.2查询满足条件指定页码的结果
* @throws Exception
*/
public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=DBAccess.getConnection();
// 如果用户需要分页的话将用户传递过来的sql语句进行转换
if(null!=pageBean&&pageBean.isPagination()) {
String countSql = this.countSql(sql);
ps=con.prepareStatement(countSql);
rs=ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getInt(1));
}
//开始查询结果
String pageSql = this.pageSql(sql, pageBean);
ps=con.prepareStatement(pageSql);
}else {
//用户不需要分页
ps=con.prepareStatement(sql);
}
rs=ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return callBack.forEach(rs);
}
/**
* 共用的方法用于执行sql语句实现增删改
* 通用编辑
* @param sql
* @return
*/
public int executeUpdate(String sql) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
int n=0;
try {
con=DBAccess.getConnection();
ps=con.prepareStatement(sql);
n=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
DBAccess.close(con, ps, rs);
}
return n;
}
/**
* 将用户sql语句修改为查询满足条件的总条目数sql语句
* @param sql
* @return
*/
private String countSql(String sql) {
String countSql="select count(*) from ("+sql+") a";
return countSql;
}
private String pageSql(String sql,PageBean pageBean) {
String pageSql="select * from ("+sql+")a limit "+pageBean.getStartIndex()+","+pageBean.getRows();
return pageSql;
}
}
这里以学生类为例在stuDao里面调用相关方法代码如下(studao继承了basedao)
package com.dff.dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.dff.entity.Student;
import com.dff.util.BaseDao;
import com.dff.util.PageBean;
import com.dff.util.StringUtils;
public class StudentDao extends BaseDao<Student>{
/**
* 现状:增删改
* 1.写sql
* 2.建立链接
* 3.预定义对象PreparedStatement
* 4.设置参数
* 5.执行sql
* 解决:
*
* @param student
* @throws Exception
*/
public void add(Student student) throws Exception {
String sql="insert into t_student values(?,?,?,?,?)";
super.executeUpdate(sql, student, new String[] {"sid","sname","snamePinyin","age","remark"});
}
public void delete(Student student) throws Exception {
String sql="delete from t_student where sid=?";
super.executeUpdate(sql, student, new String[] {"sid"});
}
public void edit(Student student) throws Exception {
String sql="update t_student set sname=?,snamePinyin=?,age=?,remark=? where sid=?";
super.executeUpdate(sql, student, new String[] {"sname","snamePinyin","age","remark","sid"});
}
/**
* 查询所有
* @param student
* @param pageIndex
* @param pageSize
* @return
*/
public List<Student> list(Student student,PageBean pageBean) throws Exception{
String sql="select * from t_student where 1=1";
if(StringUtils.isNotBlank(student.getSname())) {
sql+=" and sname like '%"+student.getSname()+"%'";
}
return this.executeQuery(sql, pageBean, new CallBack<Student>() {
@Override
public List<Student> forEach(ResultSet rs) throws Exception {
List<Student> students=new ArrayList<>();
Student s=null;
while(rs.next()) {
s=new Student();
s.setSid(rs.getInt("sid"));
s.setSname(rs.getString("sname"));
s.setAge(rs.getInt("age"));
s.setRemark(rs.getString("remark"));
students.add(s);
}
return students;
}
});
}
}
在子控制器里面写相关方法
package com.dff.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dff.dao.StudentDao;
import com.dff.entity.Student;
import com.dff.framework.ActionSupport;
import com.dff.framework.ModelDriver;
import com.dff.util.PageBean;
public class StudentAction extends ActionSupport implements ModelDriver<Student>{
private Student student=new Student();
private StudentDao studao=new StudentDao();
@Override
public Student getModel() {
// TODO Auto-generated method stub
return student;
}
public String add(HttpServletRequest req,HttpServletResponse resp) throws Exception {
studao.add(student);
return "toList";
}
public String delete(HttpServletRequest req,HttpServletResponse resp) throws Exception {
studao.delete(student);
return "toList";
}
public String edit(HttpServletRequest req,HttpServletResponse resp) throws Exception {
studao.edit(student);
return "toList";
}
public String list(HttpServletRequest req,HttpServletResponse resp) {
PageBean pagebean=new PageBean();
pagebean.setRequest(req);
List<Student> list;
try {
list = studao.list(student, pagebean);
req.setAttribute("students", list);
req.setAttribute("pageBean", pagebean);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
public String toEdit(HttpServletRequest req,HttpServletResponse resp) {
//如果跳转地是新增界面无需查询,跳转地是修改界面,需要查询当前sid对应的
if(student.getSid()!=0) {
try {
List<Student> list = studao.list(student, null);
req.setAttribute("b", list.get(0));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "toEdit";
}
}
测试代码
public static void main(String[] args) throws Exception {
Student student=new Student();
student.setSid(100);
student.setSname("aqqqq");
student.setSnamePinyin("aaaaaa");
student.setAge(100);
student.setRemark("wu");
StudentDao studao=new StudentDao();
studao.add(student);
}
界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="z" uri="/zking" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.1.0/css/bootstrap.css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.1.0/js/bootstrap.js"></script>
<title>Insert title here</title>
</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">
<tr>
<td>学生编号</td>
<td>学生姓名</td>
<td>姓名缩写</td>
<td>学生年龄</td>
<td>学生备注</td>
</tr>
<c:forEach items="${students }" var="i">
<tr>
<td>${i.sid }</td>
<td>${i.sname }</td>
<td>${i.snamePinyin }</td>
<td>${i.age }</td>
<td>${i.remark }</td>
<td>
<a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&sid=${i.sid}">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=delete&sid=${i.sid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<z:pagination pageBean="${pageBean }"/>
</body>
</html>
绑定值?
?删除效果(把编号为2的删除了)
?修改拿值界面
遇到的问题
上面报错是因为配置路径写错了?
<forward name="list" path="/index.jsp" redirect="false" />? path路径我写成了/booklist.jsp 而我的项目里面根本没有这个页面
|