SSM-员工管理系统Demo---带分页和校验(含源码)

页面展示:

 

 

 

前端JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="itcast" uri="http://itcast.cn/common/"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>员工管理系统</title>
<link href="<%=basePath%>/resource/css/dataTables.bootstrap.css" rel="stylesheet">
<link href="<%=basePath%>/resource/css/sb-admin-2.css" rel="stylesheet">
<link href="<%=basePath%>/resource/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="<%=basePath%>/resource/css/boot-crm.css" rel="stylesheet" type="text/css">
<link href="<%=basePath%>/resource/css/bootstrap-3.3.7.min.css" rel="stylesheet" type="text/css">
<link href="<%=basePath%>/resource/css/bootstrapValidator.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/resource/js/quote/jquery-2.1.1.min.js" ></script>
<script type="text/javascript" src="<%=basePath%>/resource/js/quote/bootstrap-3.3.7.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/resource/js/quote/bootstrapValidator.js"></script>
<script type="text/javascript" src="<%=basePath%>/resource/js/department/department.js"></script>

<div id="wrapper">
    <nav class="navbar navbar-inverse navbar-static-top" role="navigation"
         style="margin-bottom: 0">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand">员工管理系统</a>
        </div>
        <div class="navbar-default sidebar" role="navigation">
            <div class="sidebar-nav navbar-collapse">
                <ul class="nav" id="side-menu">
                    <li><a href="/department/list" class="active"><i class="fa fa-edit fa-fw"></i> 部门管理</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div id="page-wrapper">
        <div class="row">
            <div class="col-lg-12">
                <h1 class="page-header">部门管理</h1>
            </div>
        </div>
        <div class="panel panel-default">
            <div class="panel-body">
                <form class="form-inline" action="${pageContext.request.contextPath }/department/list" method="post">
                    <div class="form-group">
                        <label for="departmentId">部门编号</label>
                        <input type="text" class="form-control" id="departmentId" value="${queryDto.departmentId}" name="departmentId" autocomplete="off" maxlength="5">
                    </div>
                    <div class="form-group">
                        <label for="departmentName">部门名称</label>
                        <input type="text" class="form-control" id="departmentName" value="${queryDto.departmentName}" name="departmentName" autocomplete="off" maxlength="10">
                    </div>
                    <button type="submit" class="btn btn-primary">查询</button>
                    <a href="#"  class="btn btn-primary" data-toggle="modal" data-target="#departmentInsertDialog" id="insert">新增</a>
                    <input type="button" class="btn btn-danger"  value="批量删除" onclick="selectDelete()">
                </form>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <div class="panel panel-default">
                    <div class="panel-heading">部门信息列表</div>
                    <table class="table table-striped table-bordered table-hover" id="tableId">
                        <thead>
                        <tr>
                            <td align = center><input type="checkBox" id="selectAll" name="case" onclick="selectAllCheckBox('case')"/></td>
                            <th>部门编号</th>
                            <th>部门名称</th>
                            <th>部门主管</th>
                            <th>部门描述</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <c:forEach items="${page.rows}" var="item">
                            <tr align = center id="${item.departmentRecId}">
                                <td><input type="checkBox" id="case" name="case" value="${item.departmentRecId}"/></td>
                                <td>${item.departmentId}</td>
                                <td>${item.departmentName}</td>
                                <td>${item.departmentManager}</td>
                                <td>${item.departmentDescription}</td>
                                <td>
                                    <a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#departmentInsertDialog" onclick="edit(${item.departmentRecId})">编辑</a>
                                    <a href="#" class="btn btn-danger btn-xs" onclick="deleteDepartment(${item.departmentRecId})">删除</a>
                                </td>
                            </tr>
                        </c:forEach>
                        </tbody>
                    </table>
                    <%--返回分页对象时,这里面是page显示的内容,这样就能显示分页的标签--%>
                    <div class="col-md-12 text-right">
                        <itcast:page url="${pageContext.request.contextPath }/department/list"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增编辑对话框 -->
<div class="modal fade" id="departmentInsertDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    <span class="hide">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel2">部门信息</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal"  id="insertDepartmentForm"  action="#" method="get" >
                    <input type="hidden" id="insertDepartmentRecId" name="departmentRecId"/>

                    <div class="form-group">
                        <label for="insertDepartmentId" class="col-sm-2 control-label">部门编号</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="insertDepartmentId" placeholder="部门编号" name="departmentId"  autocomplete="off" maxlength="5" >
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="insertDepartmentName" class="col-sm-2 control-label">部门名称</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="insertDepartmentName" placeholder="部门名称" maxlength="20" autocomplete="off" name="departmentName">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="insertDepartmentManager" class="col-sm-2 control-label">部门主管</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="insertDepartmentManager" placeholder="部门主管" maxlength="20" autocomplete="off" name="departmentManager">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="insertDepartmentDescription" class="col-sm-2 control-label">部门描述</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="insertDepartmentDescription" placeholder="部门描述" maxlength="200" autocomplete="off" name="departmentDescription">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal" id="close">关闭</button>
                <button type="button" class="btn btn-primary" id="save" >保存 </button>
            </div>
        </div>
    </div>
</div>
</body>
</html>

JS:

$(function () {
    $("#insert").click(function () {
        var btn = document.getElementById('save');
        btn.addEventListener('click', insert, false);
    });

    $('#departmentInsertDialog').on('hide.bs.modal', function () {
        $('.modal-body').find('input').each(function(){$(this).val('');});
        $("#insertDepartmentId").removeAttr("disabled");
        $('#insertDepartmentForm')[0].reset();
        $('#insertDepartmentForm').data('bootstrapValidator').resetForm(true);
    })

    $('#insertDepartmentForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            departmentId: {
                validators: {
                    notEmpty: {
                        message: '部门编号不能为空'
                    },
                    remote: {
                        url: '/department/checkDepartmentId',
                        message: '部门编号已存在',
                        type: 'POST',
                    },
                    regexp: {
                        regexp: /(^[0-9]{2,5})$/,
                        message: '部门编号由2-5位数字组成!'
                    }
                }
            },
            departmentName: {
                validators: {
                    notEmpty: {
                        message: '部门名称不能为空'
                    },
                    regexp: {
                        regexp: /^([\u4e00-\u9fa5·s]{2,20}|[a-zA-Z.s]{2,20})$/,
                        message: '由汉字或英文字母组成的2-20位字符!'
                    }
                }
            },
            departmentManager: {
                validators: {
                    notEmpty: {
                        message: '部门主管不能为空'
                    },
                    regexp: {
                        regexp: /^([\u4e00-\u9fa5·s]{2,20}|[a-zA-Z.s]{2,20})$/,
                        message: '由汉字或英文字母组成的2-20位字符!'
                    }
                }
            },
            departmentDescription: {
                validators: {
                    notEmpty: {
                        message: '部门描述不能为空'
                    },
                }
            },
        }
    })

    $('#close').click(function() {
        $('#insertDepartmentForm').data('bootstrapValidator').resetForm(true);
    });

    $("#insertDepartmentForm").submit(function(ev){ev.preventDefault();});

});

function edit(departmentRecId) {
    $.ajax({
        type:"get",
        url:"/department/edit",
        data:{"departmentRecId":departmentRecId},
        success:function(data) {
            $("#insertDepartmentRecId").val(data.departmentRecId);
            $("#insertDepartmentId").val(data.departmentId).attr("disabled","disabled");
            $("#insertDepartmentName").val(data.departmentName);
            $("#insertDepartmentManager").val(data.departmentManager);
            $("#insertDepartmentDescription").val(data.departmentDescription);
        }
    });
    var btn = document.getElementById('save');
    btn.removeEventListener('click',insert,false);
    btn.addEventListener('click',update,false);
};

function update() {
    var bootstrapValidator = $("#insertDepartmentForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if(bootstrapValidator.isValid())
        $("#insertDepartmentForm").submit();
    else return;
    $("#insertDepartmentId").removeAttr("disabled");
    $.post("/department/update",$("#insertDepartmentForm").serialize(),function(data){
        alert("更新成功!");
        window.location.reload();
    });
};

function insert() {
    var bootstrapValidator = $("#insertDepartmentForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if(bootstrapValidator.isValid())
        $("#insertDepartmentForm").submit();
    else return;
    $.post("/department/insert", $("#insertDepartmentForm").serialize(), function (data) {
        alert("新增成功!");
        window.location.reload();
    });
};

function deleteDepartment(departmentRecId) {
    if (confirm('确定要删除吗?')) {
        $.post("/department/delete", {"departmentRecId": departmentRecId}, function (data) {
            alert("删除成功!");
            window.location.reload();
        });
    };
};

function selectDelete() {
    var checked = $("#tableId").find(":input[id='case']:checked");
    if (checked.length <= 0) {
        alert("你还没有选择任何内容!");
        return;
    };
    if(confirm("确定删除所选中的?")==true){
        var ids= "";
        checked.each(function(index, item) {
            var id = $(item).val();
            ids += id + ",";
        });
        if (ids.length > 0) {
            $.post("/department/deleteMany", {"ids": ids}, function (data) {
                alert("已勾选部门删除成功!");
                window.location.reload();
            });
        }
    };
};

function selectAllCheckBox(Obj){
    var collid = document.getElementById("selectAll");
    var coll = document.getElementsByName(Obj);
    if (collid.checked){
        for(var i = 0; i < coll.length; i++)
            coll[i].checked = true;
    }else{
        for(var i = 0; i < coll.length; i++)
            coll[i].checked = false;
    }
};

Cotroller:

package com.infosky.controller;

import com.infosky.dto.DepartmentDto;
import com.infosky.dto.QueryDto;
import com.infosky.service.Interface.DepartmentService;
import com.infosky.util.Page;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class DepartmentController
{
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping(value = "/department/list")
    public String list(QueryDto queryDto, Model model)
    {
        // 分页查询数据
        Page<DepartmentDto> page = departmentService.selectPageByQueryDto(queryDto);

        // 把分页查询的结果放到模型中
        model.addAttribute("page", page);
        model.addAttribute("queryDto", queryDto);
        return "department";
    }

    @RequestMapping(value = "/department/checkDepartmentId", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String checkDepartmentId(@RequestParam Integer departmentId) throws Exception {
        boolean result = true;
        List<DepartmentDto> department = departmentService.findDepartmentById(departmentId);
        if(department!=null&&department.size()>0){
            result = false;
        }
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

    // 数据回显
    @RequestMapping(value = "/department/edit")
    public
    @ResponseBody
    DepartmentDto edit(Integer departmentRecId)
    {
        return departmentService.selectDepartmentById(departmentRecId);
    }

    // 更新保存
    @RequestMapping(value = "/department/update")
    public
    @ResponseBody
    String update(DepartmentDto departmentdto)
    {
        departmentService.updateDepartment(departmentdto);
        return "OK";
    }

    // 新增
    @RequestMapping(value = "/department/insert")
    public
    @ResponseBody
    String insert(DepartmentDto departmentDto)
    {
        departmentService.insertDepartment(departmentDto);
        return "OK";
    }

    // 删除
    @RequestMapping(value = "/department/delete")
    public
    @ResponseBody
    Integer delete(Integer departmentRecId)
    {
        int count = departmentService.deleteDepartmentById(departmentRecId);
        return count;
    }

    // 批量删除
    @RequestMapping(value="/department/deleteMany")
    public
    @ResponseBody
    String deleteMany(String ids) {
        if (ids == null ) {
            return "FAILURE";
        }
        String[] array = ids.split(",");
        List<Integer> list = new ArrayList();
        for (String s: array) {
            int departmentRecId = Integer.parseInt(s);
            list.add(departmentRecId);
        }
        Integer count = departmentService.deleteMany(list);
        if (count != null && count > 0) {
            return "SUCCESS";
        }
        return "FAILURE";
    }
}

Service:

package com.infosky.service.Interface;

import com.infosky.dto.DepartmentDto;
import com.infosky.dto.QueryDto;
import com.infosky.util.Page;

import java.util.List;

public interface DepartmentService
{
    //根据条件分页查询
    Page<DepartmentDto> selectPageByQueryDto(QueryDto queryDto);

    //通过departmentRecId查询部门信息
    DepartmentDto selectDepartmentById(Integer departmentRecId);

    //查询部门编号
    List<DepartmentDto> findDepartmentById(Integer  departmentId);

    //更新
    void updateDepartment(DepartmentDto department);

    //删除
    int deleteDepartmentById(Integer departmentRecId);

    //批量删除
    Integer deleteMany(List list);

    //新增
    void insertDepartment(DepartmentDto department);

}

ServiceImpl:

package com.infosky.service.Impl;

import com.infosky.dto.DepartmentDto;
import com.infosky.dto.QueryDto;
import com.infosky.entity.Department;
import com.infosky.mapper.DepartmentMapper;
import com.infosky.service.Interface.DepartmentService;
import com.infosky.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("DepartmentService")
public class DepartmentServiceImpl implements DepartmentService
{
    @Autowired
    private DepartmentMapper departmentMapper;
    
    public Page<DepartmentDto> selectPageByQueryDto(QueryDto queryDto)
    {
        // 封装返回的page对象,包含分页信息和查询信息
        Page<DepartmentDto> page = new Page<DepartmentDto>();
        page.setPage(queryDto.getPage());
        page.setSize(queryDto.getSize());
        if (queryDto != null)
        {
            // 判断当前页
            if (queryDto.getSize() != null)
                page.setSize(queryDto.getSize());
            if (queryDto.getPage() != null)
            {
                // 设置查询条件,从哪一条数据开始查
                queryDto.setStartRow((queryDto.getPage() - 1) * queryDto.getSize() + 1);
                page.setPage(queryDto.getPage());

                if (queryDto.getDepartmentId() != null && !"".equals(queryDto.getDepartmentId()))
                {
                    queryDto.setDepartmentId(queryDto.getDepartmentId());
                }
                if (queryDto.getDepartmentName() != null && !"".equals(queryDto.getDepartmentName().trim()))
                {
                    queryDto.setDepartmentName(queryDto.getDepartmentName().trim());
                }
            }
        }

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("page",queryDto.getPage());
        map.put("size",queryDto.getSize());
        map.put("startRow",queryDto.getStartRow());
        map.put("departmentId",queryDto.getDepartmentId());
        map.put("departmentName",queryDto.getDepartmentName());

        // 分页查询数据结果集
        List<Department> departmentList = departmentMapper.selectDepartmentListByQueryDto(map);
        List<DepartmentDto> departmentDtoList = new ArrayList<DepartmentDto>();
        for (Department department : departmentList)
        {
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setDepartmentRecId(department.getDepartmentRecId());
            departmentDto.setDepartmentId(department.getDepartmentId());
            departmentDto.setDepartmentName(department.getDepartmentName());
            departmentDto.setDepartmentManager(department.getDepartmentManager());
            departmentDto.setDepartmentDescription(department.getDepartmentDescription());
            departmentDtoList.add(departmentDto);
        }

        // 查询到的数据总条数
        page.setTotal(departmentMapper.departmentCountByQueryDto(map));
        page.setRows(departmentDtoList);
        return page;
    }

    //查询部门编号,验证部门编号唯一性
    public List<DepartmentDto> findDepartmentById(Integer departmentId)
    {
        List<DepartmentDto> DepartmentList = new ArrayList<DepartmentDto>();
        List<Department> departmentList = departmentMapper.findDepartmentById(departmentId);
        for (Department department : departmentList)
        {
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setDepartmentId(department.getDepartmentId());
            DepartmentList.add(departmentDto);
        }
        return DepartmentList;
    }

    //查询部门信息
    public DepartmentDto selectDepartmentById(Integer DepartmentRecId)
    {
        Department department = departmentMapper.selectDepartmentById(DepartmentRecId);
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setDepartmentRecId(department.getDepartmentRecId());
        departmentDto.setDepartmentId(department.getDepartmentId());
        departmentDto.setDepartmentName(department.getDepartmentName());
        departmentDto.setDepartmentManager(department.getDepartmentManager());
        departmentDto.setDepartmentDescription(department.getDepartmentDescription());
        return departmentDto;
    }

    //更新
    public void updateDepartment(DepartmentDto departmentdto)
    {
        Department department =new Department();
        department.setDepartmentRecId(departmentdto.getDepartmentRecId());
        department.setDepartmentId(departmentdto.getDepartmentId());
        department.setDepartmentName(departmentdto.getDepartmentName());
        department.setDepartmentManager(departmentdto.getDepartmentManager());
        department.setDepartmentDescription(departmentdto.getDepartmentDescription());
        departmentMapper.updateDepartment(department);
    }

    //删除
    public int deleteDepartmentById(Integer DepartmentRecId)
    {
        return departmentMapper.deleteDepartmentById(DepartmentRecId);
    }

    //批量删除
    public Integer deleteMany(List list)
    {
        return departmentMapper.deleteMany(list);
    }

    //新增
    public void insertDepartment(DepartmentDto departmentdto)
    {
        Department department =new Department();
        department.setDepartmentRecId(departmentdto.getDepartmentRecId());
        department.setDepartmentId(departmentdto.getDepartmentId());
        department.setDepartmentName(departmentdto.getDepartmentName());
        department.setDepartmentManager(departmentdto.getDepartmentManager());
        department.setDepartmentDescription(departmentdto.getDepartmentDescription());
        departmentMapper.insertDepartment(department);
    }
    
}

Mapper:

package com.infosky.mapper;

import com.infosky.entity.Department;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository("DepartmentMapper")
public interface DepartmentMapper {

    //分页查询数据总条数
    int departmentCountByQueryDto(Map map);

    //分页查询数据结果集
    List<Department> selectDepartmentListByQueryDto(Map map);

    //查询部门编号
    List<Department> findDepartmentById(Integer departmentId);

    //通过departmentRecId查询部门信息
    Department selectDepartmentById(Integer departmentRecId);

    //更新
    void updateDepartment(Department department);

    //删除
    int deleteDepartmentById(Integer departmentRecId);

    //批量删除
    int deleteMany(List list);

    //新增
    void insertDepartment(Department department);
    
}

Mapper.xml:

<?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="com.infosky.mapper.DepartmentMapper">
    <resultMap id="Department" type="com.infosky.entity.Department">
        <id column="DEPARTMENT_REC_ID"  property="departmentRecId" jdbcType="INTEGER"/>
        <result column="DEPARTMENT_ID"  property="departmentId" jdbcType="INTEGER"/>
        <result column="DEPARTMENT_NAME"  property="departmentName" jdbcType="VARCHAR"/>
        <result column="DEPARTMENT_MANAGER"  property="departmentManager" jdbcType="VARCHAR"/>
        <result column="DEPARTMENT_DESCRIPTION"  property="departmentDescription" jdbcType="VARCHAR"/>
    </resultMap>

    <!--使用别名形式,下面可用resultType="com.infosky.entity.Department"-->
    <!--<sql id="Base_Column_List">-->
    <!--DEPARTMENT_REC_ID departmentRecId, DEPARTMENT_ID departmentId, DEPARTMENT_NAME departmentName,-->
    <!--DEPARTMENT_MANAGER departmentManager, DEPARTMENT_DESCRIPTION departmentDescription-->
   <!--</sql>-->

    <sql id="Base_Column_List">
        DEPARTMENT_REC_ID, DEPARTMENT_ID, DEPARTMENT_NAME, DEPARTMENT_MANAGER, DEPARTMENT_DESCRIPTION
    </sql>

    <!-- 根据QueryDto查询数据总条数 -->
    <select id="departmentCountByQueryDto" parameterType="com.infosky.dto.QueryDto" resultType="Integer">
        select count(*) from DEPARTMENT
    </select>

    <!-- 根据QueryDto分页查询数据结果集 -->
    <select id="selectDepartmentListByQueryDto" parameterType="java.util.Map" resultMap="Department">
        select
            <include refid="Base_Column_List" />
        from (select DEPARTMENT.* ,rownum rn from DEPARTMENT)
        <where>
            <if test="departmentId != null and departmentId != ''">
                DEPARTMENT_ID like '%'||#{departmentId,jdbcType=INTEGER}||'%'
            </if>
            <if test="departmentName!= null and department_name != ''">
                and DEPARTMENT_NAME like '%'||#{departmentName,jdbcType=VARCHAR}||'%'
            </if>
            and rn &lt;=(#{startRow}+#{size}-1) AND rn &gt;=#{startRow}
        </where>
        order by DEPARTMENT_ID asc
    </select>

    <!-- 查询部门信息 -->
    <select id="selectDepartmentById" parameterType="java.lang.Integer" resultMap="Department">
        select
            <include refid="Base_Column_List" />
        from DEPARTMENT
        <where>
            DEPARTMENT_REC_ID = #{departmentRecId,jdbcType=INTEGER}
        </where>
        order by DEPARTMENT_REC_ID asc
    </select>

    <!-- 查询部门编号 -->
    <select id="findDepartmentById" parameterType="java.lang.Integer" resultMap="Department">
        select
            DEPARTMENT_ID
        from DEPARTMENT
        <where>
            DEPARTMENT_ID = #{departmentId}
        </where>
    </select>

    <!-- 更新 -->
    <update id="updateDepartment" parameterType="com.infosky.entity.Department" >
    update DEPARTMENT
    set DEPARTMENT_ID = #{departmentId,jdbcType=INTEGER},
        DEPARTMENT_NAME = #{departmentName,jdbcType=VARCHAR},
        DEPARTMENT_MANAGER = #{departmentManager,jdbcType=VARCHAR},
        DEPARTMENT_DESCRIPTION = #{departmentDescription,jdbcType=VARCHAR}
    where DEPARTMENT_REC_ID = #{departmentRecId,jdbcType=INTEGER}
    </update>

    <!-- 删除 -->
    <delete id="deleteDepartmentById" parameterType="java.lang.Integer">
      delete from DEPARTMENT
      where DEPARTMENT_REC_ID = #{departmentRecId,jdbcType=INTEGER}
    </delete>

    <!-- 新增 -->
    <insert id="insertDepartment" parameterType="com.infosky.entity.Department" >
      insert into DEPARTMENT (DEPARTMENT_REC_ID, DEPARTMENT_ID, DEPARTMENT_NAME,
      DEPARTMENT_MANAGER, DEPARTMENT_DESCRIPTION)
      values (seq_department.nextval, #{departmentId,jdbcType=INTEGER}, #{departmentName,jdbcType=VARCHAR},
      #{departmentManager,jdbcType=VARCHAR}, #{departmentDescription,jdbcType=VARCHAR})
    </insert>

    <!-- 批量删除 -->
    <delete id="deleteMany" parameterType="java.util.List">
        delete from DEPARTMENT where DEPARTMENT_REC_ID in
        <foreach item="ids" collection="list" open="(" separator="," close=")">
            #{ids}
        </foreach>
    </delete>
</mapper>

Entity:

package com.infosky.entity;

import java.io.Serializable;

public class Department implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer departmentRecId;

    private Integer departmentId;

    private String departmentName;

    private String departmentManager;

    private String departmentDescription;

    public Integer getDepartmentRecId() {
        return departmentRecId;
    }

    public void setDepartmentRecId(Integer departmentRecId) {
        this.departmentRecId = departmentRecId;
    }

    public Integer getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(Integer departmentId) {
        this.departmentId = departmentId;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName == null ? null : departmentName.trim();
    }

    public String getDepartmentManager() {
        return departmentManager;
    }

    public void setDepartmentManager(String departmentManager) {
        this.departmentManager = departmentManager == null ? null : departmentManager.trim();
    }

    public String getDepartmentDescription() {
        return departmentDescription;
    }

    public void setDepartmentDescription(String departmentDescription) {
        this.departmentDescription = departmentDescription == null ? null : departmentDescription.trim();
    }

    @Override
    public String toString() {
        return "Department{" +
                "departmentRecId=" + departmentRecId +
                ", departmentId=" + departmentId +
                ", departmentName='" + departmentName + '\'' +
                ", departmentManager='" + departmentManager + '\'' +
                ", departmentDescription='" + departmentDescription + '\'' +
                '}';
    }
}

Dto:

package com.infosky.dto;

import java.io.Serializable;

public class DepartmentDto implements Serializable {

    private Integer departmentRecId;

    private Integer departmentId;

    private String departmentName;

    private String departmentManager;

    private String departmentDescription;

    public Integer getDepartmentRecId() {
        return departmentRecId;
    }

    public void setDepartmentRecId(Integer departmentRecId) {
        this.departmentRecId = departmentRecId;
    }

    public Integer getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(Integer departmentId) {
        this.departmentId = departmentId;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName == null ? null : departmentName.trim();
    }

    public String getDepartmentManager() {
        return departmentManager;
    }

    public void setDepartmentManager(String departmentManager) {
        this.departmentManager = departmentManager == null ? null : departmentManager.trim();
    }

    public String getDepartmentDescription() {
        return departmentDescription;
    }

    public void setDepartmentDescription(String departmentDescription) {
        this.departmentDescription = departmentDescription == null ? null : departmentDescription.trim();
    }

    @Override
    public String toString() {
        return "Department{" +
                "departmentRecId=" + departmentRecId +
                ", departmentId=" + departmentId +
                ", departmentName='" + departmentName + '\'' +
                ", departmentManager='" + departmentManager + '\'' +
                ", departmentDescription='" + departmentDescription + '\'' +
                '}';
    }
}

QueryDto:

package com.infosky.dto;

 public class QueryDto
{
    //当前页数
    private Integer page=1;

    //每页显示记录数
    private Integer size = 5;

    //当前页 开始记录号
    private Integer startRow = 1;

    private Integer departmentId;

    private String departmentName;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

    public Integer getStartRow() {
        return startRow;
    }

    public void setStartRow(Integer startRow) {
        this.startRow = startRow;
    }

    public Integer getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(Integer departmentId) {
        this.departmentId = departmentId;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }


}

工具类:

NavigationTag:
package com.infosky.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.Map;

/**
 * 显示格式 上一页 1 2 3 4 5 下一页
 */
public class NavigationTag extends TagSupport {
    static final long serialVersionUID = 2372405317744358833L;
    
    /**
     * request 中用于保存Page<E> 对象的变量名,默认为“page”
     */
    private String bean = "page";
    
    /**
     * 分页跳转的url地址,此属性必须
     */
    private String url = null;
    
    /**
     * 显示页码数量
     */
    private int number = 5;
    
    @Override
    public int doStartTag() throws JspException {
        JspWriter writer = pageContext.getOut();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Page page = (Page)request.getAttribute(bean); 
        if (page == null) 
            return SKIP_BODY;
        url = resolveUrl(url, pageContext);
        try {
            //计算总页数
            int pageCount = page.getTotal() / page.getSize();
            if (page.getTotal() % page.getSize() > 0) {
                pageCount++;
            }
            writer.print("<nav><ul class=\"pagination\">");
            //显示“上一页”按钮
            if (page.getPage() > 1) {
                String preUrl = append(url, "page", page.getPage() - 1);
                preUrl = append(preUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + preUrl + "\">上一页</a></li>");
            } else {
                writer.print("<li class=\"disabled\"><a href=\"#\">上一页</a></li>");
            }
            //显示当前页码的前2页码和后两页码 
            //若1 则 1 2 3 4 5, 若2 则 1 2 3 4 5, 若3 则1 2 3 4 5,
            //若4 则 2 3 4 5 6 ,若10  则 8 9 10 11 12
            int indexPage = (page.getPage() - 2 > 0)? page.getPage() - 2 : 1;
            for(int i=1; i <= number && indexPage <= pageCount; indexPage++, i++) {
                if(indexPage == page.getPage()) {
                    writer.print( "<li class=\"active\"><a href=\"#\">"+indexPage+"<span class=\"sr-only\">(current)</span></a></li>");
                    continue;
                }
                String pageUrl  = append(url, "page", indexPage);
                pageUrl = append(pageUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + pageUrl + "\">"+ indexPage +"</a></li>");
            }
            //显示“下一页”按钮
            if (page.getPage() < pageCount) {
                String nextUrl  = append(url, "page", page.getPage() + 1);
                nextUrl = append(nextUrl, "rows", page.getSize());
                writer.print("<li><a href=\"" + nextUrl + "\">下一页</a></li>");
            } else {
                writer.print("<li class=\"disabled\"><a href=\"#\">下一页</a></li>");
            }
            writer.print("</nav>");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SKIP_BODY;
    }
    
    private String append(String url, String key, int value) {

        return append(url, key, String.valueOf(value));
    }
    
    /**
     * 为url 参加参数对儿
     * 
     * @param url
     * @param key
     * @param value
     * @return
     */
    private String append(String url, String key, String value) {
        if (url == null || url.trim().length() == 0) {
            return "";
        }

        if (url.indexOf("?") == -1) {
            url = url + "?" + key + "=" + value;
        } else {
            if(url.endsWith("?")) {
                url = url + key + "=" + value;
            } else {
                url = url + "&amp;" + key + "=" + value;
            }
        }
        
        return url;
    }
    
    /**
     * 为url 添加翻页请求参数
     * 
     * @param url
     * @param pageContext
     * @return
     * @throws JspException
     */
    private String resolveUrl(String url, javax.servlet.jsp.PageContext pageContext) throws JspException{
        //UrlSupport.resolveUrl(url, context, pageContext)
        Map params = pageContext.getRequest().getParameterMap();
        for (Object key:params.keySet()) {
            if ("page".equals(key) || "rows".equals(key)) continue;
            Object value = params.get(key);
            if (value == null) continue;
            if (value.getClass().isArray()) {
                url = append(url, key.toString(), ((String[])value)[0]);
            } else if (value instanceof String) {
                url = append(url, key.toString(), value.toString());
            }
        }
        return url;
    }
    
    

    /**
     * @return the bean
     */
    public String getBean() {
        return bean;
    }

    /**
     * @param bean the bean to set
     */
    public void setBean(String bean) {
        this.bean = bean;
    }

    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }

    /**
     * @param url the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }

    public void setNumber(int number) {
        this.number = number;
    }
    
}

Page:

package com.infosky.util;

import java.util.List;

public class Page<T>
{
    //总记录数
    private int total;

    //当前页数
    private int page;

    //每页显示条数
    private int size;

    private List<T> rows;

    public int getTotal()
    {
        return total;
    }
    public void setTotal(int total)
    {
        this.total = total;
    }
    public int getPage()
    {
        return page;
    }
    public void setPage(int page)
    {
        this.page = page;
    }
    public int getSize()
    {
        return size;
    }
    public void setSize(int size)
    {
        this.size = size;
    }
    public List<T> getRows()
    {
        return rows;
    }
    public void setRows(List<T> rows)
    {
        this.rows = rows;
    }
}

tld标签:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
    <tlib-version>2.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>common</short-name>
    <uri>http://itcast.cn/common/</uri>
    <display-name>Common Tag</display-name>
    <description>Common Tag library</description>

    <tag>
        <name>page</name>
        <tag-class>com.infosky.util.NavigationTag</tag-class>
        <body-content>JSP</body-content>
        <description>create navigation for paging</description>
        <attribute>
            <name>bean</name>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>number</name>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>url</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

 web.xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <description>配置Spring配置文件路径</description>
    <param-name>contextConfigLocation</param-name>
    <!-- 如果是监听多个文件,可用‘,’隔开 -->
    <param-value>classpath:spring-*.xml</param-value>
  </context-param>


  <listener>
    <description>配置Spring上下文监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <listener>
    <description>Introspector缓存清除监听器</description>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <listener>
    <description>request监听器</description>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

  <!-- 配置Spring字符编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--log4j配置文件加载-->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <!--启动一个watchdog线程每1800秒扫描一下log4j配置文件的变化-->
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>1800000</param-value>
  </context-param>
  <!--spring log4j监听器-->
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

  <!-- Spring MVC 核心控制器 DispatcherServlet 配置开始 -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 可以通过contextConfigLocation来自定义SpringMVC配置文件的位置,如不指定,则默认在WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,
         此时文件名必须为[<servlet-name>]-servlet.xml,否则会出错-->
    <!--以下init-param是自定义SpringMVC的配置文件的位置 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 拦截设置 -->
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <!-- 此处可以配置成*.do,对应struts的后缀习惯 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- Spring MVC 核心配置结束 -->

  <!-- 激活Tomcat的defaultServlet来处理静态文件 -->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
  </servlet-mapping>

  <!-- session 时间 -->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <welcome-file-list>
    <welcome-file>/WEB-INF/page/index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

spring-mvc.xml:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <description>Spring MVC Configuration</description>

    <!-- 启用spring mvc 注解, 默认的注解映射的支持 -->
    <mvc:annotation-driven/>

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.infosky.controller"/>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="zh_CN" />
    </bean>

    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>

    <!-- 支持返回json(避免IE在ajax请求时,返回json出现下载文件 ) -->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>text/json;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射, 配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
            </list>
        </property>
    </bean>

    <!-- 默认的视图解析器  -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="3">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html" />
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑  -->
    </bean>


    <!-- 配置springMVC处理上传文件的信息 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="10485760000" />
        <property name="maxInMemorySize" value="40960" />
    </bean>

    <!-- Bean解析器,级别高于默认解析器,寻找bean对象进行二次处理 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>

    <!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
    <mvc:default-servlet-handler />
    <!-- 静态资源映射 -->
    <!--<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>-->

    <!-- 对静态资源放行  -->
    <mvc:resources location="/resource/css/" mapping="/css/**"/>
    <mvc:resources location="/resource/js/" mapping="/js/**"/>
    <mvc:resources location="/resource/fonts/" mapping="/fonts/**"/>

</beans>

spring-context:

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
       default-lazy-init="true">

    <description>Spring Configuration</description>

    <!-- 开启注解处理器 -->
    <context:annotation-config/>

    <!-- 开启组件自动扫描;使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <context:component-scan base-package="com.infosky"><!-- base-package 如果多个,用“,”分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--<!– 自动扫描 –>-->
    <!--<context:component-scan base-package="com.vitelon.v"/>-->

    <!--引入属性文件 为了下面配置数据库相关参数-->
    <context:property-placeholder location="classpath:dbconfig.properties" />


    <!-- dataSource 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 --><!--扫描包形式配置Mapper(mapper代理方式开发)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--配置mapper接口-->
        <property name="basePackage" value="com.infosky.mapper"/>
        <!--配置sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 对dataSource 数据源进行事务管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 事务管理 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 对insert,create,update,modify,delete,remove 开头的方法进行事务管理,只要有异常就回滚 -->
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="modify*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"  read-only="false"/>
            <tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Throwable" read-only="false"/>
            <!-- find,get,select,count开头的方法,开启只读,提高数据库访问性能 -->
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="count*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <!-- 对其他方法 使用默认的事务管理 -->
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <!-- 事务 aop 配置 -->
    <aop:config>
        <aop:pointcut id="serviceMethods" expression="execution(public * infosky.service..*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
    </aop:config>

    <!-- 配置使Spring采用CGLIB代理 --><!-- 开启基于@AspectJ切面的注解处理器 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>

log4j.properties:

#日志输出级别
log4j.rootLogger=debug,stdout,D,E

#设置stdout的日志输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#输出日志到控制台的方式,默认为System.out
log4j.appender.stdout.Target = System.out
#设置使用灵活布局
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%c (%rms)] - %m%n

#每天产生一个日志文件
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
#设置的输出日志
log4j.appender.D.File=D:/warlogs/logs/log.txt
#设置的日志最大限制
log4j.appender.D.MaxFileSize=6000KB
#最多只保存20个备份文件
log4j.appender.D.MaxBackupIndex=20
#输出INFO级别以上的日志
og4j.appender.D.Threshold=debug
log4j.appender.D.Append = true
log4j.appender.D.ImmediateFlush = true
#log4j.appender.D.DatePattern ='.'yyyy-MM-dd
#设置使用灵活布局
log4j.appender.D.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n

log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D:/warlogs/logs/error/error.txt
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
#log4j.appender.E.DatePattern = '_'yyyyMMdd'.log'
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n

generatorConfig.xml:

#日志输出级别
log4j.rootLogger=debug,stdout,D,E

#设置stdout的日志输出控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#输出日志到控制台的方式,默认为System.out
log4j.appender.stdout.Target = System.out
#设置使用灵活布局
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%c (%rms)] - %m%n

#每天产生一个日志文件
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
#设置的输出日志
log4j.appender.D.File=D:/warlogs/logs/log.txt
#设置的日志最大限制
log4j.appender.D.MaxFileSize=6000KB
#最多只保存20个备份文件
log4j.appender.D.MaxBackupIndex=20
#输出INFO级别以上的日志
og4j.appender.D.Threshold=debug
log4j.appender.D.Append = true
log4j.appender.D.ImmediateFlush = true
#log4j.appender.D.DatePattern ='.'yyyy-MM-dd
#设置使用灵活布局
log4j.appender.D.layout=org.apache.log4j.PatternLayout
#灵活定义输出格式
log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n

log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D:/warlogs/logs/error/error.txt
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
#log4j.appender.E.DatePattern = '_'yyyyMMdd'.log'
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%l (%rms)] - %m%n

dbconfig.properties:

#Oracle
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@172.11.129.114:1521:ORCL
jdbc.username=chendd
jdbc.password=111111
##<!-- 初始化连接 -->
#jdbc.initialSize=10
##最大连接数量
#jdbc.maxActive=50
##<!-- 最大空闲连接 -->
#jdbc.maxIdle=20
##<!-- 最小空闲连接 -->
#jdbc.minIdle=5
##<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
#jdbc.maxWait=60000

pom:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.infosky</groupId>
  <artifactId>springmvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

    <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <!-- spring版本号 -->
      <spring.version>4.1.1.RELEASE</spring.version>
      <!-- mybatis版本号 -->
      <mybatis.version>3.2.6</mybatis.version>
      <!-- log4j日志文件管理包版本 -->
      <slf4j.version>1.7.7</slf4j.version>
      <log4j.version>1.2.17</log4j.version>
      <!-- jackson包版本 -->
      <jackson.version>2.5.0</jackson.version>
    </properties>


    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>

      <!--分页标签依赖包-->
      <!--<dependency>-->
        <!--<groupId>com.github.pagehelper</groupId>-->
        <!--<artifactId>pagehelper</artifactId>-->
        <!--<version>5.1.2</version>-->
      <!--</dependency>-->

      <!--spring单元测试依赖-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
      </dependency>
      <!-- springMVC核心包 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <!-- spring核心包 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.0.9.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
      </dependency>
      <!-- AOP begin -->
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.7.4</version>
      </dependency>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.7.4</version>
      </dependency>
      <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
      </dependency>
      <!-- AOP end -->

      <!-- mybatis核心包 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
      </dependency>

      <!--mybatis spring 插件 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
      </dependency>

      <!-- Oracle数据库驱动包 -->
      <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>10.2.0.4.0</version>
      </dependency>

      <!-- connection pool -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.5</version>
        <scope>runtime</scope>
      </dependency>

      <!-- 日志文件管理包 -->
      <!-- log start -->
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
      </dependency>

      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
      </dependency>

      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
      </dependency>
      <!-- log end -->

      <!--servlet-->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
      </dependency>
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>

      <!-- 映入JSON -->
      <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
      </dependency>
      <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
      </dependency>

      <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.1</version>
        <classifier>jdk15</classifier>
      </dependency>

      <!-- 用dom4j解析xml文件 -->
      <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
      </dependency>


      <!-- ehcache -->
      <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.6.9</version>
      </dependency>
      <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-web</artifactId>
        <version>2.0.4</version>
      </dependency>

      <!-- 上传组件包 -->
      <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
      </dependency>

      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
      </dependency>

      <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.9</version>
      </dependency>

      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.0</version>
      </dependency>

      <!--唯一性校验用到的相关依赖包-->
      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.7</version>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.6</version>
      </dependency>
      <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>2.8.6</version>
      </dependency>


      <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
      </dependency>

      <!-- commons-beanutils -->
      <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.7.0</version>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>

      <!-- freemarker -->
      <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.19</version>
      </dependency>

      <!-- dom4j读取XML -->
      <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
      </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
    </dependencies>

    <build>
      <finalName>chenjianjun</finalName>
      <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>

        <!--逆向工程插件-->
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.2</version>
          <configuration>
            <verbose>true</verbose>
            <overwrite>true</overwrite>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>

      <!--解决maven项目编译后classes文件中没有.xml问题-->
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>
    </build>
  </project>

 

posted on 2019-04-10 09:58  农夫三拳有點疼  阅读(1464)  评论(0编辑  收藏  举报

导航