Spring Security笔记:Hello World

本文演示了Spring Security的最最基本用法,二个页面(或理解成二个url),一个需要登录认证后才能访问(比如:../admin/),一个可匿名访问(比如:../welcome)

注:以下内容参考了 http://www.mkyong.com/spring-security/spring-security-hello-world-example/

 

一、利用STS(Spring Tools Suite)创建一个Spring MVC Project

如果不想使用STS,在普通Eclipse上安装Spring Tool Suite插件也行,用Spring插件创建项目的好处在于,很多配置已经自动帮我们生成好了,基本的项目架子已经具备,不需要在这上面花太多心思,下面是项目结构图

Spring Security笔记:Hello World_第1张图片

 pom文件中的dependencies

  1 xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4     <modelVersion>4.0.0modelVersion>
  5     <groupId>com.cnblogsgroupId>
  6     <artifactId>SpringSecurity-HelloWorld-XMLartifactId>
  7     <name>SpringSecurity-HelloWorld-XMLname>
  8     <packaging>warpackaging>
  9     <version>1.0version>
 10     <properties>
 11         <jdk.version>1.6jdk.version>
 12         <spring.version>3.2.8.RELEASEspring.version>
 13         <spring.security.version>3.2.3.RELEASEspring.security.version>
 14         <jstl.version>1.2jstl.version>
 15     properties>
 16 
 17     <dependencies>
 18         
 19         <dependency>
 20             <groupId>org.springframeworkgroupId>
 21             <artifactId>spring-coreartifactId>
 22             <version>${spring.version}version>
 23         dependency>
 24         <dependency>
 25             <groupId>org.springframeworkgroupId>
 26             <artifactId>spring-aopartifactId>
 27             <version>${spring.version}version>
 28         dependency>
 29         <dependency>
 30             <groupId>org.springframeworkgroupId>
 31             <artifactId>spring-beansartifactId>
 32             <version>${spring.version}version>
 33         dependency>
 34         <dependency>
 35             <groupId>org.springframeworkgroupId>
 36             <artifactId>spring-expressionartifactId>
 37             <version>${spring.version}version>
 38         dependency>
 39         <dependency>
 40             <groupId>org.springframeworkgroupId>
 41             <artifactId>spring-contextartifactId>
 42             <version>${spring.version}version>
 43         dependency>
 44         <dependency>
 45             <groupId>org.springframeworkgroupId>
 46             <artifactId>spring-context-supportartifactId>
 47             <version>${spring.version}version>
 48         dependency>
 49         <dependency>
 50             <groupId>org.springframeworkgroupId>
 51             <artifactId>spring-webartifactId>
 52             <version>${spring.version}version>
 53         dependency>
 54 
 55         <dependency>
 56             <groupId>org.springframeworkgroupId>
 57             <artifactId>spring-webmvcartifactId>
 58             <version>${spring.version}version>
 59         dependency>
 60 
 61         
 62         <dependency>
 63             <groupId>org.springframework.securitygroupId>
 64             <artifactId>spring-security-coreartifactId>
 65             <version>${spring.security.version}version>
 66         dependency>
 67 
 68         <dependency>
 69             <groupId>org.springframework.securitygroupId>
 70             <artifactId>spring-security-webartifactId>
 71             <version>${spring.security.version}version>
 72         dependency>
 73 
 74         <dependency>
 75             <groupId>org.springframework.securitygroupId>
 76             <artifactId>spring-security-configartifactId>
 77             <version>${spring.security.version}version>
 78         dependency>
 79 
 80         
 81         <dependency>
 82             <groupId>jstlgroupId>
 83             <artifactId>jstlartifactId>
 84             <version>${jstl.version}version>
 85         dependency>
 86 
 87     dependencies>
 88     <build>
 89         <plugins>
 90             <plugin>
 91                 <artifactId>maven-eclipse-pluginartifactId>
 92                 <version>2.9version>
 93                 <configuration>
 94                     <additionalProjectnatures>
 95                         <projectnature>org.springframework.ide.eclipse.core.springnatureprojectnature>
 96                     additionalProjectnatures>
 97                     <additionalBuildcommands>
 98                         <buildcommand>org.springframework.ide.eclipse.core.springbuilderbuildcommand>
 99                     additionalBuildcommands>
100                     <downloadSources>truedownloadSources>
101                     <downloadJavadocs>truedownloadJavadocs>
102                 configuration>
103             plugin>
104             <plugin>
105                 <groupId>org.apache.maven.pluginsgroupId>
106                 <artifactId>maven-compiler-pluginartifactId>
107                 <version>2.5.1version>
108                 <configuration>
109                     <source>1.6source>
110                     <target>1.6target>
111                     <compilerArgument>-Xlint:allcompilerArgument>
112                     <showWarnings>trueshowWarnings>
113                     <showDeprecation>trueshowDeprecation>
114                 configuration>
115             plugin>
116             <plugin>
117                 <groupId>org.codehaus.mojogroupId>
118                 <artifactId>exec-maven-pluginartifactId>
119                 <version>1.2.1version>
120                 <configuration>
121                     <mainClass>org.test.int1.MainmainClass>
122                 configuration>
123             plugin>
124         plugins>
125     build>
126 project>
pom.xml

 

二、Controller

 1 package com.cnblogs.yjmyzz;
 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 HelloController {
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 }
HelloController

毫无撸点,二个普通的Action而已,分别对应视图admin.jsp以及hello.jsp

 

三、web.xml

 1 xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 5 
 6     
 8     <context-param>
 9         <param-name>contextConfigLocationparam-name>
10         <param-value>/WEB-INF/spring/root-context.xmlparam-value>
11     context-param>
12 
13     
14     <listener>
15         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
16     listener>
17 
18     
19     <servlet>
20         <servlet-name>appServletservlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
22         <init-param>
23             <param-name>contextConfigLocationparam-name>
24             <param-value>/WEB-INF/spring/appServlet/servlet-context.xmlparam-value>
25         init-param>
26         <load-on-startup>1load-on-startup>
27     servlet>
28 
29     <servlet-mapping>
30         <servlet-name>appServletservlet-name>
31         <url-pattern>/url-pattern>
32     servlet-mapping>
33 
34     
35     <filter>
36         <filter-name>springSecurityFilterChainfilter-name>
37         <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
38     filter>
39 
40     <filter-mapping>
41         <filter-name>springSecurityFilterChainfilter-name>
42         <url-pattern>/*url-pattern>
43     filter-mapping>
44 
45 web-app>
web.xml

稍做解释一下:看似一大堆,但其实除了34-43行需要手动添加之外,其它全是STS工具自动生成的,34-43行通过添加一个过滤器,对每个请求进行“拦截”处理。

此外注意里面配置的几个xml文件

/WEB-INF/spring/root-context.xml 这是Spring-beans的核心主文件
/WEB-INF/spring/appServlet/servlet-context.xml 这是Spring-MVC的入口Servlet配置文件

四、servlet-context.xml

 1 xml version="1.0" encoding="UTF-8"?>
 2 <beans:beans xmlns="http://www.springframework.org/schema/mvc"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:beans="http://www.springframework.org/schema/beans"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 9 
10     
11     
12     
13     <annotation-driven />
14 
15     
16     <resources mapping="/resources/**" location="/resources/" />
17 
18     
19     <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20         <beans:property name="prefix" value="/WEB-INF/views/" />
21         <beans:property name="suffix" value=".jsp" />
22     beans:bean>
23     
24     <context:component-scan base-package="com.cnblogs.yjmyzz" />
25     
26     
27     
28 beans:beans>
servlet-context.xml

这个是工具自动生成的,主要用来处理Spring-MVC的相关内容,跟Security其实没啥关系

 

五、root-context.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     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6     
7     
8     <import resource="spring-security.xml" />
9 beans>
root-context.xml

这个看似乎平淡无奇,但其实包含了“配置模块化”的思想,通过import,把跟Security相关的配置,单独放在另一个xml文件中,然后import进来,配置文件特别多的时候,这样可以使Spring的配置看上去更有条理

 

六、spring-security.xml

 1 <beans:beans xmlns="http://www.springframework.org/schema/security"
 2     xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://www.springframework.org/schema/beans
 4     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 5     http://www.springframework.org/schema/security
 6     http://www.springframework.org/schema/security/spring-security-3.2.xsd">
 7 
 8     <http auto-config="true">
 9         <intercept-url pattern="/admin" access="ROLE_USER" />
10     http>
11 
12     <authentication-manager>
13         <authentication-provider>
14             <user-service>
15                 <user name="yjmyzz" password="123456" authorities="ROLE_USER" />
16             user-service>
17         authentication-provider>
18     authentication-manager>
19 
20 beans:beans>
spring-security.xml

这才是Security的精华所在,8-10行,表示“/admin”请求需要ROLE_USER角色的用户才能访问,12-18行配置了一个用户yjmyzz,以及密码123456,并将该用户授于ROLE_USER角色(当然:这里只是演示,实际应用中,更常见的做法是将用户名、密码放到数据库中)

 

七、admin.jsp及hello.jsp

hello.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" session="false"%>
 3 
 4 DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>${title}title>
 9 head>
10 <body>
11     <h1>Title:${title}h1>
12     <h1>Message:${message}h1>
13 body>
14 html>
hello.jsp

admin.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" session="true"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>${title}title>
 9 head>
10 <body>
11     <h1>Title : ${title}h1>
12     <h1>Message : ${message}h1>
13 
14     <c:if test="${pageContext.request.userPrincipal.name != null}">
15         <h2>
16             Welcome : ${pageContext.request.userPrincipal.name} | <a
17                 href="/j_spring_security_logout" />"> Logouta>
18         h2>
19     c:if>
20 body>
21 html>
admin.jsp

 二个常规页面,唯一值得注意的是17行的a链接: j_spring_security_logout,是Spring Security默认生成的logout地址,除非开发人员有其它设置,否则默认退出地址就是它

 

运行效果:

访问/welcome时,毫无阻力

 Spring Security笔记:Hello World_第2张图片

 

访问/admin时,会重定向到Spring Security自动生成的login页面 spring_security_login

Spring Security笔记:Hello World_第3张图片

 

在登录页面输入yjmyzz/123456后,自动跳转到登录前的页面 /admin

Spring Security笔记:Hello World_第4张图片

 

最后:附示例源代码:SpringSecurity-HelloWorld-XML(0717).zip

你可能感兴趣的:(Spring Security笔记:Hello World)