基于spring+springmvc+mybatis的图书管理系统

来源:互联网 发布:java elasticsearch 编辑:程序博客网 时间:2024/05/19 21:19
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %><!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> <script type="text/javascript" src="statics/My97DatePicker/WdatePicker.js"></script><script type="text/javascript" src="statics/js/jquery-1.8.3.js"></script><script type="text/javascript">    function check() {         var btype = $("#btype").val();            /*var bname = $("#bname").val();        var bauthor = $("#bauthor").val();        var btime = $("#btime").val();                    if (bname == "") {            alert("图书名称不能为空");            return false;        }        if (bauthor == "") {            alert("作者姓名不能为空");            return false;        }        if (btime == "") {            alert("购买日期不能为空");            return false;        }            */        /*        var regBtime=/^(19|20)\d{2}-(1[0-2])|0?[1-9]-(3[0-1]|[1-2]\d|0?[1-9])$/;        if (regBtime.test(btime) == false) {            alert("购买日期无效");            return false;        }        */        if (btype == -1) {            alert("请选择图书类别");            return false;        }        return true;    }    </script></head><body>    <form:form action="book" commandName="book" method="post" onsubmit="return check();">    <form:errors path="*" ></form:errors>        <table width="500" border="1">            <caption>新增图书信息</caption>            <tr>                <td width="91">图书名称:</td>                <td width="216"><input type="text" name="bname" id="bname" /></td>                <td width="171"> </td>            </tr>            <tr>                <td>图书作者:</td>                <td><input type="text" name="bauthor" id="bauthor" /></td>                <td> </td>            </tr>            <tr>                <td>购买日期:</td>                <td> <input type="text" class="Wdate" id="btime" name="btime"  onClick="WdatePicker({dateFmt:'yyyy-MM-dd'})" size="21"  value="" /></td>                <td>yyyy-MM-dd格式</td>            </tr>            <tr>                <td>图书类别:</td>                <td><select id="btype" name="btype">                        <option value="-1">--选择所属分类--</option>                        <option value="0">计算机/软件</option>                        <option value="1">小说/文摘</option>                        <option value="2">杂项</option>                </select></td>                <td> </td>            </tr>            <tr>                <td colspan="3" align="center"><input type="submit"                    value="新增图书" /></td>            </tr>        </table>    </form:form></body></html><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@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"><title>图书详细信息</title></head><body>    <h2>图书详细信息</h2>    <Br /> 图书名称:${requestScope.book.bname }    <Br /> 图书作者:${requestScope.book.bauthor }    <Br /> 出版时间:${requestScope.book.btime }    <Br /> 图书类别:    <c:choose>        <c:when test="${book.btype eq 0}">计算机/软件</c:when>        <c:when test="${book.btype eq 1}">小说/文摘</c:when>        <c:when test="${book.btype eq 2}">杂项</c:when>    </c:choose></body></html><%@ 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>出错了!!!</body></html><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@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"><title>查询图书</title><style type="text/css">td {    text-align: center;}table, tr, td {    border: 1px solid black;    border-collapse: collapse;}a.add {    text-decoration: none;    color: red;}div {width:900px;    text-align: center;}</style><script type="text/javascript" src="statics/js/jquery-1.8.3.js"></script><script type="text/javascript">    $(document).ready(function() {        $("#all").click(function() {            var $bids = $("input[name=bids]");            if ($(this).is(":checked")) {                $bids.prop("checked", true);            } else {                $bids.prop("checked", false);            }        });        $("#delBtn").click(function() {            var $bids = $("input[name=bids]");            var flag=false;                        $bids.each(function(index,i){                if($(i).is(":checked")){                    flag=true;                    return;                }            });            if(flag){                if(confirm("确认删除吗?")){                    var bids="";                    for(var i=0;i<$bids.length;i++){                        if($bids[i].checked){                            if(i==$bids.length-1){                                bids+="bids="+$bids[i].value;                            }else{                                bids+="bids="+$bids[i].value+"&";                            }                                                }                    }                                    location.href="deleteBooks?"+bids;                }            }            else{                alert("请选择要删除的图书");                return false;            }        });        $("#btnSearch").click(function() {                        $("#f2").submit();        });    });        function turnPage(pageIndex){               location.href="book?pageIndex="+pageIndex;    } </script></head><body>    <c:if test="${not empty msg }">        <script type="text/javascript">            alert("${msg}");        </script>    </c:if>            <table width="900" border="1">            <caption>                <h1>图书信息</h1>            </caption>            <tr class="bg">                <td>选择</td>                <td>图书名称</td>                <td>图书作者</td>                <td>购买时间</td>                <td>图书分类</td>                <td>删除</td>                <td>更新</td>            </tr>            <c:forEach items="${p.list}" var="book">                <tr>                    <td><input type="checkbox" name="bids" value="${book.bid}" /></td>                    <td><a href="book/${book.bid}">${book.bname }</a></td>                    <td>${book.bauthor }</td>                    <td>${book.btime }</td>                    <td><c:choose>                            <c:when test="${book.btype eq 0}">计算机/软件</c:when>                            <c:when test="${book.btype eq 1}">小说/文摘</c:when>                            <c:when test="${book.btype eq 2}">杂项</c:when>                        </c:choose></td>                    <td>                        <%-- <a href="deleteBook?bid=${book.bid}" onclick="return confirm('确认删除吗?')">删除</a> --%>                        <form action="book/${book.bid}" method="post">                            <input type="hidden" name="_method" value="delete" /> <input                                type="submit" value="删除" />                        </form>                                            </td>                    <td>                        <a href="book/${book.bid}/edit" >更新</a>                                            </td>                </tr>            </c:forEach>        </table>        <br />         <form id="f1" action="deleteBooks">        <input type="checkbox" id="all" />全选           <input id="delBtn"            type="button" value="删除所选" />        </form>                    <div>    <a onclick="turnPage(1)">首页</a>         <a onclick="turnPage(${requestScope.p.prevPage})">上一页</a>     <a onclick="turnPage(${requestScope.p.nextPage})">下一页</a>     <a onclick="turnPage(${requestScope.p.totalPage})">末页</a>      第 ${requestScope.p.currPage }/共 ${requestScope.p.totalPage }页    转到第:     <select id="pageIndex" name="pageIndex" onchange="turnPage(this.value)">     <c:forEach var="i" begin="1" end="${requestScope.p.totalPage }">     <option value="${i}">${i}</option>     </c:forEach>     </select>    </div>        <br />    <br />    <a class="add" href="../book/new">新增图书信息</a></body></html><%@ 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><script type="text/javascript" src="js/jquery-1.8.3.js"></script><script type="text/javascript">    function check() {        var bname = $("#bname").val();        var bauthor = $("#bauthor").val();        var btime = $("#btime").val();        var btype = $("#btype").val();                if (bname == "") {            alert("图书名称不能为空");            return false;        }        if (bauthor == "") {            alert("作者姓名不能为空");            return false;        }        if (btime == "") {            alert("购买日期不能为空");            return false;        }            var regBtime=/^(19|20)\d{2}-(1[0-2])|0?[1-9]-(3[0-1]|[1-2]\d|0?[1-9])$/;        if (regBtime.test(btime) == false) {            alert("购买日期无效");            return false;        }        if (btype == -1) {            alert("请选择图书类别");            return false;        }        return true;    }    $(document).ready(function(){        $("#bname").val("${requestScope.book.bname}");        $("#bauthor").val("${requestScope.book.bauthor}");        $("#btime").val("${requestScope.book.btime}");        $("#btype").val(["${requestScope.book.btype}"]);    });</script></head><body>    <form action="update" method="post" onsubmit="return check();">        <input type="hidden"  name="bid" value="${requestScope.book.bid }"/>        <table width="500" border="1">            <caption>更新图书信息</caption>            <tr>                <td width="91">图书名称:</td>                <td width="216"><input type="text" name="bname" id="bname" /></td>                <td width="171"> </td>            </tr>            <tr>                <td>图书作者:</td>                <td><input type="text" name="bauthor" id="bauthor" /></td>                <td> </td>            </tr>            <tr>                <td>购买日期:</td>                <td><input type="text" name="btime" id="btime" /></td>                <td>yyyy-MM-dd格式</td>            </tr>            <tr>                <td>图书类别:</td>                <td><select id="btype" name="btype">                        <option value="-1">--选择所属分类--</option>                        <option value="0">计算机/软件</option>                        <option value="1">小说/文摘</option>                        <option value="2">杂项</option>                </select></td>                <td> </td>            </tr>            <tr>                <td colspan="3" align="center"><input type="submit"                    value="更新图书" /></td>            </tr>        </table>    </form></body></html><%@ 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="upload" method="post" enctype="multipart/form-data">上传者:<input type="text" name="name"/><br/>上传文件:<input type="file" name="f1"/><input type="submit" value="上传"/></form></body></html><%@ 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>上传成功!!!</body></html><?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">                <context:component-scan base-package="cn.jbit.ssm"></context:component-scan><!-- 连接数据库的 --><context:property-override location="classpath:db.properties"/><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"p:driverClassName="" p:url="" p:username="" p:password=""></bean><!-- dbcp数据源连接数据库<context:property-placeholder location="classpath:db.properties"/><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" ></bean> --><!-- 配置sqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"  p:mapperLocations="classpath:cn/jbit/ssm/dao/*.xml" p:configLocation="classpath:mybatis-config.xml"> </bean> <!--  扫描接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:sqlSessionFactoryBeanName="sqlSessionFactory" p:basePackage="cn.jbit.ssm.dao"></bean></beans><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <typeAliases>        <typeAlias alias="Book" type="cn.jbit.ssm.entity.Book"/>    </typeAliases>        </configuration>dataSource.driverClassName=com.mysql.jdbc.DriverdataSource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8dataSource.username=rootdataSource.password=123456<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">    <context:component-scan base-package="cn.jbit"></context:component-scan>    <mvc:annotation-driven></mvc:annotation-driven>    <!-- 对静态资源的解析 -->    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>    <!-- 视图解析器 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:suffix=".jsp"p:prefix="/WEB-INF/jsp/"p:viewClass="org.springframework.web.servlet.view.JstlView"/>    <!-- 配置全局异常    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">        <property name="exceptionMappings">        <props>            <prop key="java.lang.Exception">error</prop>        </props>        </property>    </bean> -->    <!-- 配置文件上传的解析器 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="defaultEncoding" value="utf-8"></property>    <property name="maxUploadSize" value="50000"></property>    </bean></beans><?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>ch_ssm_bookmanage</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>     <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!-- 不配置默认WEB-INF下面的applicationContext.xml -->  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>     <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--  配置过滤器 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>  </web-app>aopalliance.jarasm-4.2.jaraspectjweaver.jarcglib-3.1.jarclassmate-1.1.0.jarcommons-dbcp-1.4.jarcommons-fileupload-1.2.2.jarcommons-io-2.4.jarcommons-lang3-3.1.jarcommons-logging-1.2.jarcommons-pool-1.5.6.jarcommons-pool-1.6.jarhibernate-validator-5.2.4.Final.jarhibernate-validator-annotation-processor-5.2.4.Final.jarhibernate-validator-cdi-5.2.4.Final.jarjackson-annotations-2.5.0.jarjackson-core-2.5.0.jarjackson-databind-2.5.0.jarjavax.el-2.2.4.jarjavax.el-api-2.2.4.jarjboss-logging-3.2.1.Final.jarjstl.jarjunit-4.12.jarlog4j-1.2.17.jarlog4j-api-2.2.jarlog4j-core-2.2.jarmybatis-3.3.0.jarmybatis-spring-1.2.0.jarmysql-connector-java-5.1.38-bin.jarorg.hamcrest.core_1.3.0.v201303031735.jarslf4j-api-1.7.12.jarslf4j-api-1.7.5.jarslf4j-log4j12-1.7.12.jarslf4j-log4j12-1.7.5.jarspring-aop-4.3.0.RELEASE.jarspring-aspects-4.3.0.RELEASE.jarspring-beans-4.3.0.RELEASE.jarspring-context-4.3.0.RELEASE.jarspring-context-support-4.3.0.RELEASE.jarspring-core-4.3.0.RELEASE.jarspring-expression-4.3.0.RELEASE.jarspring-jdbc-4.3.0.RELEASE.jarspring-orm-4.3.0.RELEASE.jarspring-test-4.3.0.RELEASE.jarspring-tx-4.3.0.RELEASE.jarspring-web-4.3.0.RELEASE.jarspring-webmvc-4.3.0.RELEASE.jarstandard.jarvalidation-api-1.1.0.Final.jar package cn.jbit.ssm.biz;import java.util.List;import java.util.Map;import cn.jbit.ssm.entity.Book;public interface BookBiz {    /*添加图书*/    public int addBook(Book book) throws Exception;    /*查询当前页所有图书*/        public List<Book> getAllBooksByPage(Map<String,Object> map) throws Exception;    /*根据bid删除一本图书*/    public int deleteBookByBid(int bid) throws Exception;    /*更新图书*/    public int updateBook(Book book) throws Exception;    /*根据bid查询图书*/    public Book getBookByBid(int bid) throws Exception;        /*删除多本图书*/    public int deleteBookByBids(int [] bids) throws Exception;    /*根据条件查询图书总记录数*/    public int countAll(Book book) throws Exception;    /*根据条件分页查询图书*/    public List<Book> searchBookByPage(Map<String,Object> map) throws Exception;    /*根据图书名称和图书分类查询图书*/    public List<Book> searchBook(Book book) throws Exception;}package cn.jbit.ssm.biz.impl;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import cn.jbit.ssm.biz.BookBiz;import cn.jbit.ssm.dao.BookDao;import cn.jbit.ssm.entity.Book;@Service("bookBiz")@Transactional(propagation=Propagation.REQUIRED)public class BookBizImpl implements BookBiz {        @Autowired    private BookDao bookDao;    @Override    public int addBook(Book book) throws Exception {        // TODO Auto-generated method stub        return bookDao.addBook(book);    }    @Override    public List<Book> getAllBooksByPage(Map<String, Object> map) throws Exception {        // TODO Auto-generated method stub        return bookDao.getAllBooksByPage(map);    }    @Override    public int deleteBookByBid(int bid) throws Exception {        // TODO Auto-generated method stub        return bookDao.deleteBookByBid(bid);    }    @Override    public int updateBook(Book book) throws Exception {        // TODO Auto-generated method stub        return bookDao.updateBook(book);    }    @Override    public Book getBookByBid(int bid) throws Exception {        // TODO Auto-generated method stub        return bookDao.getBookByBid(bid);    }    @Override    public int deleteBookByBids(int[] bids) throws Exception {        // TODO Auto-generated method stub        return bookDao.deleteBookByBids(bids);    }    @Override    public int countAll(Book book) throws Exception {        // TODO Auto-generated method stub        return bookDao.countAll(book);    }    @Override    public List<Book> searchBookByPage(Map<String, Object> map) throws Exception {        // TODO Auto-generated method stub        return bookDao.searchBookByPage(map);    }    @Override    public List<Book> searchBook(Book book) throws Exception {        // TODO Auto-generated method stub        return bookDao.searchBook(book);    }    }package cn.jbit.ssm.entity;import java.io.Serializable;import java.sql.Date;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;import org.apache.ibatis.type.Alias;import org.springframework.format.annotation.DateTimeFormat;import org.springframework.format.annotation.NumberFormat;@Alias("Book")public class Book  implements Serializable{        private static final long serialVersionUID = 1L;    public Book(String bname, int btype) {        super();        this.btype = btype;    }    private int bid;//图书编号    @NotNull    private String bname;//图书名称    @NotNull    @Pattern(regexp="[\u4e00-\u9fe5a-zA-Z0-9_]{2,}")    private String bauthor;//图书作者    @Override    public String toString() {        return "Book [bid=" + bid + ", bname=" + bname + ", bauthor=" + bauthor                + ", btime=" + btime + ", btype=" + btype + ", bstartTime="                + bstartTime + ", bendTime=" + bendTime + "]";    }    //@DateTimeFormat(pattern="yyyy/MM/dd")    @NotNull    @DateTimeFormat(pattern="yyyy-MM-dd")    private Date btime;//出版时间        @NotNull        private int btype=-1;//图书类别        public Date getBstartTime() {        return bstartTime;    }    public void setBstartTime(Date bstartTime) {        this.bstartTime = bstartTime;    }    public Date getBendTime() {        return bendTime;    }    public void setBendTime(Date bendTime) {        this.bendTime = bendTime;    }    private Date bstartTime;    private Date bendTime;            public Book() {        super();    }    public Book(String bname, String bauthor, Date btime, int btype) {        super();        this.bname = bname;        this.bauthor = bauthor;        this.btime = btime;        this.btype = btype;    }    public Book(int bid, String bname, String bauthor, Date btime, int btype) {        super();        this.bid = bid;        this.bname = bname;        this.bauthor = bauthor;        this.btime = btime;        this.btype = btype;    }    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 String getBauthor() {        return bauthor;    }    public void setBauthor(String bauthor) {        this.bauthor = bauthor;    }    public Date getBtime() {        return btime;    }    public void setBtime(Date btime) {        this.btime = btime;    }    public int getBtype() {        return btype;    }    public void setBtype(int btype) {        this.btype = btype;    }    }package cn.jbit.ssm.tool;import java.util.List;public class Page<T> {private int currPage=1;//当前页private int prevPage;//上一页private int nextPage;//下一页private int totalCount;//总记录数private int totalPage;//总页数private int pageSize=5;//每页显示记录数private List<T> list;//当前页查询结果public int getCurrPage() {    return currPage;}public void setCurrPage(int currPage) {    this.currPage = currPage;}public int getPrevPage() {    int prevPage=currPage-1;    if(prevPage<1)        prevPage=1;    return prevPage;}public void setPrevPage(int prevPage) {    this.prevPage = prevPage;}public int getNextPage() {    int nextPage=currPage+1;    if(nextPage>totalPage)        nextPage=totalPage;    return nextPage;}public void setNextPage(int nextPage) {    this.nextPage = nextPage;}public int getTotalCount() {    return totalCount;}public void setTotalCount(int totalCount) {    this.totalCount = totalCount;    if(totalCount>0){        this.setTotalPage((totalCount-1)/pageSize+1);    }}public int getTotalPage() {    return totalPage;}public void setTotalPage(int totalPage) {    this.totalPage = totalPage;}public int getPageSize() {    return pageSize;}public void setPageSize(int pageSize) {    this.pageSize = pageSize;}public List<T> getList() {    return list;}public void setList(List<T> list) {    this.list = list;}}package cn.jbit.ssm.web;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import cn.jbit.ssm.biz.BookBiz;import cn.jbit.ssm.entity.Book;import cn.jbit.ssm.tool.Page;/** *  * <p>Title:BookController</p> * <p>Description: 控制器</p> * @author  张健 * @blog www.cnblogs.com/zhangjianblog * @date 2017年1月10日下午2:18:09 * @version Neon Release (4.6.0) */@Controllerpublic class BookController {        @Autowired    private BookBiz bookBiz;            //查询当前页所有图书    @RequestMapping("/book")    public String index(@RequestParam(name="pageIndex",required=false)Integer pageIndex,            Model model) throws Exception{        Map<String,Object> map=new HashMap<String,Object>();        Page<Book> p=new Page<Book>();        p.setTotalCount(bookBiz.countAll(new Book()));        if(null==pageIndex){            pageIndex=1;        }        p.setCurrPage(pageIndex);        map.put("startRow",(pageIndex-1)*p.getPageSize());        map.put("pageSize",p.getPageSize());        List<Book> list=bookBiz.getAllBooksByPage(map);        p.setList(list);        model.addAttribute("p",p);        return "list";    }            @RequestMapping("/book/new")    public String _new(){        return "addBook";    }        @RequestMapping("/book/{bid}")    public String show(@PathVariable("bid") int bid,Model model) throws Exception{        Book book=bookBiz.getBookByBid(bid);        model.addAttribute("book",book);        return "detailBook";    }            @RequestMapping(value = "/book", method = {RequestMethod.POST,RequestMethod.GET})    public String create(@ModelAttribute("book") @Valid Book book,            BindingResult bindingResult, Model model) throws Exception {        if (bindingResult.hasErrors()) {                        return "addBook";        }        int count = bookBiz.addBook(book);        if (count > 0) {            model.addAttribute("msg", "添加成功!!!");        } else {            model.addAttribute("msg", "添加失败");        }        return "redirect:/book";    }                                                                            /*        查询所有图书信息     @Autowired    private BookBiz bookBiz;    @RequestMapping("/list")    public String getAllBooks(Model model) throws Exception{        List<Book> list=bookBiz.getAllBooks();        model.addAttribute("list",list);        return "list";    }         新增图书信息     @RequestMapping("/toAdd")    public String toAdd(){            return "addBook";    }    @RequestMapping("/add")    public String addBook(Book book,Model model) throws Exception{        int count=0;        try {            count = bookBiz.addBook(book);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        if(count>0){            model.addAttribute("msg", "添加成功");        }else{            model.addAttribute("msg", "添加失败");                }        return "forward:list";    }         根据bid删除图书信息     @RequestMapping(value="/delete/{bid}",method=RequestMethod.DELETE)    public String deleteBookByBid(@PathVariable("bid") int bid,RedirectAttributes ra) throws Exception{                int count=0;        try {            count = bookBiz.deleteBookByBid(bid);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        if(count>0){            ra.addFlashAttribute("msg", "删出成功");        }else{            ra.addFlashAttribute("msg", "删除失败");        }        return "redirect:/list";    }    @RequestMapping("/delete")    public String deleteBookByBid(@RequestParam("bid") int bid,Model model) throws Exception{        int count=0;        try {            count = bookBiz.deleteBookByBid(bid);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        if(count>0){            model.addAttribute("msg", "删除成功");        }else{            model.addAttribute("msg", "删除失败");        }        return "forward:list";    }        更新图书信息     @RequestMapping(value="/update",method={RequestMethod.PUT})    public String updateBook(Book book,Model model,RedirectAttributes ra) throws Exception{        int count=0;        try {            count = bookBiz.updateBook(book);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        if(count>0){            ra.addFlashAttribute("msg", "更新成功");        }else{            ra.addFlashAttribute("msg", "更新失败");        }        return "redirect:/list";    }        @ExceptionHandler(value=Exception.class)    public String defaultHandlerException(Exception e,Model m){        m.addAttribute("e",e);        return "error";    }    @RequestMapping("/testException")     public String testException() throws Exception{        throw new Exception("测试全局异常");    }*/} package cn.jbit.ssm.dao;import java.util.List;import java.util.Map;import cn.jbit.ssm.entity.Book;/** *  * <p>Title:BookDao</p> * <p>Description: </p> * @author  张健 * @blog www.cnblogs.com/zhangjianblog * @date 2017年1月10日上午10:45:32 * @version Neon Release (4.6.0) */public interface BookDao {        /*添加图书*/    public int addBook(Book book);    /*查询当前页所有图书*/        public List<Book> getAllBooksByPage(Map<String,Object> map);    /*根据bid删除一本图书*/    public int deleteBookByBid(int bid);    /*更新图书*/    public int updateBook(Book book);    /*根据bid查询图书*/    public Book getBookByBid(int bid);        /*删除多本图书*/    public int deleteBookByBids(int [] bids);    /*根据条件查询图书总记录数*/    public int countAll(Book book);    /*根据条件分页查询图书*/    public List<Book> searchBookByPage(Map<String,Object> map);    /*根据图书名称和图书分类查询图书*/    public List<Book> searchBook(Book book);}<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="cn.jbit.ssm.dao.BookDao">  <resultMap type="Book" id="BookResultMap"> <id property="bid" column="b_id"></id><result property="bname" column="b_name"/><result property="bauthor" column="b_author"/><result property="btime" column="b_time"/><result property="btype" column="b_type"/>  </resultMap>      <select id="getAllBooksByPage" parameterType="hashmap" resultMap="BookResultMap">          select *from book limit #{startRow},#{pageSize}  </select>  <select id="searchBookByPage" parameterType="hashmap" resultMap="BookResultMap">        select * from book          <trim prefix="where" prefixOverrides="and">        <if test="bname!=null">            and b_name like concat('%',#{bname},'%')        </if>        <if test="bauthor!=null">            and b_author like concat('%',#{bauthor},'%')        </if>        <if test="bstartTime!=null">            and b_time >=#{bstartTime}        </if>        <if test="bendTime!=null">            and b_time <![CDATA[<]]>=#{bendTime}        </if>            <if test="btype!=-1">            and b_type=#{btype}        </if>        </trim>        limit #{startRow},#{pageSize}    </select>    <select id="countAll" resultType="int" parameterType="Book">        SELECT count(1) FROM book        <trim prefix="where" prefixOverrides="and">        <if test="bname!=null">            and b_name like concat('%',#{bname},'%')        </if>        <if test="bauthor!=null">            and b_author like concat('%',#{bauthor},'%')        </if>        <if test="bstartTime!=null">            and b_time >=#{bstartTime}        </if>        <if test="bendTime!=null">            and b_time <![CDATA[<]]>=#{bendTime}        </if>            <if test="btype!=-1">            and b_type=#{btype}        </if>        </trim>    </select>    <select id="getAllBooks" resultMap="BookResultMap">  select *from book  </select>      <delete id="deleteBookByBid" parameterType="int">delete from book where b_id=#{bid}</delete><insert id="addBook" parameterType="Book">insert into book(b_name,b_author,b_time,b_type) values (#{bname},#{bauthor},#{btime},#{btype})</insert><update id="updateBook" parameterType="Book"><!-- update book set b_name=#{bname},b_author=#{bauthor},b_time=#{btime},b_type=#{btype} where b_id=#{bid} -->update Book    <set>            <if test="bname!=null">b_name=#{bname}</if>            <if test="bauthor!=null">b_author=#{bauthor}</if>            <if test="btime!=null">b_time=#{btime}</if>            <if test="btype!=null">b_type=#{btype}</if>    </set></update><select id="getBookByBid" parameterType="int" resultMap="BookResultMap">select *from book where b_id=#{bid}</select><select id="searchBook" parameterType="Book" resultMap="BookResultMap">select *from book where b_name like b_name=#{bname} and b_type=#{btype}</select></mapper>

阅读全文
1 1
原创粉丝点击