我的是一个maven项目,所以第一步先导入spring security和spring的相关坐标。
properties>
<spring.version>4.2.4.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring security 安全控制框架start -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<!--spring security 安全控制框架end -->
web.xml配置过滤器
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</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>
spring security的核心配置:spring-security.xml
<!-- 在权限认证之前访问的资源 需要放行 -->
<http pattern="/login.html" security="none"></http><!-- security="none"表示不拦截 -->
<http pattern="/error.html" security="none"></http><!-- security="none"表示不拦截 -->
<!-- 配置HTTP安全控制规则-->
<http><!-- hasRole('ROLE_USER')表示这个角色必须要具有这个权限 -->
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!--配置表单 表单认证 -->
<form-login login-page="/login.html" default-target-url="/index.html"
always-use-default-target="true" authentication-failure-url="/error.html"
login-processing-url="/login"/>
<!-- 屏蔽跨域 -->
<csrf disabled="true"/>
</http>
<!-- 配置认证管理器-->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>