采用注解方式实现security
采用注解方式使用security,首先我们需要用注解方式实现Spring MVC,新建一个Maven项目

<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.petter</groupId>
<artifactId>hello-world-annotation</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>hello-world-annotation Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.version>4.3.5.RELEASE</spring.version>
<spring.security.version>4.2.1.RELEASE</spring.security.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.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!-- Spring Security -->
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
二、配置SpringMVC项目
package com.petter.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
/**
* 相当于spring的xml配置文件
* @author hongxf
* @since 2017-03-08 10:11
*/
@EnableWebMvc
@Configuration
@ComponentScan({"com.petter.*"})
public class AppConfig {
@Bean
public SpringResourceTemplateResolver springResourceTemplateResolver() {
SpringResourceTemplateResolver springResourceTemplateResolver = new SpringResourceTemplateResolver();
springResourceTemplateResolver.setPrefix("/WEB-INF/pages/");
springResourceTemplateResolver.setSuffix(".html");
springResourceTemplateResolver.setTemplateMode("HTML");
springResourceTemplateResolver.setCacheable(false);
springResourceTemplateResolver.setCharacterEncoding("UTF-8");
return springResourceTemplateResolver;
}
@Bean
public SpringTemplateEngine springTemplateEngine() {
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setTemplateResolver(springResourceTemplateResolver());
return springTemplateEngine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(springTemplateEngine());
thymeleafViewResolver.setCharacterEncoding("UTF-8");
return thymeleafViewResolver;
}
}
2、编写SpringMVCInitiallizer类文件,继承AbstractAnnotationConfigDispatcherServletInitializer,其相当于没有了的web.xml文件,代码如下:
package com.petter;
import com.petter.config.AppConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* 相当于web.xml文件
* @author hongxf
* @since 2017-03-08 10:17
*/
public class SpringMVCInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 应用程序上下文配置文件,可以是多个,即相当于多个xml文件配置
* @return
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{AppConfig.class};
}
/**
* 获取应用程序上下文配置文件
* 如果所有配置已经在AppConfig中配置,则可以设为null
* @return
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
/**
* 指定拦截路径
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
3、编写admin.html和hello.html文件,内容一致
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>admin</title>
</head>
<body>
<h1 th:text="|标题: ${title}|">Title : XXX</h1>
<h1 th:text="|信息: ${message}|">Message : XXX</h1>
</body>
</html>
4、编写HelloController
package com.petter.web;
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;
/**
* @author hongxf
* @since 2017-03-08 9:29
*/
@Controller
public class HelloController {
@RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model;
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is protected page - Admin Page!");
model.setViewName("admin");
return model;
}
@RequestMapping(value = "/dba", method = RequestMethod.GET)
public ModelAndView dbaPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is protected page - Database Page!");
model.setViewName("admin");
return model;
}
}
启动程序,访问http://localhost:8080/admin 结果如下:

package com.petter.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* 相当于在web.xml中配置spring security的filter
* @author hongxf
* @since 2017-03-08 10:10
*/
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
//do nothing
}
相当于在web.xml文件中配置的filter,即
<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>
2、配置security的过滤配置,编写文件SecurityConfig,代码如下:
package com.petter.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 相当于spring-security.xml中的配置
* @author hongxf
* @since 2017-03-08 9:30
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 在内存中设置三个用户
* @param auth
* @throws Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("hongxf").password("123456").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
}
/**
* 配置权限要求
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
.and().formLogin();
}
}
相当于xml配置文件如下所示:
<http auto-config="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/dba**" access="hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="hongxf" password="123456" authorities="ROLE_USER" />
<user name="admin" password="123456" authorities="ROLE_ADMIN" />
<user name="dba" password="123456" authorities="ROLE_DBA" />
</user-service>
</authentication-provider>
</authentication-manager>
启动程序,访问http://localhost:8080/dba 会跳转到默认登录页:


采用注解方式实现security的更多相关文章
- Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法
Spring MVC 中采用注解方式 Action中跳转到另一个Action的写法 在Action中方法的返回值都是字符串行,一般情况是返回某个JSP,如: return "xx" ...
- spring security结合数据库验证用户-注解方式
项目目录结构如下: 首先数据库的建立和数据导入,以及一些类的依赖参考XML配置方式,需要修改一些配置. 一.在AppConfig文件中添加DataSource的配置 @Bean(name = &quo ...
- Spring学习5-Spring整合JDBC及其事务处理(注解方式)
一.整合的步骤 1.步骤一:首先要获得DataSource连接池(推荐使用B方式): 要对数据库执行任何的JDBC操作,需要有一个Connection.在Spring中,Connection对象是 ...
- Spring注解方式配置说明
1.<context:annotation-config/>与<context:component-scan base-package=”XX.XX”/> 在基于主机方式配置S ...
- Spring Boot2.0之注解方式启动Springmvc
回顾下springmvc原理图: DispatcherServlet是Spring MVC的核心,每当应用接受一个HTTP请求,由DispatcherServlet负责将请求分发给应用的其他组件. 在 ...
- 使用注解方式搭建SpringMVC
1.以前搭建Spring MVC 框架一般都使用配置文件的方式进行,相对比较繁琐.spring 提供了使用注解方式搭建Spring MVC 框架的方式,方便简洁.使用Spring IOC 作为根容器管 ...
- ActiveMQ学习总结(10)——ActiveMQ采用Spring注解方式发送和监听
对于ActiveMQ消息的发送,原声的api操作繁琐,而且如果不进行二次封装,打开关闭会话以及各种创建操作也是够够的了.那么,Spring提供了一个很方便的去收发消息的框架,spring jms.整合 ...
- spring IOC装配Bean(注解方式)
1 Spring的注解装配Bean (1) Spring2.5 引入使用注解去定义Bean @Component 描述Spring框架中Bean (2) Spring的框架中提供了与@Componen ...
- Shiro启用注解方式
shiro验证权限方式一种是基于url配置文件: 例如: <bean id="shiroFilter" class="org.apache.shiro.spring ...
随机推荐
- 给大家推荐一个好的android模拟器genymotion,非常流畅,跟真机差不多
http://www.genymotion.cn/这里是下载地址, 下载的时候会要求输入邮箱并注册,这个邮箱尽量用网易这类的邮箱,我试过qq邮箱无法收到验证邮件, 程序下载安装完成后,打开客户端选择设 ...
- [SQL] 常用查询脚本
查询哪些存储过程使用了某个表 select b.name from syscomments a,sysobjects b where a.id=b.id and a.text LIKE '%ftblo ...
- 【 Android】使手机屏幕常亮,不进入待机状态
Android中,申请WakeLock可以让你的进程持续执行即使手机进入睡眠模式,比较实用的是比如后台有网络功能,可以保证操作持续进行. 需要权限 <uses-permission androi ...
- java如何使用base64生成图片文件
import org.apache.commons.codec.binary.Base64; public static void decodeFile(String base64Str,File f ...
- angularJS中的ng-repeat指令!
ng-repeat 指令: ng-repeat 指令用来遍历一个数组重复创建当前元素: <ul ng-app="myApp" ng-controller="myAp ...
- python安装whl文件的注意事项(windows系统)
首先给大家来一波福利,在没有连接外网(互联网)的情况下,只有公司内网或者断网情况下,需要安装python的一些依赖,不会操作的同学可能就会遇到麻烦.这里教大家离线安装python依赖. 方法:使用.w ...
- Python3、Unicode、UTF-8、编码
text = u'你好,今天天气不错' text print(text) text = '\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519' ...
- Python开发【笔记】:为什么pymysql重连后才能查到新添加的数据
PyMysql操控 问题描述: 之前做数据库模块的时候用到了pymysql,测试中发现了一个问题,创建两个程序,select.py从数据库中不断的读取,insert.py在数据库中插入多条数据,但是s ...
- Day01 html详解
day01 html详解 1.html的简介 1.1 什么是html? - HyperText Markup Language:超文本标记语言,网页语言 ...
- git-【十】忽略文件
1.在Git工作区的根目录下创建一个特殊的.gitignore文件,然后把要忽略的文件名填进去,Git就会自动忽略这些文件. 不需要从头写.gitignore文件,GitHub已经为我们准备了各种配置 ...