首页 > 代码库 > Spring Security笔记:Hello World
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插件创建项目的好处在于,很多配置已经自动帮我们生成好了,基本的项目架子已经具备,不需要在这上面花太多心思,下面是项目结构图
二、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 = http://www.mamicode.com/{"/", "/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 = "http://www.mamicode.com/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 }
毫无撸点,二个普通的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 <!-- The definition of the Root Spring Container shared by all Servlets 7 and Filters --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name>10 <param-value>/WEB-INF/spring/root-context.xml</param-value>11 </context-param>12 13 <!-- Creates the Spring Container shared by all Servlets and Filters -->14 <listener>15 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>16 </listener>17 18 <!-- Processes application requests -->19 <servlet>20 <servlet-name>appServlet</servlet-name>21 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>22 <init-param>23 <param-name>contextConfigLocation</param-name>24 <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>25 </init-param>26 <load-on-startup>1</load-on-startup>27 </servlet>28 29 <servlet-mapping>30 <servlet-name>appServlet</servlet-name>31 <url-pattern>/</url-pattern>32 </servlet-mapping>33 34 <!-- Spring Security -->35 <filter>36 <filter-name>springSecurityFilterChain</filter-name>37 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>38 </filter>39 40 <filter-mapping>41 <filter-name>springSecurityFilterChain</filter-name>42 <url-pattern>/*</url-pattern>43 </filter-mapping>44 45 </web-app>
稍做解释一下:看似一大堆,但其实除了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 <!-- DispatcherServlet Context: defines this servlet‘s request-processing infrastructure -->11 12 <!-- Enables the Spring MVC @Controller programming model -->13 <annotation-driven />14 15 <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->16 <resources mapping="/resources/**" location="/resources/" />17 18 <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->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>
这个是工具自动生成的,主要用来处理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 <!-- Root Context: defines shared resources visible to all other web components -->7 8 <import resource="spring-security.xml" />9 </beans>
这个看似乎平淡无奇,但其实包含了“配置模块化”的思想,通过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>
这才是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>
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} | <a17 href="<c:url value="http://www.mamicode.com//j_spring_security_logout" />"> Logout</a>18 </h2>19 </c:if>20 </body>21 </html>
二个常规页面,唯一值得注意的是17行的a链接: j_spring_security_logout,是Spring Security默认生成的logout地址,除非开发人员有其它设置,否则默认退出地址就是它
运行效果:
访问/welcome时,毫无阻力
访问/admin时,会重定向到Spring Security自动生成的login页面 spring_security_login
在登录页面输入yjmyzz/123456后,自动跳转到登录前的页面 /admin
最后:附示例源代码:SpringSecurity-HelloWorld-XML.zip