专栏首页XAISpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一)

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

最新项目下载地址

访问地址

1.基于easyui的 增 删 改 查

2.基于poi的导出excel

3.基于 SpringMVC HandlerInterceptor验证

项目结构图

源代码和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;
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • SpringMVC+MongoDB+Maven整合(微信回调Oauth授权)

    个人小程序。里面是基于百度大脑 腾讯优图做的人脸检测。是关于人工智能的哦。 2017年第一篇自己在工作中的总结文档。土豪可以打赏哦。 https://git.o...

    小帅丶
  • 微信企业号登录授权Java实现获取员工userid根据userid换openid

    微信企业号登录授权Java实现获取员工userid根据userid换openid 2016年1月8日 为了方便测试 。debug 建议大家搞个花生壳或者其他的可...

    小帅丶
  • Java分布式神经网络库Deeplearning4j之上手实践手写数字图像识别与模型训练

    环境的搭建可以参考另一篇文章。 Java分布式神经网络库Deeplearning4j 环境搭建和运行一个例子 代码所在包截图示意 ? 第一步运行MnistIm...

    小帅丶
  • webservices系列(六)——spring整合Axis2

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 ...

    逝兮诚
  • MYSQL回顾(多表查询相关)

    简单的数据我们可以直接从一个表中获取,但在真实的项目中查询符合条件的数据通常需要牵扯到多张表,这就不得不使用多表查询。多表查询分为多表连接查询、符合条件链接查询...

    VV木公子
  • Spring+SpringMVC+Hibernate简单整合(转)

    SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,下面同样做一个简单的应用实例,介绍SpringMVC的...

    yaohong
  • Hibernate多表关系配置

    映射文件中普通字段段的配置不用写上外键,在一的一方配置文件写上set标签name属性为关联属性名,里面还有key标签有column属性关系中的外键即另一个表的外...

    木瓜煲鸡脚
  • Spring Boot Web应用程序中注册 Servlet 的方法实例

    本文实例工程源代码:https://github.com/KotlinSpringBoot/demo1_add_servlet

    一个会写诗的程序员
  • django+pymysql搭建一个管理系统(一)

    小小咸鱼YwY
  • RabbitMq的消息队列类型direct、fanout、topic、headers(headers抛弃)

    1 服务端 server 将 消息 msg_txt 投递 到 交换器 exchange_name 路由键为 routing_key_name ,当 有队列 qu...

    93年的老男孩

扫码关注云+社区

领取腾讯云代金券