zoukankan      html  css  js  c++  java
  • 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插件创建项目的好处在于,很多配置已经自动帮我们生成好了,基本的项目架子已经具备,不需要在这上面花太多心思,下面是项目结构图

     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.0</modelVersion>
      5     <groupId>com.cnblogs</groupId>
      6     <artifactId>SpringSecurity-HelloWorld-XML</artifactId>
      7     <name>SpringSecurity-HelloWorld-XML</name>
      8     <packaging>war</packaging>
      9     <version>1.0</version>
     10     <properties>
     11         <jdk.version>1.6</jdk.version>
     12         <spring.version>3.2.8.RELEASE</spring.version>
     13         <spring.security.version>3.2.3.RELEASE</spring.security.version>
     14         <jstl.version>1.2</jstl.version>
     15     </properties>
     16 
     17     <dependencies>
     18         <!-- Spring dependencies -->
     19         <dependency>
     20             <groupId>org.springframework</groupId>
     21             <artifactId>spring-core</artifactId>
     22             <version>${spring.version}</version>
     23         </dependency>
     24         <dependency>
     25             <groupId>org.springframework</groupId>
     26             <artifactId>spring-aop</artifactId>
     27             <version>${spring.version}</version>
     28         </dependency>
     29         <dependency>
     30             <groupId>org.springframework</groupId>
     31             <artifactId>spring-beans</artifactId>
     32             <version>${spring.version}</version>
     33         </dependency>
     34         <dependency>
     35             <groupId>org.springframework</groupId>
     36             <artifactId>spring-expression</artifactId>
     37             <version>${spring.version}</version>
     38         </dependency>
     39         <dependency>
     40             <groupId>org.springframework</groupId>
     41             <artifactId>spring-context</artifactId>
     42             <version>${spring.version}</version>
     43         </dependency>
     44         <dependency>
     45             <groupId>org.springframework</groupId>
     46             <artifactId>spring-context-support</artifactId>
     47             <version>${spring.version}</version>
     48         </dependency>
     49         <dependency>
     50             <groupId>org.springframework</groupId>
     51             <artifactId>spring-web</artifactId>
     52             <version>${spring.version}</version>
     53         </dependency>
     54 
     55         <dependency>
     56             <groupId>org.springframework</groupId>
     57             <artifactId>spring-webmvc</artifactId>
     58             <version>${spring.version}</version>
     59         </dependency>
     60 
     61         <!-- Spring Security -->
     62         <dependency>
     63             <groupId>org.springframework.security</groupId>
     64             <artifactId>spring-security-core</artifactId>
     65             <version>${spring.security.version}</version>
     66         </dependency>
     67 
     68         <dependency>
     69             <groupId>org.springframework.security</groupId>
     70             <artifactId>spring-security-web</artifactId>
     71             <version>${spring.security.version}</version>
     72         </dependency>
     73 
     74         <dependency>
     75             <groupId>org.springframework.security</groupId>
     76             <artifactId>spring-security-config</artifactId>
     77             <version>${spring.security.version}</version>
     78         </dependency>
     79 
     80         <!-- jstl for jsp page -->
     81         <dependency>
     82             <groupId>jstl</groupId>
     83             <artifactId>jstl</artifactId>
     84             <version>${jstl.version}</version>
     85         </dependency>
     86 
     87     </dependencies>
     88     <build>
     89         <plugins>
     90             <plugin>
     91                 <artifactId>maven-eclipse-plugin</artifactId>
     92                 <version>2.9</version>
     93                 <configuration>
     94                     <additionalProjectnatures>
     95                         <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
     96                     </additionalProjectnatures>
     97                     <additionalBuildcommands>
     98                         <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
     99                     </additionalBuildcommands>
    100                     <downloadSources>true</downloadSources>
    101                     <downloadJavadocs>true</downloadJavadocs>
    102                 </configuration>
    103             </plugin>
    104             <plugin>
    105                 <groupId>org.apache.maven.plugins</groupId>
    106                 <artifactId>maven-compiler-plugin</artifactId>
    107                 <version>2.5.1</version>
    108                 <configuration>
    109                     <source>1.6</source>
    110                     <target>1.6</target>
    111                     <compilerArgument>-Xlint:all</compilerArgument>
    112                     <showWarnings>true</showWarnings>
    113                     <showDeprecation>true</showDeprecation>
    114                 </configuration>
    115             </plugin>
    116             <plugin>
    117                 <groupId>org.codehaus.mojo</groupId>
    118                 <artifactId>exec-maven-plugin</artifactId>
    119                 <version>1.2.1</version>
    120                 <configuration>
    121                     <mainClass>org.test.int1.Main</mainClass>
    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     <!-- 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>
    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     <!-- 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>
    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     <!-- Root Context: defines shared resources visible to all other web components -->
    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="<c:url value="/j_spring_security_logout" />"> Logout</a>
    18         </h2>
    19     </c:if>
    20 </body>
    21 </html>
    admin.jsp

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

    运行效果:

    访问/welcome时,毫无阻力

     

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

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

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

  • 相关阅读:
    2019-12-18
    java读取XML文件,及封装XML字符串
    java不用中间变量交换两个值
    oracle获取当前月的第一个星期五
    2019-10-23
    HTTP中GET请求与POST请求的区别
    Java面试题整理(转载)
    java 字节流与字符流的区别
    20190822
    C++标准库string
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/spring-security-with-spring-mvc-helloworld.html
Copyright © 2011-2022 走看看