自定义MVC三

完成t_mvc_book表的增删改查
1、通用分页的jar、自定义mvc框架、自定义标签
导入jar、导入之前写好的pageTag、自定义mvc.xml

pageTag

private static final long serialVersionUID = -553969530960334073L;

    private PageBean pageBean;

    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }
    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            out.print(toHTML());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return super.doStartTag();
    }

    private String toHTML() {
        // TODO Auto-generated method stub
        StringBuilder sb=new StringBuilder();
        //拼接下一次发送请求所要提交得隐藏得form表单
        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) {
                //上一次请求可能携带页码namepage得参数,但是改参数在前面以及单独赋值
                //为什么要单独赋值?因为上一次请求时第一页得数据,下一次可能时第二页,以后这前后请求page对应得值不一样,需要单独赋值
                if(!"page".equals(entry.getKey())) {
//                    <input type='hidden' name='hobby' value='1'>
//                    <input type='hidden' name='hobby' value='2'>
                    //[1,2]
                    for(String val:entry.getValue()) {
                        sb.append(" <input type='hidden' name='"+entry.getKey()+"' value='"+val+"'> ");
                    }
                }
            }
        }

        sb.append(" </form>");
        //拼接分页条
        sb.append(" <div style='text-align: right; font-size: 12px;'> ");
        sb.append(" 每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页&nbsp;&nbsp;<a ");
        sb.append(" href='javascript:gotoPage(1)'>首页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getpreviousPage()+")'>上一页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a>&nbsp;&nbsp;<input type='text'");
        sb.append(" id='skipPage'");
        sb.append(" style='text-align: center; font-size: 12px; width: 50px;'>&nbsp;&nbsp;<a");
        sb.append(" href='javascript:skipPage()'>Go</a>");
        sb.append(" </div>");
        //拼接分页所需要得js代码
        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();
    }

mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
    <!--
        config标签:可以包含0~N个action标签
    -->
<config>
    <!--
        action标签:可以饱含0~N个forward标签
        path:以/开头的字符串,并且值必须唯一 非空
        type:字符串,非空
    -->
    
    <action path="/Cal" type="com.web.CalAction">
        <forward name="res" path="/res.jsp" redirect="false" />
    </action>
    <action path="/book" type="com.web.BookAction">
        <forward name="list" path="/BookList.jsp" redirect="false" />
        <forward name="edit" path="/bookEdit.jsp" redirect="false" />
        <forward name="tolist" path="/book.action?methodName=list" />
        
    </action>
</config>

 

2、dao层 通用的增删改方法

Bookdao

public class Bookdao extends BaseDao<Book>{
    /**
     * 查询所有
     * @param book
     * @param pageBean
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
        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 SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int edit(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException  {
        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 SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int add(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException  {
        String sql="insert into t_mvc_book values(?,?,?)";
        return super.executeupdate(sql,new String[] {"bid","bname","price"}, book);
    }
    /**
     * 删除
     * @param book
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int del(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException  {
        String sql="delete from t_mvc_book where bid=?";
        return super.executeupdate(sql,new String[] {"bid"}, book);
    }
    
    
}

3、web层
mvc.xml进行配置

private Book book=new Book();
    private Bookdao bookDao=new Bookdao();
    /**
     * 分页查询
     * @param req
     * @param resp
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String list(HttpServletRequest req,HttpServletResponse resp) {
        PageBean pageBean=new PageBean();
        pageBean.setRequest(req);
        List<Book> list;
        try {
            list = this.bookDao.list(book, pageBean);
            System.out.println(list);
            req.setAttribute("booklist",list);
            req.setAttribute("pageBean",pageBean);
        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "list";
    }
    /**
     * 跳转到增加或者修改页面
     * @param req
     * @param resp
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String preSave(HttpServletRequest req,HttpServletResponse resp){
        //bid的类型是int类型,而int类型的默认值是0,如果jsp为传递bid的参数值,那么bid=0;
        if(book.getBid()==0) {
            System.out.println("增加逻辑...");
        }else {
            //修改数据回显逻辑 bid=1 book-->list.add(book)-->${book.bname}
            Book b;
            try {
                b = this.bookDao.list(book, null).get(0);
                req.setAttribute("book", b);
            } catch (InstantiationException | IllegalAccessException | SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //新增页面与修改页面是同一个JSP
        return "edit";
    }
    /**
     * 新增
     * @param req
     * @param resp
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String add(HttpServletRequest req,HttpServletResponse resp) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
        this.bookDao.add(book);
        //新增完刷新页面
        return "tolist";
        
    }
    /**
     * 修改
     * @param req
     * @param resp
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String edit(HttpServletRequest req,HttpServletResponse resp) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
        this.bookDao.edit(book);
        return "tolist";
        
    }
    /**
     * 删除
     * @param req
     * @param resp
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String del(HttpServletRequest req,HttpServletResponse resp) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
        this.bookDao.del(book);
        return "tolist";
        
    }
    @Override
    public Book getModel() {
        
        return book;
    }

 


4、jsp

首页

 

<%@ 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="/jt" %>
<!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>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
    <br>

    <form action="${pageContext.request.contextPath}/book.action?methodName=list"
        method="post">
        书名:<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>&nbsp;&nbsp;
                     <a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>&nbsp;
                </td>
            </tr>
        </c:forEach>
    </table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

 

修改新增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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book.action" method="post">
   <input type="hidden" name="methodName" value="${book.bname == null?'add':'edit' }">
   书籍ID:<input type="text" name="bid" value="${book.bid }"><br>
   书籍名称:<input type="text" name="bname" value="${book.bname }"><br>
   书籍价格:<input type="text" name="price" value="${book.price }"><br>
   <input type="submit">
</form>
</body>
</html>

下面运行下效果

新增

修改

删除

 

posted @ 2019-06-27 18:32  youshutup  阅读(320)  评论(0编辑  收藏  举报