使用ssm框架编写简单图书管理系统(二)

项目中用到了分页 然后我使用的是mybatis的插件pagehelper

官网地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

需要导入jar包 

坐标地址:  

<!--分页插件-->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.1.2</version>
</dependency>

在spring配置文件中加上配置

<!-- 4  配置sqlsessionfactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="druidDataSource"/>
    <!-- 加载xml文件-->
    <property name="mapperLocations" value="classpath:cn/vp/dao/*.xml"/>
    <!-- 给类取别名mybayis-->
    <property name="typeAliasesPackage" value="cn.vp"/>
    <!--分页插件-->
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    <value>
                        helperDialect=mysql
                        reasonable=true
                    </value>
                </property>
            </bean>
        </array>
    </property>
</bean>

  1.   涉及的2个类  PageHelper PageInfo

只有紧跟在 PageHelper.startPage 方法后的第一个MyBatis 的查询(select)方法会被分页

 PageHelper.startPage(now,2);//该工具类设置当前页码数和每页显示的行数

List<Book>books = bookService.queryAll(bookTypeid, bookname, borrow);

//PageInfo工具类存放查询的结果集

PageInfo<Book>pageInfo = new PageInfo<Book>(books);

map.put("pageInfo",pageInfo);

2.      页面用法

<c:forEachitems="${pageInfo.list}"var="pp"> //list为PageInfo工具类的属性,取存放的数据集合

第${pageInfo.pageNum}/${pageInfo.pages}页// pageNum代表当前页码数 pages总页数

项目核心代码

项目目录:


BookController.java

@Controller
@SessionAttributes({"bookTypes", "bookInfos"})
public class BookController implements ServletContextAware {

    private ServletContext servletContext;

    @Autowired
    BookTypeService bookTypeService;

    @Autowired
    BookService bookService;

    /**
     * 跳转到首页
     * @param map 保存的数据类似于
     * @return
     */
    @RequestMapping("/add.htm")
    public String getBookType(ModelMap map) {
        List<BookType> bookTypes = bookTypeService.queryAll();
        PageHelper.startPage(1, 3);
        List<BookInfo> bookInfos = bookService.queryAll();
        PageInfo<BookInfo> pageInfo = new PageInfo<BookInfo>(bookInfos);
        map.put("pageInfo", pageInfo);
        System.out.println(bookInfos);
        map.put("bookTypes", bookTypes);
        return "forward:/list.jsp";
    }


    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    /**
     * 根据图书id删除图书   参数为数组是因为可以批量删除 也可以穿单个bookid
     * @param bookid 图书id
     * @return 跳转到查询
     */
    @RequestMapping(value = "/ajaxDelect.htm",produces={"application/json;","text/html;charset=UTF-8;"})
    public  String ajaxDelect(Integer[] bookid){
        int i = bookService.deleteByIds(bookid);
        System.err.println("受影响的行数:"+i);
        System.out.println("1111111");
        return "forward:/ajaxQuety.htm";
    }



    //点击详情 先把数据查询出来跳转到详情页面并赋值
    // 因为修改和详情都会调用这个方法 所以多加一个参数
    @RequestMapping("queryByid.htm")
    public String queryByid(@RequestParam("bookid")Integer bookid,ModelMap modelMap,Integer type){
        BookInfo bookInfo = bookService.queryByid(bookid);
        modelMap.put("bookInfo",bookInfo);
        //如果为type==1则为修改页面 2为详情页面
        if (type==1) {
            return "forward:/edit.jsp";
        }else {
            return "forward:/showBook.jsp";
        }
    }

    /**
     * 修改
     * @param bookInfo 图书
     * @return 跳转到首页
     */
    @RequestMapping("editBookInfoById.htm")
    public String editBookInfoById(BookInfo bookInfo){
        String path = bookInfo.getPath();
        System.err.println(path);
        int i = bookService.updateBookInfo(bookInfo);
        System.err.println("修改条数"+i);
        return "forward:/add.htm";
    }

    /**
     * 新增
     * @param bookInfo 图书
     * @return 返回到首页
     */
    @RequestMapping("addBook.htm")
    public String addBook(BookInfo bookInfo){
        int i = bookService.addBook(bookInfo);
        System.err.println("新增的条数"+i);
        return "forward:/add.htm";
    }


    /**
     * ajax 查询
     * @param bookTypeid 图书类型id
     * @param bookname 图书名称
     * @param borrow 是否借阅
     * @param now 当前页数
     * @return 返回json类型的图书集合
     */
    @RequestMapping(value = "/ajaxQuety.htm",produces={"application/json;","text/html;charset=UTF-8;"})
    @ResponseBody//返回结果不会被解析为跳转路径
    public String ajaxQuery(@RequestParam(value="bookTypeid",required=false,defaultValue="0")String bookTypeid,
                            String bookname,
                            @RequestParam(value="borrow",required=false,defaultValue="-1")  String borrow,
                            @RequestParam(value = "now", required = false, defaultValue = "1")Integer now) {
        System.out.println("bookTypeid:"+bookTypeid+"bookname:"+ bookname+"borrow:"+borrow);
        //分页 now 页码  pagesize 显示几条
        PageHelper.startPage(now, 3);
        List<BookInfo> bookInfos = bookService.query(bookTypeid, bookname, borrow);
        //将数据库获取到数据放入pageInfo里  在jsp页面上获取 需要通过pageInfo.list获取
        PageInfo<BookInfo> pageInfo = new PageInfo<BookInfo>(bookInfos);
        //转成json返回出去
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageInfo", pageInfo);
        //因为里面有date类型数据所以需要转换一下
        return JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd");
    }


    /**
     * 照片上传和回显
     * @param fileImage 图片名称
     * @return json类型的对象
     */
    @RequestMapping("imageupload.htm")
    @ResponseBody
    public String imageUpload(@RequestParam("fileImage") CommonsMultipartFile fileImage) {
        System.out.println("111111");
        // 获取上传图片的位置
        String path = servletContext.getRealPath("/images/");
        System.out.println("上传的路径为:" + path);
        // 获取文件名称
        String name = fileImage.getOriginalFilename();
        // 创建file对象 写入
        File file = new File(path, name);
        try {
            fileImage.getFileItem().write(file);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 将上传的图片路径以json的方式返回客户端
        String imagePath = "images/" + name;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imagePath", imagePath);
        // 将对象转为json格式
        String json = jsonObject.toJSONString();
        System.out.println("json:" + json);
        return json;
    }

}

list.jsp(首页)

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="/js/jquery.form.js"></script>
</head>
<body>
<div style="height: 600px; width: 800px; margin: 0px auto;">


    <form action="" method="post" id="query">
        图书分类<select name="bookTypeid">
        <option value="0">全部</option>
        <c:forEach items="${bookTypes}" var="type">
            <option value="${type.id}"
                    <c:if test="${type.id==bookTypeid}">selected="selected"</c:if>>${type.typeName}</option>
        </c:forEach>
    </select> &nbsp; 图书名称<input name="bookname" value="${bookname}">
        &nbsp;是否借阅 <select name="borrow">
        <option value="-1">请选择</option>
        <option value="0"
                <c:if test="${borrow==0 }">selected="selected" </c:if>>未借阅
        </option>
        <option value="1"
                <c:if test="${borrow==1 }">selected="selected" </c:if>>已借阅
        </option>
    </select> <input type="hidden" name="now" id="pageno">
        <input type="button" onclick="queryBooks()" value="查询">
    </form>


    <a href="add.jsp">添加</a> &nbsp;
    <button onclick="deleteAll();">批量删除</button>
    <form id="delete" action="bookservlet.do" method="post">
        <input type="hidden" name="choose" value="7">
        <table border="1">
            <thead>
            <tr>
                <td><input type="checkbox"
                           onclick="changecheckBox(this.checked);"></td>
                <td>图书编号</td>
                <td>图书分类</td>
                <td>图书名称</td>
                <td>作者</td>
                <td>出版社</td>
                <td>图片</td>
                <td>操作</td>
                <td>详情</td>
                <td>删除</td>
                <td>修改</td>
            </tr>
            </thead>
            <tbody id="bookbody">
            <c:forEach items="${pageInfo.list}" var="book">
                <tr>
                    <td><input type="checkbox" name="bookid" id="bookid"
                               value="${book.bookId }"></td>
                    <td>${book.bookCode }</td>
                    <td>${book.bookType.typeName}</td>
                    <td>${book.bookName }</td>
                    <td>${book.bookAuthor }</td>
                    <td>${book.publishPress }</td>
                    <td><img src="/${book.path }"></td>
                    <td><c:if test="${book.isBorrow ==0 }">未借阅</c:if> <c:if
                            test="${book.isBorrow ==1 }">已借阅</c:if></td>
                    <td><a href="/queryByid.htm?bookid=${book.bookId}&&type=2">详情</a></td>
                    <td><a href="javascript:delect(${book.bookId});">删除</a></td>
                    <td><a href="/queryByid.htm?bookid=${book.bookId}&&type=1">修改</a></td>
                </tr>
            </c:forEach>
            </tbody>
            <tfoot id="bookfoot">
            <tr>
                <td colspan="9"><a href="javascript:queryBooks(1);">首页</a>&nbsp;&nbsp;
                    <a href="javascript:queryBooks(${pageInfo.pageNum-1});">上一页</a>&nbsp;&nbsp;
                    <a href="javascript:queryBooks(${pageInfo.pageNum+1});">下一页</a>&nbsp;&nbsp;
                    <a href="javascript:queryBooks(${pageInfo.pages});">末页</a>&nbsp;&nbsp;
                    ${pageInfo.pageNum}/${pageInfo.pages}</td>
            </tr>
            </tfoot>
        </table>
    </form>
</div>
</body>
<script type="text/javascript">

    // 全选
    function changecheckBox(checked) {
        $("input[name='bookid']").attr("checked", checked);
    }

    function delect(bookid) {
        $.ajax({
            url: "/ajaxDelect.htm?bookid=" + bookid,
            dataType: "json",
            type: "post",
            success: function (data) {
                alert("删除成功");
                loaddata(data);
            }
        });
    }

    function deleteAll() {
        var obj = {
            url: "/ajaxDelect.htm",
            dataType: "json",
            type: "post",
            success: function (data) {
                loaddata(data);
            }
        };
        $("#delete").ajaxSubmit(obj);
    }


    function queryBooks(pageno) {
        $("#pageno").attr("value", pageno);
        //编写ajax
        var obj = {
            url: "/ajaxQuety.htm",
            dataType: "json",
            type: "post",
            success: function (data) {
                loaddata(data);
            }
        };
        //jqeury.from ajax提交表单
        $("#query").ajaxSubmit(obj);

    }

    function loaddata(data) {
        $("#bookbody").html("");
        $(data.pageInfo.list).each(function () {
            var borrow = (this.isBorrow == 0) ? "未借阅" : "已借阅";
            $("#bookbody").append(' <tr>\n' +
                '                    <td><input type="checkbox" id="bookid" name="bookid"\n' +
                '                               value="' + this.bookId + '"></td>\n' +
                '                    <td>' + this.bookCode + '</td>\n' +
                '                    <td>' + this.bookType.typeName + '</td>\n' +
                '                    <td>' + this.bookName + '</td>\n' +
                '                    <td>' + this.bookAuthor + '</td>\n' +
                '                    <td>' + this.publishPress + '</td>\n' +
                '                    <td><img src="/' + this.path + '"></td>\n' +
                '                    <td>' + borrow + '</td>\n' +
                '                    <td><a href="/queryByid.htm?bookid=\'+this.bookId+\'&&type=2">详情</a></td>\n' +
                '                    <td><a href="javascript:delect(' + this.bookId + ');">删除</a></td>\n' +
                '                    <td><a href="/queryByid.htm?bookid=' + this.bookId + '&&type=1">修改</a></td>\n' +
                '                </tr>');

        });
        $("#bookfoot").html("");
        $("#bookfoot").append(' <tr>\n' +
            '                <td colspan="9"><a href="javascript:queryBooks(1);">首页</a>&nbsp;&nbsp;\n' +
            '                    <a href="javascript:queryBooks(' + (data.pageInfo.pageNum - 1) + ');">上一页</a>&nbsp;&nbsp;\n' +
            '                    <a href="javascript:queryBooks(' + (data.pageInfo.pageNum + 1) + ');">下一页</a>&nbsp;&nbsp;\n' +
            '                    <a href="javascript:queryBooks(' + (data.pageInfo.pages) + ');">末页</a>&nbsp;&nbsp;\n' +
            '                    ' + (data.pageInfo.pageNum) + '/' + (data.pageInfo.pages) + '页\n' +
            '                </td>\n' +
            '            </tr>');
    }

</script>

</html>

edit.jsp(修改页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html>
<head>
    <title>修改</title>
    <style type="text/css">
        #body {
            margin: 0px auto;
            width: 800px;
            height: 600px;
        }
    </style>

    <script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
    <!-- jQuery.form.js是一个form插件,支持ajax表单提交和ajax文件上传 -->
    <script type="text/javascript" src="/js/jquery.form.js"></script>
</head>

<body>
<div id="body">
    <div style="margin: 0px auto; width: 500px;">
        <form action="/editBookInfoById.htm" method="post" enctype="multipart/form-data" id="imm">
            <table border="1px" style="text-align: center;">
                <tr>
                    <td>图书编号</td>
                    <input type="hidden" name="bookId" value="${bookInfo.bookId}">
                    <td><input id="code" name="bookCode" onblur="checkCode();" value="${bookInfo.bookCode}"><span
                            id="codeMessage"></span></td>
                </tr>
                <tr>
                    <td>图书名称</td>
                    <td><input name="bookName" value="${bookInfo.bookName}"></td>
                </tr>
                <tr>
                    <td>图书分类</td>
                    <td style="text-align: left;"><select name="bookType.id">
                        <c:forEach items="${bookTypes}" var="bookTy">
                            <option <c:if test="${bookInfo.bookType.id==bookTy.id}">selected</c:if> value="${bookTy.id }">${bookTy.typeName}</option>
                        </c:forEach>
                    </select></td>
                </tr>
                <tr>
                    <td>作者</td>
                    <td><input name="bookAuthor" value="${bookInfo.bookAuthor}"></td>
                </tr>
                <tr>
                    <td>出版社</td>
                    <td><input name="publishPress" value="${bookInfo.publishPress}"></td>
                </tr>
                <tr>
                    <td>出版时间</td>
                    <td><input type="date" name="publishDate" value="<fmt:formatDate value="${bookInfo.publishDate }" pattern="yyyy-MM-dd"/>"></td>
                </tr>
                <tr>
                    <td>图片上传</td>
                    <td><img id="img" width="50dp" height="50dp" src="/${bookInfo.path }">
                        <input name="fileImage" type="file" onchange="uploadImage();">
                        <input type="text" hidden name="path" id="path" value="${bookInfo.path }">
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="提交"> <input
                            type="button" value="取消"></td>

                </tr>
            </table>
        </form>
    </div>

    <script type="text/javascript">

        function uploadImage() {
            //编写ajax
            var obj = {
                url: "/imageupload.htm",
                dataType: "json",
                type: "post",
                success: function (data) {
                    $("#img").attr("src", data.imagePath);
                    $("#path").val(data.imagePath);
                }
            };
            //提交form
            $("#imm").ajaxSubmit(obj);

        }
    </script>
</div>
</body>


</html>

显示的页面(有点丑)




阅读更多

没有更多推荐了,返回首页