Spring Security4.X 简单实例介绍

简介

本例子采用的是SpringMVC、SpringSecurity和Spring整合的简单使用

使用gradle搭建的项目(gradle比maven更加便捷),可以自行了解

web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 5          version="3.1">
 6 
 7     <!-- Spring启动监听器 -->
 8     <listener>
 9         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
10     </listener>
11 
12     <!-- Spring配置 -->
13     <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <param-value>classpath:spring/spring-service.xml</param-value>
16     </context-param>
17 
18     <!-- 配置DispatcherServlet -->
19     <servlet>
20         <servlet-name>Spring MVC</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22         <init-param>
23             <param-name>contextConfigLocation</param-name>
24             <param-value>classpath:spring/spring-web.xml</param-value>
25         </init-param>
26     </servlet>
27     <servlet-mapping>
28         <servlet-name>Spring MVC</servlet-name>
29         <!-- 默认匹配所有的请求 -->
30         <url-pattern>/</url-pattern>
31     </servlet-mapping>
32 
33     <!-- 编码过滤器 乱码处理 -->
34     <filter>
35         <filter-name>encodingFilter</filter-name>
36         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
37         <async-supported>true</async-supported>
38         <init-param>
39             <param-name>encoding</param-name>
40             <param-value>UTF-8</param-value>
41         </init-param>
42     </filter>
43     <filter-mapping>
44         <filter-name>encodingFilter</filter-name>
45         <url-pattern>/*</url-pattern>
46     </filter-mapping>
47 
48     <!-- 配置Spring Security -->
49     <filter>
50         <filter-name>springSecurityFilterChain</filter-name>
51         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
52     </filter>
53 
54     <filter-mapping>
55         <filter-name>springSecurityFilterChain</filter-name>
56         <url-pattern>/*</url-pattern>
57     </filter-mapping>
58 
59 </web-app>

spring相关配置

  spring-service.xml

  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:tx="http://www.springframework.org/schema/tx"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context
 9         http://www.springframework.org/schema/context/spring-context.xsd
10         http://www.springframework.org/schema/aop
11         http://www.springframework.org/schema/aop/spring-aop.xsd
12         http://www.springframework.org/schema/security
13         http://www.springframework.org/schema/security/spring-security.xsd
14         http://www.springframework.org/schema/tx
15         http://www.springframework.org/schema/tx/spring-tx.xsd">
16 
17     <import resource="spring-security.xml"/>
18 
19 </beans>

  spring-web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 7 
 8     <!-- 1:开启SpringMVC注解模式 -->
 9     <!-- 简化配置:
10         (1):自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
11         (2).提供一系列:数据绑定,数字和日期的format @NumberFormat,@DataTimeFormat,
12                 xml,json默认读写支持
13      -->
14     <mvc:annotation-driven/>
15 
16     <!-- 2:静态资源 默认Servlet配置
17             1:加入对静态资源的处理:js,gif,png
18             2:允许使用"/"做整体映射
19     -->
20     <mvc:default-servlet-handler/>
21 
22     <!-- 3:配置jsp 显示ViewResolver -->
23     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
24         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
25         <property name="prefix" value="/views/"/>
26         <property name="suffix" value=".jsp"/>
27     </bean>
28 
29     <!--4: 扫描web相关的bean -->
30     <context:component-scan base-package="com.h3c.xservice.lc.controller" />
31 
32     <bean id="mappingJacksonHttpMessageConverter"
33           class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
34         <property name="supportedMediaTypes">
35             <list>
36                 <value>text/html;charset=UTF-8</value>
37             </list>
38         </property>
39     </bean>
40 
41 </beans>

  spring-security.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans:beans xmlns="http://www.springframework.org/schema/security"
 3              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4              xmlns:beans="http://www.springframework.org/schema/beans"
 5              xsi:schemaLocation="http://www.springframework.org/schema/security
 6                 http://www.springframework.org/schema/security/spring-security.xsd
 7                 http://www.springframework.org/schema/beans
 8                 http://www.springframework.org/schema/beans/spring-beans.xsd">
 9 
10     <http auto-config="true" use-expressions="true">
11         <intercept-url pattern="/admin" access="hasRole('ROLE_USER')" />
12         <logout logout-url="/j_spring_security_logout" invalidate-session="true" logout-success-url="/login"/>
13         <csrf disabled="true"/>
14     </http>
15 
16     <authentication-manager>
17         <authentication-provider>
18             <user-service>
19                 <user name="root" password="root" authorities="ROLE_USER"/>
20             </user-service>
21         </authentication-provider>
22     </authentication-manager>
23 
24 </beans:beans>

如果 配置access = "ROLE_USER",会出现500错误,4.X需要配置access = "hashRole('ROLE_USER')"

csrf标签下 disabled属性需要配置为true,否则logout会错

use-expressions = "true" 加和不加都没什么影响

java代码

 1 package com.h3c.xservice.lc.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestMethod;
 6 import org.springframework.web.servlet.ModelAndView;
 7 
 8 @Controller
 9 public class UserController {
10 
11     @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
12     public ModelAndView welcome() {
13 
14         ModelAndView model = new ModelAndView();
15         model.addObject("title", "Welcome - Spring Security Hello World");
16         model.addObject("message", "This is welcome page!");
17         model.setViewName("hello");
18         return model;
19 
20     }
21 
22     @RequestMapping(value = "/admin", method = RequestMethod.GET)
23     public ModelAndView admin() {
24 
25         ModelAndView model = new ModelAndView();
26         model.addObject("title", "Admin - Spring Security Hello World");
27         model.addObject("message", "This is protected page!");
28         model.setViewName("admin");
29 
30         return model;
31 
32     }
33 
34 }

jsp代码

admin.jsp

 

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 3 <html>
 4 <head>
 5     <title>${title}</title>
 6 </head>
 7 <body>
 8     <h1>Title : ${title}</h1>
 9     <h1>Message : ${message}</h1>
10 
11     <c:if test="${pageContext.request.userPrincipal.name != null}">
12         <h2>
13             Welcome : ${pageContext.request.userPrincipal.name} |
14             <a href="<c:url value="/j_spring_security_logout" />"> Logout</a>
15         </h2>
16     </c:if>
17 </body>
18 </html>

 

hello.jsp

 

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>${title}</title>
 5 </head>
 6 <body>
 7     <h1>Title:${title}</h1>
 8     <h1>Message:${message}</h1>
 9 </body>
10 </html>

 

浏览器访问

    

  访问127.0.0.1:8080/项目名/welcome,如下

 

   访问127.0.0.1:8080/项目名/admin,如下

  

当账号密码错误的时候会有错误提示,可以自行测试。正确后,会进去admin页面,如下

因为我配置了点击Logout后重定向到登录页面,所以点击后又会去到上图页面。

 

参考学习资料:

http://www.tuicool.com/articles/R7bQ3eb

http://www.cnblogs.com/yjmyzz/p/spring-security-with-spring-mvc-helloworld.html

http://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/reference/htmlsingle/

原文地址:https://www.cnblogs.com/tiecheng/p/6003476.html