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

pom文件中的dependencies

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cnblogs</groupId>
<artifactId>SpringSecurity-HelloWorld-XML</artifactId>
<name>SpringSecurity-HelloWorld-XML</name>
<packaging>war</packaging>
<version>1.0</version>
<properties>
<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
</properties> <dependencies>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.version}</version>
</dependency> <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency> <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency> <!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency> </dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>

pom.xml

二、Controller

 package com.cnblogs.yjmyzz;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController { @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public ModelAndView welcome() { ModelAndView model = new ModelAndView();
model.addObject("title", "Welcome - Spring Security Hello World");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model; } @RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView admin() { ModelAndView model = new ModelAndView();
model.addObject("title", "Admin - Spring Security Hello World");
model.addObject("message", "This is protected page!");
model.setViewName("admin"); return model; } }

HelloController

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

三、web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param> <!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter> <filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </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

 <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean> <context:component-scan base-package="com.cnblogs.yjmyzz" /> </beans:beans>

servlet-context.xml

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

五、root-context.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> <import resource="spring-security.xml" />
</beans>

root-context.xml

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

六、spring-security.xml

 <beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd"> <http auto-config="true">
<intercept-url pattern="/admin" access="ROLE_USER" />
</http> <authentication-manager>
<authentication-provider>
<user-service>
<user name="yjmyzz" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager> </beans:beans>

spring-security.xml

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

七、admin.jsp及hello.jsp

hello.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
<h1>Title:${title}</h1>
<h1>Message:${message}</h1>
</body>
</html>

hello.jsp

admin.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="true"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1> <c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>
Welcome : ${pageContext.request.userPrincipal.name} | <a
href="<c:url value="/j_spring_security_logout" />"> Logout</a>
</h2>
</c:if>
</body>
</html>

admin.jsp

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

运行效果:

访问/welcome时,毫无阻力

Spring Security笔记:Hello World

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

Spring Security笔记:Hello World

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

Spring Security笔记:Hello World

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

上一篇:js 程序出发事件


下一篇:第六步:Lucene查询索引(优化一)