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

个人小程序,可以微信扫一扫看看。谢谢支持

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

访问地址

1.基于easyui的 增 删 改 查

2.基于poi的导出excel

3.基于 SpringMVC HandlerInterceptor验证

项目结构图

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

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

一:web.xml代码

1<?xml version="1.0" encoding="UTF-8"?> 2<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"> 3  <display-name>elve</display-name> 4  <context-param> 5    <param-name>contextConfigLocation</param-name> 6    <param-value> 7            classpath:app-context.xml 8    </param-value> 9  </context-param> 10  <context-param> 11    <param-name>webAppRootKey</param-name> 12    <param-value>demo.root</param-value> 13  </context-param> 14   15   16  <filter> 17    <filter-name>encodingFilter</filter-name> 18    <filter-class> 19            org.springframework.web.filter.CharacterEncodingFilter 20        </filter-class> 21    <init-param> 22      <param-name>encoding</param-name> 23      <param-value>UTF-8</param-value> 24    </init-param> 25  </filter> 26  <filter-mapping> 27    <filter-name>encodingFilter</filter-name> 28    <url-pattern>/*</url-pattern> 29  </filter-mapping> 30  <listener> 31    <listener-class> 32        org.springframework.web.context.ContextLoaderListener 33    </listener-class> 34  </listener> 35  <listener> 36    <listener-class> 37        com.xs.demo.listener.SessionListener 38    </listener-class> 39  </listener> 40  <servlet> 41    <servlet-name>app</servlet-name> 42       <servlet-class> 43        org.springframework.web.servlet.DispatcherServlet 44    </servlet-class> 45    <init-param> 46      <param-name>contextConfigLocation</param-name> 47      <param-value>classpath:app-servlet.xml</param-value> 48    </init-param> 49    <load-on-startup>2</load-on-startup> 50  </servlet> 51  <servlet-mapping> 52    <servlet-name>app</servlet-name> 53    <url-pattern>/</url-pattern> 54  </servlet-mapping> 55  <session-config> 56    <session-timeout>60</session-timeout> 57  </session-config> 58  <welcome-file-list> 59    <welcome-file>index.jsp</welcome-file> 60    <welcome-file>index.html</welcome-file> 61  </welcome-file-list> 62  <error-page> 63    <error-code>500</error-code> 64    <location>/system/500.jsp</location> 65  </error-page> 66  <error-page> 67    <error-code>404</error-code> 68    <location>/system/404.jsp</location> 69  </error-page> 70  <error-page> 71    <error-code>403</error-code> 72    <location>/system/403.jsp</location> 73  </error-page> 74</web-app>

1.UserController代码

1package com.xs.demo.controller; 2 3import java.net.URLEncoder; 4import java.util.HashMap; 5import java.util.Map; 6 7import javax.servlet.http.HttpServletRequest; 8import javax.servlet.http.HttpServletResponse; 9 10import org.apache.commons.logging.Log; 11import org.apache.commons.logging.LogFactory; 12import org.springframework.stereotype.Controller; 13import org.springframework.web.bind.ServletRequestUtils; 14import org.springframework.web.bind.annotation.RequestMapping; 15 16import com.google.gson.Gson; 17import com.google.gson.GsonBuilder; 18import com.xs.demo.entity.Userinfo; 19import com.xs.demo.service.UserService; 20import com.xs.demo.util.StringUtil; 21/** 22 * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD 23 * @author 宗潇帅 24 * 类名称:UserController  25 * @date 2014-11-15 下午4:05:32  26 * 备注: 27 */ 28@Controller 29@RequestMapping(value="/user") 30public class UserController { 31     32    UserService userService; 33     34    private static Log log = LogFactory.getLog(UserController.class); 35     36    /** 37     * index --list 38     * @param request 39     * @param response 40     * @return 41     * @throws Exception 42     */ 43    @RequestMapping(value="/index") 44    public String index(HttpServletRequest request, 45            HttpServletResponse response)throws Exception{ 46        return "/views/user/index"; 47    } 48    /** 49     * list method 50     * @param request 51     * @param response 52     * @return 53     * @throws Exception 54     */ 55    @RequestMapping(value = "/list") 56    public String list(HttpServletRequest request, 57            HttpServletResponse response) throws Exception{ 58        int start = ServletRequestUtils.getIntParameter(request, "page", 1)-1; 59        int size = ServletRequestUtils.getIntParameter(request, "rows", 0); 60        String name = ServletRequestUtils.getStringParameter(request, "name",""); 61        String order = StringUtil.getOrderString(request);    //取得排序参数 62         63        String result = null; 64        try{ 65            result = userService.list(name,start, size, order); 66        }catch (Exception e) { 67            if(log.isErrorEnabled()){ 68                log.error("查询列表失败", e); 69            } 70            result = ""; 71        } 72        String sortName = ServletRequestUtils.getStringParameter(request, "sort", ""); 73        String sortOrder = ServletRequestUtils.getStringParameter(request, "order", ""); 74        Map<String, Object> searchMap = new HashMap<String,Object>(); 75        searchMap.put("pageNumber", start+1); 76        searchMap.put("rows", size); 77        searchMap.put("sortName", sortName); 78        searchMap.put("sortOrder", sortOrder); 79        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); 80        String s = gson.toJson(searchMap); 81        s = URLEncoder.encode(s,"UTF-8");  82         83        StringUtil.writeToWeb(result, "html", response); 84        return null; 85    } 86    /** 87     * gotoAdd --page 88     * @param request 89     * @param response 90     * @return 91     * @throws Exception 92     */ 93    @RequestMapping(value="/gotoAdd") 94    public String gotoAdd(HttpServletRequest request, 95            HttpServletResponse response) throws Exception{ 96        return "views/user/add"; 97    } 98    /** 99     * add --method 100     * @param request 101     * @param response 102     * @return 103     * @throws Exception 104     */ 105    @RequestMapping(value="/add") 106    public String add(HttpServletRequest request, 107            HttpServletResponse response)throws Exception { 108        String result = null; 109        Userinfo userinfo = (Userinfo)StringUtil.requestToObject(request, Userinfo.class); 110        Userinfo dbUserinfo =  userService.getUserByName(userinfo.getName()); 111        if(dbUserinfo!=null){ 112            result = "{\"success\":false,\"msg\":\"名称已存在!\"}"; 113            StringUtil.writeToWeb(result, "html", response); 114            return null; 115        } 116        try{ 117            if(userinfo.getName().trim().length()<0){ 118                result = "{\"success\":false,\"msg\":\"名称不能为空!\"}"; 119                StringUtil.writeToWeb(result, "html", response); 120                return null; 121            }else if(null == userinfo.getAge()){ 122                result = "{\"success\":false,\"msg\":\"年龄参数有误!\"}"; 123                StringUtil.writeToWeb(result, "html", response); 124                return null; 125            }else{ 126                result = userService.save(userinfo); 127            } 128        }catch(Exception e){ 129            if(log.isErrorEnabled()){ 130                log.error("新增失败", e); 131            } 132            result = "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}"; 133        } 134        StringUtil.writeToWeb(result, "html", response); 135        return null; 136    } 137    /** 138     * gotoModify --page 139     * @param request 140     * @param response 141     * @return 142     */ 143    @RequestMapping(value="/gotoModify") 144    public String gotoModify(HttpServletRequest request, 145            HttpServletResponse response)throws Exception { 146        Integer id = ServletRequestUtils.getIntParameter(request,"id"); 147        Userinfo userinfo = userService.get(Userinfo.class,id); 148        request.setAttribute("userinfo", userinfo); 149            return "views/user/modify"; 150    } 151    /** 152     * modify --method 153     * @param request 154     * @param response 155     * @return 156     * @throws Exception 157     */ 158    @RequestMapping(value="/modify") 159    public String modify(HttpServletRequest request, 160            HttpServletResponse response) throws Exception { 161        Integer id = ServletRequestUtils.getIntParameter(request, "id"); 162        Userinfo dbUserinfo = userService.get(Userinfo.class, id); 163        Userinfo userinfo = (Userinfo) StringUtil.requestToObject(request, Userinfo.class); 164        String result; 165        if(!dbUserinfo.getName().equals(userinfo.getName())){ 166            Userinfo hasUserinfo = userService.getUserByName(userinfo.getName()); 167            if(hasUserinfo!=null){ 168                result = "{\"success\":false,\"msg\":\"角色名称已存在!\"}"; 169                StringUtil.writeToWeb(result, "html", response); 170                return null; 171            } 172        } 173        try{ 174            result = userService.update(request,userinfo, id); 175        }catch (Exception e ){ 176            if(log.isErrorEnabled()){ 177                log.error("修改失败", e); 178            } 179            result = "{\"success\":false,\"msg\":\"系统错误,请稍候再试!\"}"; 180        } 181        StringUtil.writeToWeb(result, "html", response); 182        return null; 183    } 184    /** 185     * delete --method 186     * @param request 187     * @param response 188     * @return 189     * @throws Exception 190     */ 191    @RequestMapping(value = "/delete") 192    public String delete(HttpServletRequest request, 193            HttpServletResponse response) throws Exception{ 194        Integer id = ServletRequestUtils.getIntParameter(request, "id"); 195         196        try{ 197            if(null != id){ 198                userService.delete(id); 199            } 200            String result = "{\"success\":true,\"msg\":\"删除成功\"}"; 201            StringUtil.writeToWeb(result, "html", response); 202            return null; 203        } catch (Exception e) { 204            if(log.isErrorEnabled()){ 205                log.error("删除失败", e); 206            } 207            String result = "{\"success\":false,\"msg\":\"删除失败,请稍候再试!\"}"; 208            StringUtil.writeToWeb(result, "html", response); 209            return null; 210        } 211    } 212    public UserService getUserService() { 213        return userService; 214    } 215 216    public void setUserService(UserService userService) { 217        this.userService = userService; 218    } 219     220}

2.UserService代码

1package com.xs.demo.service; 2 3import java.io.Serializable; 4import java.util.Date; 5import java.util.HashMap; 6import java.util.List; 7import java.util.Map; 8 9import javax.servlet.http.HttpServletRequest; 10 11 12 13 14 15import com.google.gson.Gson; 16import com.google.gson.GsonBuilder; 17import com.xs.demo.dao.UserDao; 18import com.xs.demo.entity.Userinfo; 19import com.xs.demo.util.StringUtil; 20/** 21 *  SpringMVC+Hibernate +MySql+ EasyUI ---CRUD 22 * @author 宗潇帅 23 * 类名称:UserService  24 * @date 2014-11-15 下午4:14:37  25 * 备注: 26 */ 27public class UserService extends BaseService { 28    UserDao userDao; 29    /** 30     * list 31     * @param name 32     * @param start 33     * @param size 34     * @param order 35     * @return 36     */ 37    public String list(String name,int start, int size, String order){ 38        List<Map<String,Object>> list =userDao.list(name,start, size, order);  39        int count = count(name,start, size, order); 40         41        Map<String,Object> map = new HashMap<String, Object>(); 42        map.put("total", count); 43        map.put("rows", list); 44         45        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 46        String s = gson.toJson(map); 47        return s; 48    } 49    /** 50     * save 51     * @param userinfo 52     * @return 53     */ 54    public String save(Userinfo userinfo) { 55        String result = null; 56        Date date = new Date(); 57        userinfo.setBirthday(date); 58        userinfo.setPassword("888888"); 59        super.save(userinfo); 60        result = "{\"success\":true,\"msg\":\"新增角色成功\"}"; 61        return result ; 62    } 63    /** 64     * count 65     * @param name 66     * @param start 67     * @param size 68     * @param order 69     * @return 70     */ 71    public int count(String name,int start, int size, String order){ 72        return userDao.count(name,start, size, order); 73    } 74    /** 75     * getuserbyname 76     * @param name 77     * @return 78     */ 79    public Userinfo getUserByName(String name) { 80        return userDao.getUserByName(name); 81    } 82    /** 83     * update 84     * @param request 85     * @param userinfo 86     * @param id 87     * @return 88     */ 89    public String update(HttpServletRequest request, Userinfo userinfo, 90            Integer id) { 91        Userinfo userinfoOld = super.get(Userinfo.class, id); 92        if(null != userinfo){ 93            StringUtil.requestToObject(request, userinfoOld); 94        } 95        super.update(userinfoOld); 96        String result = "{\"success\":true,\"msg\":\"更新成功!\"}"; 97        return result; 98    } 99    /** 100     * delete 101     * @param id 102     */ 103    public void delete(Serializable id){ 104        userDao.delete(Userinfo.class,id); 105    } 106     107     108     109    /*------------------*/ 110    public UserDao getUserDao() { 111        return userDao; 112    } 113    public void setUserDao(UserDao userDao) { 114        this.userDao = userDao; 115    } 116 117 118 119     120}

3.UserDao

1package com.xs.demo.dao; 2 3import java.util.ArrayList; 4import java.util.List; 5import java.util.Map; 6 7 8import com.xs.demo.entity.Userinfo; 9/** 10 * SpringMVC+Hibernate +MySql+ EasyUI ---CRUD 11 * @author 宗潇帅 12 * 类名称:UserDao  13 * @date 2014-11-15 下午4:34:51  14 * 备注: 15 */ 16public class UserDao extends BaseDao{ 17 18    public List<Map<String, Object>> list(String name,int start, int size, 19            String order) { 20        List<Object> param = new ArrayList<Object>(); 21        String sql = "select u.* from userinfo u where 1=1 "; 22        if(null != name && name.trim().length() > 0){ 23            sql += " and u.name like ? "; 24            param.add("%"+name+"%"); 25        } 26        if(null == order || order.length() == 0){ 27            order = " birthday asc"; 28        } 29        return super.listByNative(sql, param.toArray(), start, size, order); 30    } 31 32    public int count(String name,int start, int size, 33            String order) { 34        List<Object> param = new ArrayList<Object>(); 35        String sql = "select count(*) from userinfo u where 1=1 "; 36        if(null != name && name.trim().length() > 0){ 37            sql += " and u.name like ? "; 38            param.add("%"+name+"%"); 39        } 40        return super.countByNative(sql, param.toArray()); 41    } 42 43    @SuppressWarnings("unchecked") 44    public Userinfo getUserByName(String name) { 45        String hql="select u from Userinfo u where u.name=? "; 46        List<Userinfo> list=super.list(hql, new Object[]{name}); 47        if(list!=null&&list.size()>0){ 48            return list.get(0); 49        }else{ 50            return null; 51        } 52    } 53 54}

4.add.jsp

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2<%@ page contentType="text/html;charset=UTF-8" %> 3<html xmlns="http://www.w3.org/1999/xhtml"> 4<head> 5<%@ include file="/common/meta.jsp"%> 6<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7<title>SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</title> 8<script type="text/javascript"> 9    function doCancel(){ 10        document.location.href="${ctx }/user/index"; 11    } 12     13    $(function(){ 14        $('#form1').form({ 15            onSubmit: function(){ 16                var v = $(this).form('validate'); 17                    if(v){ 18                        $("#doSubmit").unbind('click'); 19                    } 20                    return v; 21            }, 22            success:function(data){ 23                data = eval('(' + data + ')'); 24                if(data.success == true){ 25                    document.location.href="${ctx }/user/index"; 26                }else { 27                        $("#doSubmit").bind("click",function(){ 28                       $('#form1').submit(); 29                    }); 30                    alert(data.msg); 31                } 32            } 33        }); 34        $("#doSubmit").click(function() { 35            $('#form1').submit(); 36            return false; 37        }); 38    }); 39</script> 40</head> 41<body> 42<div class="tables_title">Add New UserInfo</div> 43<form action="${ctx }/user/add " id="form1" method="post"> 44    <div class="dengji_table"> 45        <div class="basic_table"> 46            <div class="clospan"> 47                <class="basic_name">名称</p> 48                <p> 49                <input name="name"  id="name" type="text" class="easyui-validatebox"  data-options="required:true" placeholder="输入中文"/> 50                </p> 51             </div> 52         </div> 53         <div class="basic_table"> 54            <div class="clospan"> 55                <class="basic_name" style=" border-right:none;">年龄</p> 56                <p> 57                <input name="age"  id="age" type="number"  min="18" max="99" class="easyui-validatebox"  data-options="required:true" placeholder="年龄不得小于18"/> 58                </p> 59        </div> 60        </div> 61        <div class="basic_table"> 62          <div class="clospan"> 63                <class="basic_name" style=" border-right:none;">地址</p> 64                <p> 65                <input name="address"  id="address" type="text"  class="easyui-validatebox"  data-options="required:true" placeholder="市区名"/> 66                </p> 67        </div> 68        </div> 69             <div class="clospan_func"> 70                <div class="btns"> 71                    <a href="javascript:void(0);" id="doSubmit" class="blank_btn">保存</a> 72                    <a href="javascript:void(0);" onclick="doCancel();" class="blank_btn">返回</a> 73                </div> 74            </div> 75        </div> 76      </form> 77</body> 78</html>

5.index.jsp

1<%@ page contentType="text/html;charset=UTF-8" %> 2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3<html xmlns="http://www.w3.org/1999/xhtml"> 4<head> 5<%@ include file="/common/meta.jsp"%> 6<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7<title>SpringMVC+Hibernate +MySql+ EasyUI ---CRUD</title> 8<script type="text/javascript"> 9    var searchString; 10 11    function resizeDg(){ 12        $('#dg').datagrid("resize", { width: $(window).width() * 0.4}); 13    } 14     15    function getCookie(c_name){ 16         if (document.cookie.length>0){ 17          c_start=document.cookie.indexOf(c_name + "="); 18          if (c_start!=-1){  19            c_start=c_start + c_name.length+1; 20            c_end=document.cookie.indexOf(";",c_start); 21            if (c_end==-1) { 22                c_end=document.cookie.length; 23            } 24            return document.cookie.substring(c_start,c_end); 25           }  26          } 27        return ""; 28    } 29     30    var pageSize = 20; 31    var pageNumber = 1; 32    var sortName = ''; 33    var sortOrder = ''; 34    function initDate(){ 35        var s = getCookie("role"); 36        s = decodeURIComponent(s); 37        if(!= null && s != ""){ 38            searchMap = eval('(' + s + ')'); 39            pageSize = searchMap.rows; 40            if(pageSize == null || pageSize == ""){ 41                pageSize = 20; 42            } 43            pageNumber = searchMap.pageNumber; 44            sortName = searchMap.sortName; 45            sortOrder = searchMap.sortOrder; 46            $("#name").val(searchMap.name ); 47        } 48    } 49     50    $(function(){ 51         $("#doSearch").click(function(){ 52            doSearch(); 53        }); 54        initDate(); 55        var name=$("#name").val(); 56        $('#dg').datagrid({ 57            url:"${ctx }/user/list", 58            pagination:true, 59            singleSelect:true, 60            pageSize:pageSize, 61            pageNumber:pageNumber, 62            sortOrder:sortOrder, 63            sortName:sortName, 64            queryParams:{   65                name:name, 66            }, 67            width:800, 68               columns:[[ 69                   {field:'name',title:'名称', width:100, align:"center",sortable:true}, 70                   {field:'age',title:'年龄', width:50, align:"center",sortable:true}, 71                   {field:'address',title:'地址', width:50, align:"center",sortable:true}, 72                   {field:'operation',title:'操作', width:340, align:"center", sortable:false, 73                       formatter:function(value,row,index){ 74                           var s =""; 75                        s+="<a href=\"javascript:void(0)\"><span onclick=\"javaScript:gotoModify('"+row.id+"');\">修改</span></a>"; 76                           s += "|"; 77                        s+="<a href=\"javascript:void(0)\"><span onclick=\"javaScript:gotoDel('"+row.id+"');\">删除</span>&nbsp;&nbsp;</a>"; 78                        return s; 79                       } 80                   } 81               ]] 82        }); 83         var p = $('#dg').datagrid('getPager');     84         $(p).pagination({     85              pageList: [10,20,50,100] 86          });   87         88        $("#doSearch").click(function(){ 89            doSearch(); 90        }); 91    }); 92     93     94    function gotoAdd(){ 95        var url = '${ctx }/user/gotoAdd'; 96        window.location.href=url; 97    } 98    function gotoModify(id){ 99        var url = '${ctx}/user/gotoModify?id='+id; 100        window.location.href=url; 101    } 102    function gotoDel(id){ 103        if(!confirm('确定删除所选记录?')){ 104            return; 105        } 106        var url = '${ctx}/user/delete?id='+id; 107        $.ajax({ 108            type : 'post', 109            url : url, 110            dataType: "json", 111                success:function(data){ 112                    if(data.success == true){ 113                        doSearch(); 114                    }else{ 115                        alert(data.msg); 116                    } 117                } 118            }); 119    } 120         121    function doSearch(){ 122        var name=$("#name").val(); 123        /* var schoolId=$("#schoolId").val(); */ 124        $("#dg").datagrid('load',{   125            name:name 126        }); //重新载入  127    } 128         129</script> 130</head> 131<body onload="resizeDg();" onresize="resizeDg();" > 132<div class="neirong"> 133<div class="add-content" style="margin-top:0"> 134    <div class="xinxi2"> 135           <div class="search_box"> 136           <p>名称: <input name="name" id="name" type="text" /></p> 137           <a href="javascript:void(0);" id="doSearch" class="blank_btn">查询</a></div> 138           <div class="btn_div"> 139           <a href="javascript:void(0);" onclick="gotoAdd();" id="xtsz_rygl_jsgl_add" class="blank_btn">新增</a> 140           </div> 141       </div> 142    <div class="contant_list" > 143        <!-- c_top start--> 144        <table  width="100%"> 145            <tr> 146                <td> 147                    <table id="dg"></table> 148                </td> 149            </tr> 150        </table> 151    </div> 152  </div> 153</div> 154</body> 155</html>

6.modfiy.jsp

1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2<%@ page contentType="text/html;charset=UTF-8" %> 3<html xmlns="http://www.w3.org/1999/xhtml"> 4<head> 5<%@ include file="/common/meta.jsp"%> 6<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7<title>修改用户信息</title> 8<script type="text/javascript"> 9 10    function doCancel(){ 11        document.location.href="${ctx }/user/index"; 12    } 13     14    $(function(){ 15        $('#form1').form({ 16            onSubmit: function(){ 17                var v = $(this).form('validate'); 18                    if(v){ 19                        $("#doSubmit").unbind('click'); 20                    } 21                    return v; 22            }, 23            success:function(data){ 24                data = eval('(' + data + ')'); 25                if(data.success == true){ 26                    document.location.href="${ctx }/user/index"; 27                }else { 28                        $("#doSubmit").bind("click",function(){ 29                       $('#form1').submit(); 30                    }); 31                    alert(data.msg); 32                } 33            } 34        }); 35        $("#doSubmit").click(function() { 36            $('#form1').submit(); 37            return false; 38        }); 39 40    }); 41</script> 42</head> 43<body> 44<div class="tables_title">修改用户</div> 45<form action="${ctx }/user/modify" id="form1" method="post"> 46 <input type="hidden" name="id" value="${userinfo.id }"></input> 47<div class="dengji_table"> 48        <div class="basic_table"> 49            <div class="clospan"> 50                <class="basic_name">名称</p> 51                <p> 52                <input name="name"  id="name" type="text" class="easyui-validatebox"  data-options="required:true" value="${userinfo.name}"/> 53                </p> 54             </div> 55         </div> 56         <div class="basic_table"> 57            <div class="clospan"> 58                <class="basic_name" style=" border-right:none;">年龄</p> 59                <p> 60                <input name="age"  id="age" type="number"  min="18" max="99" class="easyui-validatebox"  data-options="required:true" value="${userinfo.age}"/> 61                </p> 62        </div> 63        </div> 64        <div class="basic_table"> 65          <div class="clospan"> 66                <class="basic_name" style=" border-right:none;">地址</p> 67                <p> 68                <input name="address"  id="address" type="text"  class="easyui-validatebox"  data-options="required:true" value="${userinfo.address}"/> 69                </p> 70        </div> 71        </div> 72             <div class="clospan_func"> 73                <div class="btns"> 74                    <a href="javascript:void(0);" id="doSubmit" class="blank_btn">保存</a> 75                    <a href="javascript:void(0);" onclick="doCancel();" class="blank_btn">返回</a> 76                </div> 77            </div> 78        </div> 79      </form> 80</body> 81</html>

7.app-aop.xml

1<?xml version="1.0" encoding="UTF-8"?> 2<beans  3    xmlns="http://www.springframework.org/schema/beans"  4    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5    xmlns:aop="http://www.springframework.org/schema/aop" 6    xmlns:jee="http://www.springframework.org/schema/jee"  7    xmlns:tx="http://www.springframework.org/schema/tx" 8    xmlns:context="http://www.springframework.org/schema/context" 9    xsi:schemaLocation="http://www.springframework.org/schema/beans  10        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  11        http://www.springframework.org/schema/aop  12        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13        http://www.springframework.org/schema/tx  14        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  15        http://www.springframework.org/schema/jee  16        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd  17        http://www.springframework.org/schema/context  18        http://www.springframework.org/schema/context/spring-context-3.2.xsd" 19    default-autowire="byName"> 20     21     22    <aop:config> 23        <aop:pointcut id="testPointcut" expression="execution(* cn.com.elve.live..service..*.*(..))" /> 24    </aop:config> 25    <!-- 普通的AOP,如果想得到被代理的方法参数,那么就必须在配置里提前写好,这样有非常大的局限性 --> 26    <aop:config> 27        <aop:aspect ref="testSchemaAop"> 28            <aop:before method="before" pointcut-ref="testPointcut"/> 29            <aop:after-returning method="afterReturning" pointcut-ref="testPointcut" returning="object"/> 30            <aop:after-throwing method="afterThrowing" pointcut-ref="testPointcut" throwing="object"/> 31            <aop:after method="after" pointcut-ref="testPointcut"/> 32        </aop:aspect> 33    </aop:config> 34     35    <!-- 基于advisor的代理,代理类需要实现spring提供的接口,然后就可以用到强大的功能了。 --> 36    <aop:config> 37        <aop:advisor pointcut-ref="testPointcut" advice-ref="afterReturn" /> 38    </aop:config> 39     40     41     42    <!-- 需要由spring注入的bean定义 --> 43    <bean id="afterReturn" class="com.xs.demo.aop.AfterReturn"/> 44    <bean id="afterThrow" class="com.xs.demo.aop.AfterThrow"/> 45    <bean id="before" class="com.xs.demo.aop.Before"/> 46    <bean id="testSchemaAop" class="com.xs.demo.aop.TestSchemaAop"/> 47     48     49     50</beans>

8.app-context.xml

1<?xml version="1.0" encoding="UTF-8"?> 2<beans  3    xmlns="http://www.springframework.org/schema/beans"  4    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5    xmlns:aop="http://www.springframework.org/schema/aop" 6    xmlns:jee="http://www.springframework.org/schema/jee"  7    xmlns:tx="http://www.springframework.org/schema/tx" 8    xmlns:context="http://www.springframework.org/schema/context" 9    xsi:schemaLocation="http://www.springframework.org/schema/beans  10        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  11        http://www.springframework.org/schema/aop  12        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13        http://www.springframework.org/schema/tx  14        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  15        http://www.springframework.org/schema/jee  16        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd  17        http://www.springframework.org/schema/context  18        http://www.springframework.org/schema/context/spring-context-3.2.xsd" 19    default-autowire="byName"> 20    <!-- 使用annotation 自动注册bean --> 21    <context:annotation-config/> 22    <context:component-scan base-package="com.xs.demo"> 23        <context:include-filter type="regex" expression=".*Service"/> 24        <context:include-filter type="regex" expression=".*Dao"/> 25        <context:include-filter type="regex" expression=".*Job"/> 26    </context:component-scan> 27     28     29    <import resource="classpath:/app-db.xml"/> 30     31    <!-- 配置文件读取 --> 32    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 33        <property name="locations"> 34            <list> 35                <value>classpath:/jdbc.properties</value> 36                <value>classpath:/hibernate.properties</value> 37                <value>classpath:/log4j.properties</value> 38            </list> 39        </property> 40    </bean> 41     42     43     44    <!-- 开启AOP监听 只对当前配置文件有效 --> 45    <aop:aspectj-autoproxy expose-proxy="true"/> 46     47    <!-- 开启注解事务 只对当前配置文件有效 --> 48      <tx:annotation-driven transaction-manager="txManager"/> 49 50    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 51        <property name="sessionFactory" ref="sessionFactory"/> 52    </bean> 53 54    <tx:advice id="txAdvice" transaction-manager="txManager"> 55        <tx:attributes> 56            <tx:method name="save*" propagation="REQUIRED" /> 57            <tx:method name="add*" propagation="REQUIRED" /> 58            <tx:method name="create*" propagation="REQUIRED" /> 59            <tx:method name="insert*" propagation="REQUIRED" /> 60            <tx:method name="update*" propagation="REQUIRED" /> 61            <tx:method name="modify*" propagation="REQUIRED" /> 62            <tx:method name="upload*" propagation="REQUIRED" /> 63            <tx:method name="merge*" propagation="REQUIRED" /> 64            <tx:method name="del*" propagation="REQUIRED" /> 65            <tx:method name="remove*" propagation="REQUIRED" /> 66            <tx:method name="move*" propagation="REQUIRED" /> 67            <tx:method name="change*" propagation="REQUIRED" /> 68            <tx:method name="put*" propagation="REQUIRED" /> 69            <tx:method name="use*" propagation="REQUIRED"/> 70            <tx:method name="log*" propagation="REQUIRED"/> 71            <tx:method name="sh*" propagation="REQUIRED"/> 72            <tx:method name="bh*" propagation="REQUIRED"/> 73            <tx:method name="sf*" propagation="REQUIRED"/> 74            <tx:method name="bj*" propagation="REQUIRED"/> 75            <tx:method name="tf*" propagation="REQUIRED"/> 76            <tx:method name="mobileLogin" propagation="REQUIRED"/> 77            <tx:method name="register*" propagation="REQUIRED"/> 78            <tx:method name="goto*" propagation="REQUIRED"/> 79            <tx:method name="active*" propagation="REQUIRED"/> 80            <tx:method name="send*" propagation="REQUIRED"/> 81            <tx:method name="handel*" propagation="REQUIRED"/> 82            <tx:method name="attendance*" propagation="REQUIRED"/> 83            <tx:method name="batch" propagation="REQUIRED"/> 84            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到--> 85            <tx:method name="get*" propagation="REQUIRED" read-only="true" /> 86            <tx:method name="count*" propagation="REQUIRED" read-only="true" /> 87            <tx:method name="find*" propagation="REQUIRED" read-only="true" /> 88            <tx:method name="list*" propagation="REQUIRED" read-only="true" /> 89            <tx:method name="*" read-only="true" /> 90        </tx:attributes> 91    </tx:advice> 92    <aop:config expose-proxy="true"> 93        <!-- 只对业务逻辑层实施事务 --> 94        <aop:pointcut id="txPointcut" expression="execution(* com.xs.demo..service..*.*(..))" /> 95        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> 96    </aop:config> 97     98    <!-- 自动扫描测试用service --> 99<!--     <context:component-scan base-package="test.service"></context:component-scan> --> 100     101     102    <!--    javaMailSender  103    <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl" > 104        <property name="host" value="smtp.qq.com"/> 105        <property name="port" value="465"/> 106        <property name="username" value="elve@elve.cn"/> 107        <property name="password" value="654123.huo"/> 108        <property name="javaMailProperties"> 109            <props>  110                <prop key="mail.smtp.auth">true</prop>  111                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> 112            </props>  113        </property>  114    </bean> --> 115     116     117     118</beans>

9.app-servlet.xml

1<?xml version="1.0" encoding="UTF-8"?> 2 3 4<!-- 配置urlMapping --> 5<beans  6    xmlns="http://www.springframework.org/schema/beans"  7    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 8    xmlns:aop="http://www.springframework.org/schema/aop" 9    xmlns:jee="http://www.springframework.org/schema/jee"  10    xmlns:tx="http://www.springframework.org/schema/tx" 11    xmlns:mvc="http://www.springframework.org/schema/mvc" 12    xmlns:context="http://www.springframework.org/schema/context" 13    xsi:schemaLocation=" 14        http://www.springframework.org/schema/beans  15        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  16        http://www.springframework.org/schema/aop  17        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 18        http://www.springframework.org/schema/tx  19        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  20        http://www.springframework.org/schema/jee  21        http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 22        http://www.springframework.org/schema/mvc 23        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 24        http://www.springframework.org/schema/context  25        http://www.springframework.org/schema/context/spring-context-3.2.xsd" 26    default-autowire="byName"> 27    <!-- 启用基于注解的处理器映射,添加拦截器,类级别的处理器映射 --> 28    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> 29        <property name="interceptors"> 30            <list> 31                <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />   32            </list> 33        </property> 34    </bean> 35     36    <!-- 设置自动扫描的controller类的路径,可以写多个 --> 37    <!-- 例<context:component-scan base-package="cn.com.elve.live.controller,cn.com.elve.live.xxx"/> --> 38    <context:component-scan base-package="com.xs.demo.controller"/> 39    <!--  40    配置一个基于注解的定制的WebBindingInitializer,解决日期转换问题,方法级别的处理器映射, 41    有人说该bean要放在context:component-scan前面,要不然不起作用,但我试的放后面也可以啊。 42    --> 43    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 44        <property name="cacheSeconds" value="0" /> 45    </bean> 46     47    <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd --> 48    <mvc:resources mapping="/images/**" location="/images/"/> 49    <mvc:resources mapping="/js/**" location="/js/"/> 50    <mvc:resources mapping="/css/**" location="/css/"/> 51    <mvc:resources mapping="/swf/**" location="/swf/"/> 52    <mvc:resources mapping="/file/**" location="/file/"/> 53    <mvc:resources mapping="/FusionCharts/**" location="/FusionCharts/"/> 54     55    <!-- viewResolver 视图解析器,将视图名(ModelAndView中的view)解析成URL--> 56    <bean id="viewResolver" 57        class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 58        <property name="suffix" value=".jsp" /> 59        <property name="prefix" value="/WEB-INF/"/> 60        <property name="order" value="20"></property> 61        <property name="viewClass" 62            value="org.springframework.web.servlet.view.InternalResourceView" /> 63    </bean> 64     65     <!-- 针对freemarker的视图配置 --> 66    <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> 67        <property name="suffix" value=".ftl" /> 68        <property name="order" value="5"></property>    <!--resolver排序,本resolver会早于viewResolver--> 69        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property> 70        <property name="contentType" value="text/html;charset=UTF-8"></property> 71        <property name="requestContextAttribute" value="request" /> 72        <property name="exposeSpringMacroHelpers" value="true" /> 73        <property name="exposeRequestAttributes" value="true" /> 74        <property name="exposeSessionAttributes" value="true" /> 75    </bean> 76     77    <bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 78        <property name="templateLoaderPath" value="/WEB-INF/" /> 79        <property name="freemarkerSettings"> 80            <props> 81                <prop key="template_update_delay">0</prop> 82                <prop key="default_encoding">UTF-8</prop> 83                <prop key="number_format">0.##########</prop> 84                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> 85                <prop key="classic_compatible">true</prop> 86                <prop key="template_exception_handler">ignore</prop> 87            </props> 88        </property> 89    </bean> 90     91     92    <!--multipartResolver 支持分段文件上传 使用时form需要加上enctype="multipart/form-data"属性,且form的method设置为POST--> 93    <bean id="multipartResolver" 94        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 95        <property name="maxUploadSize" value="500400000" /> 96        <property name="maxInMemorySize" value="4096" /> 97        <property name="defaultEncoding" value="UTF-8"/> 98    </bean> 99     100    <!-- 国际化配置 -->   101    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" > 102        <property name="cookieName" value="clientlanguage"/> 103        <property name="cookieMaxAge" value="94608000"/> 104    </bean>   105     106</beans>

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

1package com.xs.demo.inteceptor; 2 3import javax.servlet.http.HttpServletRequest; 4import javax.servlet.http.HttpServletResponse; 5 6import org.springframework.web.servlet.HandlerInterceptor; 7import org.springframework.web.servlet.ModelAndView; 8 9 10public class Test implements HandlerInterceptor{ 11 12    @Override 13    public void afterCompletion(HttpServletRequest arg0, 14            HttpServletResponse arg1, Object arg2, Exception arg3) 15            throws Exception { 16        System.out.println("最后执行"); 17    } 18    @Override 19    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, 20            Object arg2, ModelAndView arg3) throws Exception { 21        System.out.println("第二步执行"); 22    } 23    @Override 24    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, 25            Object arg2) throws Exception { 26        System.out.println("主要的业务逻辑"); 27        return false; 28    } 29 30}

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

1public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 2            Object handler) throws Exception { 3        System.out.println("第一步"); 4        String path = request.getServletPath(); 5        if(path.startsWith("/user/")){ 6            Login userinfo = (Login) request.getSession().getAttribute(Constants.LOGIN_INFO); 7            if(null == userinfo && !path.startsWith("/user/gotoAdd/")){ 8                response.sendRedirect(request.getContextPath()+"/system/login.jsp"); 9                return false; 10            }else{ 11                System.out.println("else"); 12                return true; 13            } 14        } 15        return true; 16    }

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

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

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

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

点赞
收藏

评论区

加载中...

相关推荐

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

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )