SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

Easter79
• 阅读 752

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一) 个人小程序,可以微信扫一扫看看。谢谢支持

http://pan.baidu.com/s/1kTMp0WZ  最新项目下载地址

访问地址

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

1.基于easyui的 增 删 改 查

2.基于poi的导出excel

3.基于 SpringMVC HandlerInterceptor验证

项目结构图

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

源代码和jar包等下会上传是百度网盘

http://yun.baidu.com/pcloud/album/info?query\_uk=3724757956&album\_id=3094796070610213829

一:web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<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/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>elve</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath:app-context.xml
    </param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>demo.root</param-value>
  </context-param>
  
  
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <listener>
    <listener-class>
        com.xs.demo.listener.SessionListener
    </listener-class>
  </listener>
  <servlet>
    <servlet-name>app</servlet-name>
       <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:app-servlet.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <error-page>
    <error-code>500</error-code>
    <location>/system/500.jsp</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/system/404.jsp</location>
  </error-page>
  <error-page>
    <error-code>403</error-code>
    <location>/system/403.jsp</location>
  </error-page>
</web-app>

1.UserController代码

package com.xs.demo.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xs.demo.entity.Userinfo;
import com.xs.demo.service.UserService;
import com.xs.demo.util.StringUtil;
/**
 * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
 * @author 宗潇帅
 * 类名称:UserController 
 * @date 2014-11-15 下午4:05:32 
 * 备注:
 */
@Controller
@RequestMapping(value="/user")
public class UserController {
    
    UserService userService;
    
    private static Log log = LogFactory.getLog(UserController.class);
    
    /**
     * index --list
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/index")
    public String index(HttpServletRequest request,
            HttpServletResponse response)throws Exception{
        return "/views/user/index";
    }
    /**
     * list method
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        int start = ServletRequestUtils.getIntParameter(request, "page", 1)-1;
        int size = ServletRequestUtils.getIntParameter(request, "rows", 0);
        String name = ServletRequestUtils.getStringParameter(request, "name","");
        String order = StringUtil.getOrderString(request);    //取得排序参数
        
        String result = null;
        try{
            result = userService.list(name,start, size, order);
        }catch (Exception e) {
            if(log.isErrorEnabled()){
                log.error("查询列表失败", e);
            }
            result = "";
        }
        String sortName = ServletRequestUtils.getStringParameter(request, "sort", "");
        String sortOrder = ServletRequestUtils.getStringParameter(request, "order", "");
        Map<String, Object> searchMap = new HashMap<String,Object>();
        searchMap.put("pageNumber", start+1);
        searchMap.put("rows", size);
        searchMap.put("sortName", sortName);
        searchMap.put("sortOrder", sortOrder);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String s = gson.toJson(searchMap);
        s = URLEncoder.encode(s,"UTF-8"); 
        
        StringUtil.writeToWeb(result, "html", response);
        return null;
    }
    /**
     * gotoAdd --page
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/gotoAdd")
    public String gotoAdd(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        return "views/user/add";
    }
    /**
     * add --method
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/add")
    public String add(HttpServletRequest request,
            HttpServletResponse response)throws Exception {
        String result = null;
        Userinfo userinfo = (Userinfo)StringUtil.requestToObject(request, Userinfo.class);
        Userinfo dbUserinfo =  userService.getUserByName(userinfo.getName());
        if(dbUserinfo!=null){
            result = "{\"success\":false,\"msg\":\"名称已存在!\"}";
            StringUtil.writeToWeb(result, "html", response);
            return null;
        }
        try{
            if(userinfo.getName().trim().length()<0){
                result = "{\"success\":false,\"msg\":\"名称不能为空!\"}";
                StringUtil.writeToWeb(result, "html", response);
                return null;
            }else if(null == userinfo.getAge()){
                result = "{\"success\":false,\"msg\":\"年龄参数有误!\"}";
                StringUtil.writeToWeb(result, "html", response);
                return null;
            }else{
                result = userService.save(userinfo);
            }
        }catch(Exception e){
            if(log.isErrorEnabled()){
                log.error("新增失败", e);
            }
            result = "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}";
        }
        StringUtil.writeToWeb(result, "html", response);
        return null;
    }
    /**
     * gotoModify --page
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="/gotoModify")
    public String gotoModify(HttpServletRequest request,
            HttpServletResponse response)throws Exception {
        Integer id = ServletRequestUtils.getIntParameter(request,"id");
        Userinfo userinfo = userService.get(Userinfo.class,id);
        request.setAttribute("userinfo", userinfo);
            return "views/user/modify";
    }
    /**
     * modify --method
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/modify")
    public String modify(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Integer id = ServletRequestUtils.getIntParameter(request, "id");
        Userinfo dbUserinfo = userService.get(Userinfo.class, id);
        Userinfo userinfo = (Userinfo) StringUtil.requestToObject(request, Userinfo.class);
        String result;
        if(!dbUserinfo.getName().equals(userinfo.getName())){
            Userinfo hasUserinfo = userService.getUserByName(userinfo.getName());
            if(hasUserinfo!=null){
                result = "{\"success\":false,\"msg\":\"角色名称已存在!\"}";
                StringUtil.writeToWeb(result, "html", response);
                return null;
            }
        }
        try{
            result = userService.update(request,userinfo, id);
        }catch (Exception e ){
            if(log.isErrorEnabled()){
                log.error("修改失败", e);
            }
            result = "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}";
        }
        StringUtil.writeToWeb(result, "html", response);
        return null;
    }
    /**
     * delete --method
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    public String delete(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        Integer id = ServletRequestUtils.getIntParameter(request, "id");
        
        try{
            if(null != id){
                userService.delete(id);
            }
            String result = "{\"success\":true,\"msg\":\"删除成功\"}";
            StringUtil.writeToWeb(result, "html", response);
            return null;
        } catch (Exception e) {
            if(log.isErrorEnabled()){
                log.error("删除失败", e);
            }
            String result = "{\"success\":false,\"msg\":\"删除失败,请稍候再试!\"}";
            StringUtil.writeToWeb(result, "html", response);
            return null;
        }
    }
    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    
}

2.UserService代码

package com.xs.demo.service;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;





import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xs.demo.dao.UserDao;
import com.xs.demo.entity.Userinfo;
import com.xs.demo.util.StringUtil;
/**
 *  SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
 * @author 宗潇帅
 * 类名称:UserService 
 * @date 2014-11-15 下午4:14:37 
 * 备注:
 */
public class UserService extends BaseService {
    UserDao userDao;
    /**
     * list
     * @param name
     * @param start
     * @param size
     * @param order
     * @return
     */
    public String list(String name,int start, int size, String order){
        List<Map<String,Object>> list =userDao.list(name,start, size, order); 
        int count = count(name,start, size, order);
        
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", list);
        
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String s = gson.toJson(map);
        return s;
    }
    /**
     * save
     * @param userinfo
     * @return
     */
    public String save(Userinfo userinfo) {
        String result = null;
        Date date = new Date();
        userinfo.setBirthday(date);
        userinfo.setPassword("888888");
        super.save(userinfo);
        result = "{\"success\":true,\"msg\":\"新增角色成功\"}";
        return result ;
    }
    /**
     * count
     * @param name
     * @param start
     * @param size
     * @param order
     * @return
     */
    public int count(String name,int start, int size, String order){
        return userDao.count(name,start, size, order);
    }
    /**
     * getuserbyname
     * @param name
     * @return
     */
    public Userinfo getUserByName(String name) {
        return userDao.getUserByName(name);
    }
    /**
     * update
     * @param request
     * @param userinfo
     * @param id
     * @return
     */
    public String update(HttpServletRequest request, Userinfo userinfo,
            Integer id) {
        Userinfo userinfoOld = super.get(Userinfo.class, id);
        if(null != userinfo){
            StringUtil.requestToObject(request, userinfoOld);
        }
        super.update(userinfoOld);
        String result = "{\"success\":true,\"msg\":\"更新成功!\"}";
        return result;
    }
    /**
     * delete
     * @param id
     */
    public void delete(Serializable id){
        userDao.delete(Userinfo.class,id);
    }
    
    
    
    /*------------------*/
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }



    
}

3.UserDao

package com.xs.demo.dao;

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


import com.xs.demo.entity.Userinfo;
/**
 * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD
 * @author 宗潇帅
 * 类名称:UserDao 
 * @date 2014-11-15 下午4:34:51 
 * 备注:
 */
public class UserDao extends BaseDao{

    public List<Map<String, Object>> list(String name,int start, int size,
            String order) {
        List<Object> param = new ArrayList<Object>();
        String sql = "select u.* from userinfo u where 1=1 ";
        if(null != name && name.trim().length() > 0){
            sql += " and u.name like ? ";
            param.add("%"+name+"%");
        }
        if(null == order || order.length() == 0){
            order = " birthday asc";
        }
        return super.listByNative(sql, param.toArray(), start, size, order);
    }

    public int count(String name,int start, int size,
            String order) {
        List<Object> param = new ArrayList<Object>();
        String sql = "select count(*) from userinfo u where 1=1 ";
        if(null != name && name.trim().length() > 0){
            sql += " and u.name like ? ";
            param.add("%"+name+"%");
        }
        return super.countByNative(sql, param.toArray());
    }

    @SuppressWarnings("unchecked")
    public Userinfo getUserByName(String name) {
        String hql="select u from Userinfo u where u.name=? ";
        List<Userinfo> list=super.list(hql, new Object[]{name});
        if(list!=null&&list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

}

4.add.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/common/meta.jsp"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</title>
<script type="text/javascript">
    function doCancel(){
        document.location.href="${ctx }/user/index";
    }
    
    $(function(){
        $('#form1').form({
            onSubmit: function(){
                var v = $(this).form('validate');
                    if(v){
                        $("#doSubmit").unbind('click');
                    }
                    return v;
            },
            success:function(data){
                data = eval('(' + data + ')');
                if(data.success == true){
                    document.location.href="${ctx }/user/index";
                }else {
                        $("#doSubmit").bind("click",function(){
                       $('#form1').submit();
                    });
                    alert(data.msg);
                }
            }
        });
        $("#doSubmit").click(function() {
            $('#form1').submit();
            return false;
        });
    });
</script>
</head>
<body>
<div class="tables_title">Add New UserInfo</div>
<form action="${ctx }/user/add " id="form1" method="post">
    <div class="dengji_table">
        <div class="basic_table">
            <div class="clospan">
                <p class="basic_name">名称</p>
                <p>
                <input name="name"  id="name" type="text" class="easyui-validatebox"  data-options="required:true" placeholder="输入中文"/>
                </p>
             </div>
         </div>
         <div class="basic_table">
            <div class="clospan">
                <p class="basic_name" style=" border-right:none;">年龄</p>
                <p>
                <input name="age"  id="age" type="number"  min="18" max="99" class="easyui-validatebox"  data-options="required:true" placeholder="年龄不得小于18"/>
                </p>
        </div>
        </div>
        <div class="basic_table">
          <div class="clospan">
                <p class="basic_name" style=" border-right:none;">地址</p>
                <p>
                <input name="address"  id="address" type="text"  class="easyui-validatebox"  data-options="required:true" placeholder="市区名"/>
                </p>
        </div>
        </div>
             <div class="clospan_func">
                <div class="btns">
                    <a href="javascript:void(0);" id="doSubmit" class="blank_btn">保存</a>
                    <a href="javascript:void(0);" onclick="doCancel();" class="blank_btn">返回</a>
                </div>
            </div>
        </div>
      </form>
</body>
</html>

5.index.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/common/meta.jsp"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</title>
<script type="text/javascript">
    var searchString;

    function resizeDg(){
        $('#dg').datagrid("resize", { width: $(window).width() * 0.4});
    }
    
    function getCookie(c_name){
         if (document.cookie.length>0){
          c_start=document.cookie.indexOf(c_name + "=");
          if (c_start!=-1){ 
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) {
                c_end=document.cookie.length;
            }
            return document.cookie.substring(c_start,c_end);
           } 
          }
        return "";
    }
    
    var pageSize = 20;
    var pageNumber = 1;
    var sortName = '';
    var sortOrder = '';
    function initDate(){
        var s = getCookie("role");
        s = decodeURIComponent(s);
        if(s != null && s != ""){
            searchMap = eval('(' + s + ')');
            pageSize = searchMap.rows;
            if(pageSize == null || pageSize == ""){
                pageSize = 20;
            }
            pageNumber = searchMap.pageNumber;
            sortName = searchMap.sortName;
            sortOrder = searchMap.sortOrder;
            $("#name").val(searchMap.name );
        }
    }
    
    $(function(){
         $("#doSearch").click(function(){
            doSearch();
        });
        initDate();
        var name=$("#name").val();
        $('#dg').datagrid({
            url:"${ctx }/user/list",
            pagination:true,
            singleSelect:true,
            pageSize:pageSize,
            pageNumber:pageNumber,
            sortOrder:sortOrder,
            sortName:sortName,
            queryParams:{  
                name:name,
            },
            width:800,
               columns:[[
                   {field:'name',title:'名称', width:100, align:"center",sortable:true},
                   {field:'age',title:'年龄', width:50, align:"center",sortable:true},
                   {field:'address',title:'地址', width:50, align:"center",sortable:true},
                   {field:'operation',title:'操作', width:340, align:"center", sortable:false,
                       formatter:function(value,row,index){
                           var s ="";
                        s+="<a href=\"javascript:void(0)\"><span onclick=\"javaScript:gotoModify('"+row.id+"');\">修改</span></a>";
                           s += "|";
                        s+="<a href=\"javascript:void(0)\"><span onclick=\"javaScript:gotoDel('"+row.id+"');\">删除</span>&nbsp;&nbsp;</a>";
                        return s;
                       }
                   }
               ]]
        });
         var p = $('#dg').datagrid('getPager');    
         $(p).pagination({    
              pageList: [10,20,50,100]
          });  
        
        $("#doSearch").click(function(){
            doSearch();
        });
    });
    
    
    function gotoAdd(){
        var url = '${ctx }/user/gotoAdd';
        window.location.href=url;
    }
    function gotoModify(id){
        var url = '${ctx}/user/gotoModify?id='+id;
        window.location.href=url;
    }
    function gotoDel(id){
        if(!confirm('确定删除所选记录?')){
            return;
        }
        var url = '${ctx}/user/delete?id='+id;
        $.ajax({
            type : 'post',
            url : url,
            dataType: "json",
                success:function(data){
                    if(data.success == true){
                        doSearch();
                    }else{
                        alert(data.msg);
                    }
                }
            });
    }
        
    function doSearch(){
        var name=$("#name").val();
        /* var schoolId=$("#schoolId").val(); */
        $("#dg").datagrid('load',{  
            name:name
        }); //重新载入 
    }
        
</script>
</head>
<body onload="resizeDg();" onresize="resizeDg();" >
<div class="neirong">
<div class="add-content" style="margin-top:0">
    <div class="xinxi2">
           <div class="search_box">
           <p>名称: <input name="name" id="name" type="text" /></p>
           <a href="javascript:void(0);" id="doSearch" class="blank_btn">查询</a></div>
           <div class="btn_div">
           <a href="javascript:void(0);" onclick="gotoAdd();" id="xtsz_rygl_jsgl_add" class="blank_btn">新增</a>
           </div>
       </div>
    <div class="contant_list" >
        <!-- c_top start-->
        <table  width="100%">
            <tr>
                <td>
                    <table id="dg"></table>
                </td>
            </tr>
        </table>
    </div>
  </div>
</div>
</body>
</html>

6.modfiy.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/common/meta.jsp"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>修改用户信息</title>
<script type="text/javascript">

    function doCancel(){
        document.location.href="${ctx }/user/index";
    }
    
    $(function(){
        $('#form1').form({
            onSubmit: function(){
                var v = $(this).form('validate');
                    if(v){
                        $("#doSubmit").unbind('click');
                    }
                    return v;
            },
            success:function(data){
                data = eval('(' + data + ')');
                if(data.success == true){
                    document.location.href="${ctx }/user/index";
                }else {
                        $("#doSubmit").bind("click",function(){
                       $('#form1').submit();
                    });
                    alert(data.msg);
                }
            }
        });
        $("#doSubmit").click(function() {
            $('#form1').submit();
            return false;
        });

    });
</script>
</head>
<body>
<div class="tables_title">修改用户</div>
<form action="${ctx }/user/modify" id="form1" method="post">
 <input type="hidden" name="id" value="${userinfo.id }"></input>
<div class="dengji_table">
        <div class="basic_table">
            <div class="clospan">
                <p class="basic_name">名称</p>
                <p>
                <input name="name"  id="name" type="text" class="easyui-validatebox"  data-options="required:true" value="${userinfo.name}"/>
                </p>
             </div>
         </div>
         <div class="basic_table">
            <div class="clospan">
                <p class="basic_name" style=" border-right:none;">年龄</p>
                <p>
                <input name="age"  id="age" type="number"  min="18" max="99" class="easyui-validatebox"  data-options="required:true" value="${userinfo.age}"/>
                </p>
        </div>
        </div>
        <div class="basic_table">
          <div class="clospan">
                <p class="basic_name" style=" border-right:none;">地址</p>
                <p>
                <input name="address"  id="address" type="text"  class="easyui-validatebox"  data-options="required:true" value="${userinfo.address}"/>
                </p>
        </div>
        </div>
             <div class="clospan_func">
                <div class="btns">
                    <a href="javascript:void(0);" id="doSubmit" class="blank_btn">保存</a>
                    <a href="javascript:void(0);" onclick="doCancel();" class="blank_btn">返回</a>
                </div>
            </div>
        </div>
      </form>
</body>
</html>

7.app-aop.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:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-autowire="byName">
    
    
    <aop:config>
        <aop:pointcut id="testPointcut" expression="execution(* cn.com.elve.live..service..*.*(..))" />
    </aop:config>
    <!-- 普通的AOP,如果想得到被代理的方法参数,那么就必须在配置里提前写好,这样有非常大的局限性 -->
    <aop:config>
        <aop:aspect ref="testSchemaAop">
            <aop:before method="before" pointcut-ref="testPointcut"/>
            <aop:after-returning method="afterReturning" pointcut-ref="testPointcut" returning="object"/>
            <aop:after-throwing method="afterThrowing" pointcut-ref="testPointcut" throwing="object"/>
            <aop:after method="after" pointcut-ref="testPointcut"/>
        </aop:aspect>
    </aop:config>
    
    <!-- 基于advisor的代理,代理类需要实现spring提供的接口,然后就可以用到强大的功能了。 -->
    <aop:config>
        <aop:advisor pointcut-ref="testPointcut" advice-ref="afterReturn" />
    </aop:config>
    
    
    
    <!-- 需要由spring注入的bean定义 -->
    <bean id="afterReturn" class="com.xs.demo.aop.AfterReturn"/>
    <bean id="afterThrow" class="com.xs.demo.aop.AfterThrow"/>
    <bean id="before" class="com.xs.demo.aop.Before"/>
    <bean id="testSchemaAop" class="com.xs.demo.aop.TestSchemaAop"/>
    
    
    
</beans>

8.app-context.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:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-autowire="byName">
    <!-- 使用annotation 自动注册bean -->
    <context:annotation-config/>
    <context:component-scan base-package="com.xs.demo">
        <context:include-filter type="regex" expression=".*Service"/>
        <context:include-filter type="regex" expression=".*Dao"/>
        <context:include-filter type="regex" expression=".*Job"/>
    </context:component-scan>
    
    
    <import resource="classpath:/app-db.xml"/>
    
    <!-- 配置文件读取 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/jdbc.properties</value>
                <value>classpath:/hibernate.properties</value>
                <value>classpath:/log4j.properties</value>
            </list>
        </property>
    </bean>
    
    
    
    <!-- 开启AOP监听 只对当前配置文件有效 -->
    <aop:aspectj-autoproxy expose-proxy="true"/>
    
    <!-- 开启注解事务 只对当前配置文件有效 -->
      <tx:annotation-driven transaction-manager="txManager"/>

    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="upload*" propagation="REQUIRED" />
            <tx:method name="merge*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="move*" propagation="REQUIRED" />
            <tx:method name="change*" propagation="REQUIRED" />
            <tx:method name="put*" propagation="REQUIRED" />
            <tx:method name="use*" propagation="REQUIRED"/>
            <tx:method name="log*" propagation="REQUIRED"/>
            <tx:method name="sh*" propagation="REQUIRED"/>
            <tx:method name="bh*" propagation="REQUIRED"/>
            <tx:method name="sf*" propagation="REQUIRED"/>
            <tx:method name="bj*" propagation="REQUIRED"/>
            <tx:method name="tf*" propagation="REQUIRED"/>
            <tx:method name="mobileLogin" propagation="REQUIRED"/>
            <tx:method name="register*" propagation="REQUIRED"/>
            <tx:method name="goto*" propagation="REQUIRED"/>
            <tx:method name="active*" propagation="REQUIRED"/>
            <tx:method name="send*" propagation="REQUIRED"/>
            <tx:method name="handel*" propagation="REQUIRED"/>
            <tx:method name="attendance*" propagation="REQUIRED"/>
            <tx:method name="batch" propagation="REQUIRED"/>
            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <aop:config expose-proxy="true">
        <!-- 只对业务逻辑层实施事务 -->
        <aop:pointcut id="txPointcut" expression="execution(* com.xs.demo..service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    
    <!-- 自动扫描测试用service -->
<!--     <context:component-scan base-package="test.service"></context:component-scan> -->
    
    
    <!--    javaMailSender 
    <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl" >
        <property name="host" value="smtp.qq.com"/>
        <property name="port" value="465"/>
        <property name="username" value="elve@elve.cn"/>
        <property name="password" value="654123.huo"/>
        <property name="javaMailProperties">
            <props> 
                <prop key="mail.smtp.auth">true</prop> 
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
            </props> 
        </property> 
    </bean> -->
    
    
    
</beans>

9.app-servlet.xml

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


<!-- 配置urlMapping -->
<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:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd"
    default-autowire="byName">
    <!-- 启用基于注解的处理器映射,添加拦截器,类级别的处理器映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <list>
                <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
            </list>
        </property>
    </bean>
    
    <!-- 设置自动扫描的controller类的路径,可以写多个 -->
    <!-- 例<context:component-scan base-package="cn.com.elve.live.controller,cn.com.elve.live.xxx"/> -->
    <context:component-scan base-package="com.xs.demo.controller"/>
    <!-- 
    配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射,
    有人说该bean要放在context:component-scan前面,要不然不起作用,但我试的放后面也可以啊。
    -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
    </bean>
    
    <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/swf/**" location="/swf/"/>
    <mvc:resources mapping="/file/**" location="/file/"/>
    <mvc:resources mapping="/FusionCharts/**" location="/FusionCharts/"/>
    
    <!-- viewResolver 视图解析器,将视图名(ModelAndView中的view)解析成URL-->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp" />
        <property name="prefix" value="/WEB-INF/"/>
        <property name="order" value="20"></property>
        <property name="viewClass"
            value="org.springframework.web.servlet.view.InternalResourceView" />
    </bean>
    
     <!-- 针对freemarker的视图配置 -->
    <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="suffix" value=".ftl" />
        <property name="order" value="5"></property>    <!--resolver排序,本resolver会早于viewResolver-->
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
        <property name="contentType" value="text/html;charset=UTF-8"></property>
        <property name="requestContextAttribute" value="request" />
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
    </bean>
    
    <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>
    
    
    <!--multipartResolver 支持分段文件上传 使用时form需要加上enctype="multipart/form-data"属性,且form的method设置为POST-->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500400000" />
        <property name="maxInMemorySize" value="4096" />
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    
    <!-- 国际化配置 -->  
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" >
        <property name="cookieName" value="clientlanguage"/>
        <property name="cookieMaxAge" value="94608000"/>
    </bean>  
    
</beans>

 使用的SpringMVC HandlerInterceptor验证是否登陆。

package com.xs.demo.inteceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class Test implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("最后执行");
    }
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("第二步执行");
    }
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        System.out.println("主要的业务逻辑");
        return false;
    }

}

代码很简单。判断session是否为空。且判断用户请求的url

public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        System.out.println("第一步");
        String path = request.getServletPath();
        if(path.startsWith("/user/")){
            Login userinfo = (Login) request.getSession().getAttribute(Constants.LOGIN_INFO);
            if(null == userinfo && !path.startsWith("/user/gotoAdd/")){
                response.sendRedirect(request.getContextPath()+"/system/login.jsp");
                return false;
            }else{
                System.out.println("else");
                return true;
            }
        }
        return true;
    }

个人微博 http://weibo.com/zxshuai319

个人博客 http://my.oschina.net/xshuai/blog

公开QQ  783021975 不说具体问题。一律不回复

个人联盟 http://www.bengbeng.com/?sid=687095

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
Highcharts AJAX JSON JQuery 实现动态数据交互显示图表 柱形图
!(http://static.oschina.net/uploads/space/2015/0114/113658_PHf4_1444646.png)!(https://static.oschina.net/uploads/space/2017/0420/171449_piOt_1444646.jpg)个人小程序,可以微信扫一扫看看。谢谢支持
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k