(一)spring.mvc spring security3

刚学习java,最近工作之余做的一个demo,工作中使用了spring.mvc。但是security这部分工作中没有过多使用。该demo中主要实现了数据库表数据存储用户角色进而控制url。

网上搜索很多例子,大多是配置文件中建立一个admin一个user。使用数据库的比较少。

技术关键字:整体使用spring.mvc3层结构  css+div做的效果,第一次做的不漂亮,但是很有成就感,还没有学会切图

,ss3,主界面使用装饰器实现。页面控件使用jquery UI,表格使用的是jqgrid。访问数据库使用mybatis

 

首先上几个效果图,没有美工,完全是自己刚学css搞的效果。

渐变背景色在ff中有效果,在IE中无效,这个还没解决。。

登陆页面

登陆页面代码:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/themes/redmond/jquery-ui-1.7.1.custom.css" />
 8     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/themes/ui.jqgrid.css" />
 9     
10     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/style.css" />
11     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/controlStyle.css" />
12 
13     <script src="${pageContext.request.contextPath}/static/js/jQuery/jquery-1.4.2.js" type="text/javascript"></script>
14     <script src="${pageContext.request.contextPath}/static/js/myWebsite.menu.js" type="text/javascript"></script>
15 
16     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/i18n/grid.locale-en.js" type="text/javascript"></script>
17     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/jquery-ui-1.7.custom.js" type="text/javascript"></script>
18     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/jquery.jqGrid.src.js" type="text/javascript"></script>
19 <title>登录页面</title>
20 
21 <script type="text/javascript">
22 $(function(){
23     
24     $("#loginBtn").click(function(){
25         $("#loginForm").submit();        
26     });
27     
28     var msg = '${msg}';
29     if(msg=="CURRENT_USER_NAMEORPASSWORD_ERROR"){
30         $.showMsg("用户名或者密码错误.");
31     }
32 });
33 </script>
34 </head>
35 <body >
36     <div class="loginPageBody">
37         <form id="loginForm" name="loginForm" action="${pageContext.request.contextPath}/j_spring_security_check" method="post">
38 
39             <div class="login_form_msg_inner">
40                 <div  class="login_header_msg">
41                     <h3>Spring.MVC学习系统</h3>
42                 </div>
43                 <div class="login_body_msg">

44                     <div>
45                         <div  class="lbm_left">
46                             <img src="${pageContext.request.contextPath}/static/image/userIcon.JPG"></img>
47                         </div>
48                         <div class="lbm_right" >
49                             <ul style="float:left;">
50                                 <li>用户名</li>
51                                 <li><input type="text" name="j_username" value="" /> </li>
52                                 <li>密码</li>
53                                 <li><input type="password" name="j_password" value="" /></li>
54                             </ul>
55                         </div>
56                         
57                         <div class="lbm_login">
58                             <button id="loginBtn">登录</button>
59                         </div>
60                     </div>
61                 </div>
62                 <div class="login_footer_msg">
63                     <ul>
64                         <li><a href="${pageContext.request.contextPath}/auth/toRegisterUser.do">注册</a></li>
65                         <li><a href="${pageContext.request.contextPath}/auth/prelogin.do">登录</a></li>
66                         <li><a href="${pageContext.request.contextPath}/auth/toLostPsd.do">忘记密码</a></li>
67                         <li><a href="">忘记账号</a></li>
68                     </ul>
69                 </div>
70             </div>
71             <div class="lbm_login_copyright">
72                 <span style="font-family: arial;font-size: 14px;">&#169;</span> 1997-2013 pengsonghai版权所有</span> 
73             </div>
74         </form>
75     </div>
76     
77 </body>
78 </html>
View Code

 

主页面:装饰器+自己写的菜单UI,装饰器是该demo、中最简单的部分,配置文件和jsp都非常简单

 装饰器代码:头是系统说明或者公司logo

左边是导航菜单,右边是主区域,

主区域包含上下2部分,上部分可以是广告图片,下部分是每个菜单点击后的主界面。

页面居中花了点时间

  1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2 <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
  3 
  4 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  5 
  6 
  7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  8 <html>
  9 <head>
 10     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 11     
 12     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/themes/redmond/jquery-ui-1.7.1.custom.css" />
 13     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/themes/ui.jqgrid.css" />
 14     
 15     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/style.css" />
 16     <link rel="stylesheet" type="text/css" media="screen" href="${pageContext.request.contextPath}/static/css/controlStyle.css" />
 17         
 18 <%--     <script src="${pageContext.request.contextPath}/static/js/jQuery/jquery.js" type="text/javascript"></script> --%>
 19     <script src="${pageContext.request.contextPath}/static/js/jQuery/jquery-1.4.2.js" type="text/javascript"></script>
 20     <script src="${pageContext.request.contextPath}/static/js/myWebsite.menu.js" type="text/javascript"></script>
 21     
 22     
 23     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/i18n/grid.locale-en.js" type="text/javascript"></script>
 24     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/jquery-ui-1.7.custom.js" type="text/javascript"></script>
 25     <script src="${pageContext.request.contextPath}/static/js/jQuery/ui/jquery.jqGrid.src.js" type="text/javascript"></script>
 26     
 27     <%--jQuery UI --%>
 28 
 29     <script type="text/javascript">
 30         $(function(){
 31             $.initTree("#menu");
 32         });
 33         
 34         
 35     </script>
 36     
 37     <title>myWebsite</title>
 38     <decorator:head />
 39 </head>
 40 <body>
 41     <div id="page-container" style="margin-left: auto;margin-right: auto;">
 42         <div id="main-nav"></div>
 43         <div id="header">
 44             <div style="float:left;">
 45                 <span>Spring.MVC myBatis jQuery jqGrid</span><br/>
 46                 <span>这是一个demo.</span>
 47             </div>
 48             
 49             <div  style="float:right;">欢迎您,
 50                 <%
 51                 String name = "";
 52                 org.springframework.security.core.userdetails.UserDetails userDetails = 
 53                         (org.springframework.security.core.userdetails.UserDetails) org.springframework.security.core.context.SecurityContextHolder
 54                                 .getContext()
 55                                 .getAuthentication()
 56                                 .getPrincipal();
 57                 if(userDetails!=null){
 58                     name=userDetails.getUsername();
 59                 }
 60                 %>
 61                 <%= name%> 
 62                 <a href="${pageContext.request.contextPath}/auth/logout.do">退出</a>
 63             </div>
 64         </div>
 65         <!-- main region -->
 66         <div id="content">
 67             <div class="logos">
 68                 <img alt="log" src="${pageContext.request.contextPath}/static/image/javaLogo.jpg" class="logo">
 69                 <img alt="log" src="${pageContext.request.contextPath}/static/image/spring.jpg" class="logo">
 70                 <img alt="log" src="${pageContext.request.contextPath}/static/image/jquery.jpg" class="logo">
 71                 <img alt="log" src="${pageContext.request.contextPath}/static/image/mybatis.jpg" class="logo">
 72             </div>
 73             <decorator:body />
 74         </div>
 75         <!-- left region -->
 76         <div id="sidebar-a">
 77             <div id="menu">
 78                 <c:forEach items="${mainPageLeftMenudData.rows}" var="item">
 79                     <div>
 80                         <h4 class="menuTitle"><span class="firstLevel"></span>${item.name}</h4>
 81                         <div class="childMenu_Div">
 82                             <ul>
 83                                 <c:forEach items="${item.childMenus}" var="childItem">
 84                                     <c:if test="${childItem.netType == 'IN'}">
 85                                         <li><a href="${pageContext.request.contextPath}${childItem.url}">${childItem.name}</a></li>
 86                                     </c:if>
 87                                     <c:if test="${childItem.netType == 'OUT'}">
 88                                         <li><a href="${childItem.url}" target="_blank">${childItem.name}</a></li>
 89                                     </c:if>
 90                                     
 91                                 </c:forEach>
 92                             </ul>
 93                         </div>
 94                     </div>
 95                 </c:forEach>
 96             </div>
 97         </div>
 98         <div id="footer">
 99             <span style="font-family: arial;font-size: 14px;">&#169;</span> 1997-2013 pengsonghai版权所有</span> 
100         </div>
101     </div>
102 </body>
103 </html>
View Code


jqgrid:

jqgrid示例代码:

jqgrid花费时间最多,上班网络不好,并且有诸多限制,搜索不到有用的信息,自己摸索浪费很多时间

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>myWebsite-查看所有用户</title>
 8 
 9 <script type="text/javascript">
10 
11     $(document).ready(function() {
12         
13     });
14     
15     $(function(){
16            $("#alluser").jqGrid({
17                url:"allUserAjax.do",
18                datatype: "json",
19                height: 250,
20                width:600,
21                colNames:['编号','用户名', '状态', '说明'],
22                colModel:[
23                       
24                        {name:'id',index:'id', width:60, sorttype:"long"},
25                        {name:'userName',index:'userName', width:120,sorttype:"string"},
26                        {name:'status',index:'status', width:90,sorttype:"string"},
27                        {name:'descn',index:'descn', width:120,sorttype:"string"}               
28                ],
29                jsonReader: {
30                    root:"rows",       // 数据行(默认为:rows)
31                    page: "page",      // 当前页
32                    total: "total",    // 总页数
33                    records: "records",// 总记录数
34                    repeatitems : false// 设置成false,在后台设置值的时候,可以乱序。且并非每个值都得设
35                    },
36                    sortname:'id',
37                 sortorder:'asc',
38                 viewrecords:true,
39                 rowNum:10,
40                 rowList:[10,20,30],
41                pager:$("#pager"),
42                caption: "用户列表:"
43            }).navGrid('#pager',{edit:false,add:false,del:false});
44         });
45     
46 
47 </script>
48 </head>
49 <body >
50     <div class="index_main_show" style="position: relative;">
51         <div class="right_header">
52             用户管理--预览
53         </div>
54         <div class="contentRightDiv">
55         
56             <table cellpadding="0" cellspacing="0" border="0" id="alluser">
57             </table>
58             <div id="pager"></div>
59         </div>
60     </div>
61 </body>
62 </html>
View Code

 

 

 

报msg和error:

该效果是jquery ui中的dailog控件又简单包装了一下。使用时仅需要$.showMSg或者$.showError。转如字符串即可。

自己包装写的代码不多,但是重在动手,不能全是拿来主义吧。

 

 

dailog窗口2

 代码:

  1 <%@ page language="java" contentType="text/html; charset=UTF-8"
  2     pageEncoding="UTF-8"%>
  3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4 <html>
  5 <head>
  6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7 <title>myWebsite-查看所有菜单</title>
  8 
  9 <script type="text/javascript">
 10 var baseUrl = "${pageContext.request.contextPath}";
 11 
 12     $(document).ready(function() {
 13         
 14         $("#addMenu").click(function(){
 15             // 1 首先请求一级菜单数据
 16             getFirstLevelMenu();
 17         });
 18         
 19         $("#dialog").dialog({
 20             autoOpen: false,
 21             bgiframe: true,
 22             resizable: false,
 23             height:300,
 24             width:300,
 25             modal: true,
 26             overlay: {
 27                 backgroundColor: '#000',
 28                 opacity: 0.5
 29             },
 30             buttons: {
 31                 '保存': function() {
 32                     submit();
 33                 },
 34                 '取消': function() {
 35                     $("#dialog").dialog('close');
 36                 }
 37             }
 38         });
 39     });
 40 
 41     $(function(){
 42            $("#allmenu").jqGrid({
 43                url:"allMenuAjax.do",
 44                datatype: "json",
 45                height: 250,
 46                colNames:['编号','上级编号', '菜单名', 'URL', '权限','类型'],
 47                colModel:[
 48                        {name:'id',index:'id', width:88, sorttype:"long"},
 49                        {name:'parentId',index:'parentId', width:90,sorttype:"long"},
 50                        {name:'name',index:'name', width:100,sorttype:"string"},
 51                        {name:'url',index:'url', width:150,sorttype:"string"},
 52                        {name:'authority',index:'authority', width:120,sorttype:"string"},                
 53                        {name:'netType',index:'netType', width:120,sorttype:"string"}               
 54                            ],
 55                jsonReader: {
 56                    root:"rows",       // 数据行(默认为:rows)
 57                    page: "page",      // 当前页
 58                    total: "total",    // 总页数
 59                    records: "records",// 总记录数
 60                    repeatitems : false// 设置成false,在后台设置值的时候,可以乱序。且并非每个值都得设
 61                    },
 62                    sortname:'id',
 63                 sortorder:'asc',
 64                 viewrecords:true,
 65                 rowNum:10,
 66                 rowList:[10,20,30],
 67                pager:$("#pager"),
 68                caption: "菜单列表:"
 69            }).navGrid('#pager',{edit:false,add:false,del:false});
 70         });
 71     
 72     function submit(){
 73         
 74         var pid = $("#parentId").val() ;
 75         var n = $("#name").val() ;
 76         var u = $("#url").val();
 77         var i = $("#netType").val() ;
 78         
 79         if(!pid || !n||!u||!i){
 80             return;
 81         }
 82         
 83         if(pid.length<1 || n.length<1 ||u.length<1 ||i.length<1){
 84             return;
 85         }

 86         
 87         var url1 = baseUrl + "/menu/addMenuAjax.do?parentId=" + pid
 88                           + "&name=" + encodeURIComponent(encodeURIComponent(n))
 89                           + "&url=" + u + "&netType=" + i;
 90 
 91         $.ajax({url:url1, 
 92             type:"POST", 
 93             dataType:'json',
 94             success:function(str){
 95                 alert("新增菜单成功!");
 96                 $("#dialog").dialog('close');
 97             },
 98             error:function(er){
 99                 alert(er);
100             }
101         });
102     }
103     
104     // 请求一级菜单数据
105     function getFirstLevelMenu(){
106         
107         var url1 = baseUrl + "/menu/getFirstLevelMenu.do";
108 
109         $.ajax({url:url1, 
110             type:"POST", 
111             dataType:'json',
112             success:function(str){
113                 
114                 // 2 成功后设置一级菜单ddl
115                 initDDL(str.rows);
116                 
117                 // 3 然后show dialog window
118                 $('#dialog').dialog('open');
119             },
120             error:function(er){
121                 alert(er);
122             }
123         });
124     }
125     
126     // 初始化新增窗口的父级菜单DDL数据源
127     function initDDL(rows){
128         var menus = rows;
129         var ddlOption = "<option value='-1'>一级菜单</option>";
130         //id name
131         for(var i=0;i<menus.length;i++){
132             ddlOption+="<option value='"+menus[i].id+"'>"+menus[i].name+"</option>";
133         }
134         $("#parentId").html(ddlOption);
135     }
136 </script>
137 </head>
138 <body>
139 <div class="index_main_show" style="position: relative;">
140         <div class="right_header">
141             菜单管理--预览
142         </div>
143         <div class="contentRightDiv">
144             <table cellpadding="0" cellspacing="0" border="0" id="allmenu">
145             </table>
146             <div id="pager"></div>
147         </div>
148         <div class="contentRightDiv">
149             <button id="addMenu">新增菜单</button>
150         </div>
151         <div id="dialog" title="新增菜单">
152             <table>
153                 <tr>
154                     <td>上级菜单:</td>
155                     <td>
156                         <select id="parentId" style="max-width: 300px;">
157                         </select>
158                     </td>
159                 </tr>
160                 <tr>
161                     <td>菜单名称:</td>
162                     <td><input type="text" id="name"></td>
163                 </tr>
164                 <tr>
165                     <td>URL:</td>
166                     <td><input type="text"  id="url"></td>
167                 </tr>
168 
169                 <tr>
170                     <td>内/外网:</td>
171                     <td><input type="text"  id="netType"></td>
172                 </tr>
173             </table>
174         </div>
175     </div>
176 </body>
177 </html>
View Code

 

 

点击查看菜单,该url需要role_adimin才可以看,如果role_user的用户查看会提示没有权限

 

主要代码:

web.xml的配置应该很成熟了,大家简单看看就好

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  3   <display-name>myWebsite</display-name>
  4   <welcome-file-list>
  5     <welcome-file>default.jsp</welcome-file>
  6   </welcome-file-list>
  7   
  8       <context-param>
  9         <param-name>contextConfigLocation</param-name>
 10         <param-value>classpath:spring/applicationContext.xml</param-value>
 11     </context-param>
 12     
 13     <context-param>
 14         <param-name>log4jConfigLocation</param-name>
 15         <param-value>classpath:log4j/log4j.xml</param-value>
 16     </context-param>
 17     
 18     <context-param>a
 19         <param-name>log4jRefreshInterval</param-name>
 20         <param-value>60000</param-value>
 21     </context-param>
 22     
 23     <!-- Log4j  -->
 24     <listener>
 25         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 26     </listener>
 27     
 28     <!-- Spring  -->
 29     <listener>
 30         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 31     </listener>
 32     <!-- Spring Interceptor  -->
 33     <listener>
 34         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 35     </listener>
 36     
 37   <filter>
 38     <filter-name>springSecurityFilterChain</filter-name>
 39     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 40   </filter>
 41   <filter>
 42     <filter-name>sitemesh</filter-name>
 43     <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
 44   </filter>
 45   
 46     <!--   -->
 47     <filter>
 48         <filter-name>CharacterEncodingFilter</filter-name>
 49         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 50         <init-param>
 51             <param-name>encoding</param-name>
 52             <param-value>UTF-8</param-value>
 53         </init-param>
 54         <init-param>
 55             <param-name>forceEncoding</param-name>
 56             <param-value>true</param-value>
 57         </init-param>
 58     </filter>
 59     
 60     <!-- spring mvc controller -->
 61     <servlet>
 62         <servlet-name>spring</servlet-name>
 63         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 64         <init-param>
 65             <param-name>contextConfigLocation</param-name>
 66             <param-value>classpath:spring/applicationContext-mvc*.xml</param-value>
 67         </init-param>
 68         <load-on-startup>1</load-on-startup>
 69     </servlet>
 70     
 71   <filter-mapping>
 72     <filter-name>springSecurityFilterChain</filter-name>
 73     <url-pattern>/*</url-pattern>
 74   </filter-mapping>
 75   <filter-mapping>
 76     <filter-name>CharacterEncodingFilter</filter-name>
 77     <url-pattern>/*</url-pattern>
 78   </filter-mapping>
 79   <filter-mapping>
 80     <filter-name>sitemesh</filter-name>
 81     <url-pattern>*.do</url-pattern>
 82   </filter-mapping>
 83   <servlet-mapping>
 84     <servlet-name>spring</servlet-name>
 85     <url-pattern>*.do</url-pattern>
 86   </servlet-mapping>
 87   
 88     <session-config>
 89     <session-timeout>20</session-timeout>
 90   </session-config>
 91   
 92   <error-page>
 93     <error-code>400</error-code>
 94     <location>/error/400.jsp</location>
 95   </error-page>
 96   <error-page>
 97     <error-code>404</error-code>
 98     <location>/error/404.jsp</location>
 99   </error-page>
100   <error-page>
101     <error-code>500</error-code>
102     <location>/error/500.jsp</location>
103   </error-page>
104 </web-app>
View Code

 

sitemesh也很简单


sitemesh.xml

 1 <sitemesh>
 2     <property name="decorators-file" value="/WEB-INF/decorators.xml"/>
 3     <excludes file="${decorators-file}"/>
 4 
 5     <page-parsers>
 6         <parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" />
 7     </page-parsers>
 8     <decorator-mappers>
 9         <mapper class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper">
10             <param name="property.1" value="meta.decorator" />
11             <param name="property.2" value="decorator" />
12         </mapper>
13         <mapper class="com.opensymphony.module.sitemesh.mapper.FrameSetDecoratorMapper"/>
14         <mapper class="com.opensymphony.module.sitemesh.mapper.PrintableDecoratorMapper">
15             <param name="decorator" value="printable" />
16             <param name="parameter.name" value="printable" />
17             <param name="parameter.value" value="true" />
18         </mapper>
19         <mapper class="com.opensymphony.module.sitemesh.mapper.FileDecoratorMapper"/>
20         <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
21             <param name="config" value="${decorators-file}" />
22         </mapper>
23     </decorator-mappers>
24 </sitemesh>
View Code

decorators.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <decorators defaultdir="/WEB-INF/decorators">
 3     <excludes>
 4          <pattern>/default.jsp</pattern>
 5          <pattern>/static/**</pattern>
 6          <pattern>/auth/login.do</pattern>
 7          <pattern>/auth/prelogin.do</pattern>
 8          <pattern>/auth/toRegisterUser.do</pattern>
 9          <pattern>/auth/registerUser.do</pattern>
10     </excludes>
11 
12     <decorator name="mainPage" page="mainPage.jsp">
13         <pattern>/auth/index.do</pattern>
14         <pattern>/auth/allUser.do</pattern>
15         <pattern>/auth/changePsd.do</pattern>
16         <pattern>/auth/changeUserDetail.do</pattern>
17         <pattern>/menu/*.do</pattern>
18     </decorator>
19 </decorators>
View Code

application-mvc.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:util="http://www.springframework.org/schema/util"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans
 9                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
10                         http://www.springframework.org/schema/mvc 
11                         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
12                         http://www.springframework.org/schema/context 
13                         http://www.springframework.org/schema/context/spring-context-3.0.xsd
14                         http://www.springframework.org/schema/util 
15                         http://www.springframework.org/schema/util/spring-util-3.0.xsd">
16     
17     <context:component-scan base-package="com.cn.sh.**.controller" />
18     
19     <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20         <property name="prefix" value="/WEB-INF/view/" />
21         <property name="suffix" value=".jsp" />
22         <property name="order" value="10"/>
23     </bean>
24     
25     <!-- FreeMarker -->
26     <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
27         <!-- freemarker -->
28         <property name="templateLoaderPath" value="/WEB-INF/templates/"/>
29         <property name="freemarkerSettings">
30             <props>
31                 <prop key="template_update_delay">0</prop>
32                 <prop key="default_encoding">UTF-8</prop>
33                 <prop key="number_format">0.##########</prop>
34                 <prop key="classic_compatible">true</prop>
35                 <prop key="template_exception_handler">ignore</prop>
36             </props> 
37         </property>
38     </bean>
39     
40     <!-- FreeMarker -->
41     <bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
42         <property name="contentType" value="text/html; charset=utf-8"/>  
43         <property name="cache" value="true"/>
44         <property name="suffix" value=".ftl"/>
45         <property name="order" value="5"/>
46     </bean>
47     
48     <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
49     
50     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
51         <property name="messageConverters">
52             <util:list id="beanList">
53                 <ref bean="mappingJacksonHttpMessageConverter"/>
54             </util:list>
55         </property>
56         <property name="cacheSeconds" value="0" />
57     </bean>
58 </beans>
View Code

application-security.xml这个对我来说是这次做demo的核心部分

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans:beans xmlns="http://www.springframework.org/schema/security" 
 3     xmlns:beans="http://www.springframework.org/schema/beans" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
 7     http://www.springframework.org/schema/security 
 8     http://www.springframework.org/schema/security/spring-security-3.1.xsd">
 9     
10         <http pattern="/static/css/**"         security="none" />  
11         <http pattern="/static/image/**"     security="none" />  
12         <http pattern="/static/js/**"         security="none" />  
13         <http pattern="/403.jsp"             security="none" /> 
14         <http pattern="/default.jsp"         security="none" />  
15         <http pattern="/auth/prelogin.do"         security="none" /> 
16         
17     <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint"
18             access-denied-page="/error/403.jsp">
19         <!--form_login 
20         <form-login login-page="/default.jsp"
21                     default-target-url="/auth/index.do"
22                     authentication-failure-url="/auth/prelogin.do"/>
23         -->
24         <!---->
25         <logout logout-success-url="/auth/prelogin.do"/>
26          <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"  />  
27         <custom-filter ref="filterSecurityInterceptor"  before="FILTER_SECURITY_INTERCEPTOR" />
28     </http>
29     
30    <beans:bean id="filterSecurityInterceptor"
31         class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor" autowire="byType">
32         <beans:property name="authenticationManager" ref="myAuthenticationManager" />
33         <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
34          <beans:property name="securityMetadataSource" ref="filterInvocationSecurityMetadataSource" />       
35     </beans:bean>
36 
37     <beans:bean id="filterInvocationSecurityMetadataSource"
38         class="com.cn.sh.framework.security.JdbcFilterInvocationDefinitionSourceFactoryBean">
39         <beans:property name="dataSource" ref="dataSource"/>
40         <beans:property name="resourceQuery" value="select re.res_string,r.name from role r join resc_role rr on r.id=rr.role_id join resc re on re.id=rr.resc_id order by re.priority,res_string"/>
41     </beans:bean>
42      <authentication-manager alias="myAuthenticationManager">  
43         <authentication-provider user-service-ref="myUserDetailServiceImpl"/>  
44     </authentication-manager>  
45     <beans:bean id="myAccessDecisionManager" class="com.cn.sh.framework.security.MyAccessDecisionManager"/>
46     <beans:bean id="myUserDetailServiceImpl" class="com.cn.sh.framework.security.MyUserDetailServiceImpl"/> 
47     <!--login filter begin-->
48     <beans:bean id="loginFilter"  class="com.cn.sh.framework.security.MyUsernamePasswordAuthenticationFilter">  
49         <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>  
50         <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>  
51         <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>  
52         <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>  
53     </beans:bean>
54     <beans:bean id="loginLogAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">  
55         <beans:property name="defaultTargetUrl" value="/auth/index.do"></beans:property>  
56     </beans:bean>  
57     <beans:bean id="simpleUrlAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
58         <beans:property name="defaultFailureUrl" value="/default.jsp"></beans:property>  
59     </beans:bean>  
60     <beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">      
61         <beans:property name="loginFormUrl" value="/auth/login.do" />      
62         <beans:property name="forceHttps" value="false" />      
63     </beans:bean>   
64     <!--login filter end-->
65 </beans:beans>
View Code

 第二篇会贴出security使用到的代码和自己摸索时碰到的卡点

posted on 2013-05-23 22:46  HiCC  阅读(785)  评论(0编辑  收藏  举报