自定义MVC增删查改
1首先我们先来创建项目
2:导入架包

3:导入相应的包

4:写其他类的方法:
dao层:
public class StuDao implements IStuDao{
//扩大作用域
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
/**
* 分页查询
* @param pageIndex
* @param pageSize
* @param str
* @param colName
* @return
*/
public List<Student> getAll(int pageIndex,int pageSize,String str){
List<Student> ls=new ArrayList<>();
try {
//连接数据库
con=DBAccess.getConnection();
//写sql语句
ps=con.prepareStatement("select * from tb_stu "+str+" limit "+(pageIndex-1)*pageSize+","+pageSize+"");
//结果集
ResultSet rs=ps.executeQuery();
while(rs.next()) {
Student stu=new Student();
stu.setSid(rs.getInt(1));
stu.setSname(rs.getString(2));
stu.setShobby(rs.getString(3));
stu.setT(getT(rs.getInt(4)));
stu.setC(getC(rs.getInt(5)));
//增加
ls.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return ls;
}
/**
* 查出所有教员
* @return
*/
public List<Teacher> getTid(){
//有多个所以用集合
List<Teacher> ls=new ArrayList<>();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select * from tb_teacher");
rs=ps.executeQuery();
while(rs.next()) {
Teacher t=new Teacher();
t.setTid(rs.getInt(1));
t.setTname(rs.getString(2));
ls.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return ls;
}
/**
* 查出所有班级
* @return
*/
public List<Clas> getCid(){
List<Clas> ls=new ArrayList<>();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select * from tb_class");
rs=ps.executeQuery();
while(rs.next()) {
Clas c=new Clas();
c.setCid(rs.getInt(1));
c.setCname(rs.getString(2));
ls.add(c);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return ls;
}
@Override
public int add(Student stu) {
int n=0;
try {
con=DBAccess.getConnection();
//?代表占位字符
ps=con.prepareStatement("insert into tb_stu values(?,?,?,?,?)");
ps.setInt(1, stu.getSid());
ps.setString(2, stu.getSname());
ps.setString(3, stu.getShobby());
ps.setInt(4, stu.getT().getTid());
ps.setInt(5, stu.getC().getCid());
n=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return n;
}
@Override
public int update(Student stu, int sid) {
int n=0;
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("update tb_stu set sid=?,sname=?,shobby=?,tid=?,cid=? where sid=?");
ps.setInt(1, stu.getSid());
ps.setString(2, stu.getSname());
ps.setString(3, stu.getShobby());
ps.setInt(4, stu.getT().getTid());
ps.setInt(5, stu.getC().getCid());
ps.setInt(6, sid);
n=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return n;
}
@Override
public int del(int sid) {
int n=0;
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("delete from tb_stu where sid="+sid);
n=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return n;
}
@Override
public Student getBySid(int sid) {
Student stu=new Student();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select * from tb_stu where sid=?");
ps.setInt(1, sid);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
stu.setSid(rs.getInt(1));
stu.setSname(rs.getString(2));
stu.setShobby(rs.getString(3));
stu.setT(getT(rs.getInt(4)));
stu.setC(getC(rs.getInt(5)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return stu;
}
@Override
public int getSid() {
// TODO Auto-generated method stub
return 0;
}
/**
* 获取最大行数
* @param str
* @return
*/
public int getRows(String str){
int n = 0;
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select count(*) from tb_stu "+str+"");
rs = ps.executeQuery();
if(rs.next()){
n = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
DBAccess.close(con, ps, rs);
}
return n;
}
public Clas getC(int cid) {
Clas c=new Clas();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select * from tb_class where cid="+cid);
rs=ps.executeQuery();
if(rs.next()) {
c.setCid(rs.getInt(1));
c.setCname(rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return c;
}
public Teacher getT(int tid) {
Teacher t=new Teacher();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select * from tb_teacher where tid="+tid);
rs=ps.executeQuery();
if(rs.next()) {
t.setTid(rs.getInt(1));
t.setTname(rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return t;
}
public List<Student> getAllName(){
List<Student> ls=new ArrayList<>();
try {
con=DBAccess.getConnection();
ps=con.prepareStatement("select sname from tb_stu");
ResultSet rs=ps.executeQuery();
while(rs.next()) {
Student stu=new Student();
stu.setSname(rs.getString(1));
ls.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(con, ps, rs);
}
return ls;
}
public static void main(String[] args) {
List<Student> ls = new StuDao().getAllName();
System.out.println(ls);
for (Student s : ls) {
String aa = PinYinUtil.toPinyin(s.getSname());
System.out.println(aa);
}
}
}
//接下来我们写一个类里面含有主控制器:
framework:他里面不止有子控制器:还有其他的之前的包
DispatcherServlet:
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -7094025920085803724L;
private ConfigModel configModel = null;
//初始化方法
public void init() {
try {
//将原来的读取框架的默认配置文件转变成读取可配置路径的配置文件
String xmlPath = this.getInitParameter("xmlPath");
//如果xmlPath为空或者有空字符串
if(xmlPath == null || "".equals(xmlPath)) {
configModel = ConfigModelFatory.build();
}
else {
configModel = ConfigModelFatory.build(xmlPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
init();//调用初始化的方法
String url = req.getRequestURI();//获取的路径Mvc/xxx.action
//截取最后一个/和最后一个点
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
//根据路径获取action的模型
ActionModel actionModel = configModel.pop(url);
if(actionModel==null) {
throw new RuntimeException("你没有配置对应的子控制器Action!!!");
}
try {
//原来子控制器的来源是map集合,这样的话子控制器被写死再map容器中,代码不够灵活
//现在将子控制器配置方式存放再config.xml中,未来可以通过改变config.xml中的内容
//随意给中央控制器添加子控制器
Action action = (Action)Class.forName(actionModel.getType()).newInstance();
// 调用模型驱动接口,获取所需要操作的实体类,然后将jsp传递过来的参数,封装到实体类中
if(action instanceof ModelDriver) {
ModelDriver modelDriver=(ModelDriver)action;
Object model = modelDriver.getModel();
//封装属性
BeanUtils.populate(model, req.getParameterMap());
}
// 每个子控制器,都需要对结果进行对应的处理,要么重定向,要么转发,代码重复量较大
// 针对于这一现象,将其交给配置文件来处理
// 调用了增强版的子控制器来处理业务逻辑
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(code);
if(forwardModel ==null) {
throw new RuntimeException("你没有配置对应的子控制器Action的处理方式Forward!!!");
}
String jspPath = forwardModel.getPath();
if(forwardModel.isRedirect()) {
resp.sendRedirect(req.getContextPath()+jspPath);//拼接上路径,相当于绝对路径
}
else {
req.getRequestDispatcher(jspPath).forward(req, resp);
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
驱动模型接口:ModeIDriver
/**
* 模型驱动接口
* 是用来处理jsp页面传递过来的参数,
* 将所有的参数自动封装到实体类T中
*
* @param <T>
*/
public interface ModelDriver<T> {
T getModel();
}
只控制器action
Action:
/**
* 子控制器
* 专门用来处理业务逻辑
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
}
com.Servlet:
他里面的Servlet 都需要继承HttpServlet
AddServlet:增加
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码方式
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取out
PrintWriter out = resp.getWriter();
//接受jsp页面传来的值
String sid=req.getParameter("sid");
String sname=req.getParameter("sname");
String tid=req.getParameter("tid");
String cid=req.getParameter("cid");
IStuBiz isb=new StuBiz();
//拼接
String shobby="";
String[] s = req.getParameterValues("shobby");
//把最后一个逗号去掉
if(s!=null) {
for (int i = 0; i < s.length; i++) {
shobby+=s[i]+",";
}
shobby=shobby.substring(0, shobby.length()-1);
}
//实列化并调用增加方法
Student stu=new Student(Integer.parseInt(sid), sname, shobby, new StuDao().getT(Integer.parseInt(tid)),new StuDao().getC(Integer.parseInt(cid)));
int n = isb.add(stu);
if(n>0) {
resp.sendRedirect("index.jsp");
}
else {
out.print("<script>alert('增加失败!');location.href='add.jsp';</script>");
}
}
}
删除:DelServlet
public class DelServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码方式
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取out
PrintWriter out = resp.getWriter();
//接受jsp页面传来的值
String sid=req.getParameter("sid");
IStuBiz isb=new StuBiz();
//调用方法
int n = isb.del(Integer.parseInt(sid));
if(n>0) {
resp.sendRedirect("index.jsp");
}
else {
out.print("<script>alert('删除失败');location.href='index.jsp';</script>");
}
}
Index:
public class IndexServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
int pageIndex=1;
int pageSize=5;
String bb = req.getParameter("name");
String a = PinYinUtil.toPinyin(bb);
System.out.println(a+"name");
String str="";
String pid=req.getParameter("pid");
if(pid!=null) {
pageIndex=Integer.parseInt(pid);
}
req.setAttribute("pageIndex", pageIndex);
String tid=req.getParameter("tid");
System.out.println(tid+"t");
String cid=req.getParameter("cid");
System.out.println(cid+"c");
String shobby="";
String[] s = req.getParameterValues("shobby");
if(s!=null) {
for (int i = 0; i < s.length; i++) {
shobby+=s[i]+",";
}
shobby=shobby.substring(0, shobby.length()-1);
}
System.err.println("aa"+shobby);
if(tid==null&&cid==null) {
str="where shobby like '%"+shobby+"%'";
System.out.println("hello");
}
else if(tid.equals("a")&&!cid.equals("a")) {
str="where cid="+Integer.parseInt(cid)+" and shobby like '%"+shobby+"%'";
System.out.println(1);
}
else if(cid.equals("a")&&!tid.equals("a")) {
str="where tid="+Integer.parseInt(tid)+" and shobby like '%"+shobby+"%'";
System.out.println(2);
}
else if(!tid.equals("a")&&!cid.equals("a")) {
System.out.println(3);
str="where tid="+tid+" and cid="+cid+" and shobby like '%"+shobby+"%'";
}
else{
str="where shobby like '%"+shobby+"%'";
System.out.println(4);
}
IStuBiz isb=new StuBiz();
int row=isb.getRows(str);
int max=row/pageSize;
if(row%pageSize!=0) {
max++;
}
req.setAttribute("max", max);
List<Clas> lsc = new StuDao().getCid();
List<Teacher> lst = new StuDao().getTid();
req.setAttribute("lst", lst);
req.setAttribute("lsc", lsc);
List<Student> ls=isb.getAll(pageIndex, pageSize, str);
req.setAttribute("myls", ls);
if(ls.size()!=0) {
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
else {
System.out.println("集合为空");
}
}
}
查单个:preServlet:
public class PreServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String sid=req.getParameter("sid");
IStuBiz isb=new StuBiz();
Student stu = isb.getBySid(Integer.parseInt(sid));
//把值存到req里面去
req.setAttribute("s", stu);
获取cid
List<Clas> lsc = new StuDao().getCid();
获取tid
List<Teacher> lst = new StuDao().getTid();
//把值存到req里面去
req.setAttribute("lst", lst);
req.setAttribute("lsc", lsc);
String q="吃饭,睡觉,打豆豆,跳舞";
String shobby = stu.getShobby();
String[] aa = shobby.split(",");//爱好的集合
for (String s : aa) {
System.out.println(q.contains(s)+"qq");
}
System.out.println(shobby);
req.setAttribute("sh", aa);
req.getRequestDispatcher("update.jsp").forward(req, resp);
}
}
//修改UpdateServlet
public class UpdateServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String sid=req.getParameter("sid");
String sid1=req.getParameter("sid1");
String sname=req.getParameter("sname");
String shobby=req.getParameter("shobby");
String tid=req.getParameter("tid");
String cid=req.getParameter("cid");
IStuBiz isb=new StuBiz();
Student stu=new Student(Integer.parseInt(sid), sname, shobby, new StuDao().getT(Integer.parseInt(tid)),new StuDao().getC(Integer.parseInt(cid)));
int n = isb.update(stu, Integer.parseInt(sid1));
if(n>0) {
out.print("<script>alert('修改成功!');location.href='index.jsp';</script>");
}
else {
out.print("<script>alert('修改失败!');location.href='pre.do?sid="+sid+"';</script>");
}
}
}
com.tag
复选框:CheckboxTag.java
public class CheckboxTag extends BodyTagSupport {
private String type;
private String name;
private String value;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public CheckboxTag(String type, String name, String value) {
super();
this.type = type;
this.name = name;
this.value = value;
}
public CheckboxTag() {
super();
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuffer sb=new StringBuffer();
sb.append("<input type='' name='' value='' />");
return null;
}
}
com.util
BaseDao 分页:
运用泛型传值
public class BaseDao<T> {
public static interface CallBack<E>{
//遍历ResultSet结果集
public List<E> forEach(ResultSet rs) throws SQLException, Exception;
}
/**
* 分页查询
* @param sql
* @param pageBean
* @return
*/
public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack){
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=DBAccess.getConnection();
//判断是否分页
if(null!=pageBean&&pageBean.isPagination()) {
//第一次查询总记录数
String countSql=this.getCountSql(sql);
stmt=conn.prepareStatement(countSql);
rs=stmt.executeQuery();
if(rs.next()) {
Object obj = rs.getObject(1);
pageBean.setTotal(Integer.parseInt(obj.toString()));
}
//DBHelper.close(conn, stmt, rs);
//第二次满足条件的分页数据集
sql=this.getPagerSql(sql, pageBean);
}
stmt=conn.prepareStatement(sql);
rs=stmt.executeQuery();
//处理结果集
return callBack.forEach(rs);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBAccess.close(conn, stmt, rs);
}
return null;
}
/**
* 替换成分页sql语句
* @param sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t";
}
/**
* 替换成分页sql语句
* @param sql
* @param pageBean
* @return
*/
private String getPagerSql(String sql,PageBean pageBean) {
return sql+" Limit "+pageBean.getStartIndex()+","+
pageBean.getRows();
}
}
本文详细介绍了一种自定义MVC框架的实现过程,包括项目搭建、架包导入、DAO层设计、控制器编写及分页查询功能。通过具体代码示例,展示了如何处理增删查改操作,并实现了数据分页显示。
493

被折叠的 条评论
为什么被折叠?



