采用注解方式实现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 ...
随机推荐
- Java 去除List列表中的重复项
/** * Remove list duplicate item * * @param srcList * @return */ private static ArrayList<Resolve ...
- mysql如何查询当前周的第一天的日期?
转自:http://blog.csdn.net/zzhongcy/article/details/43016685 select date_sub(curdate(),INTERVAL WEEKDAY ...
- 查询hadoop参数变量
[hadoop@master hadoop]$ hive -S -e 'set -v'|grep querylog|grep -E -v 'CLASSPATH|class'hive.querylog. ...
- loadrunner多场景的串行执行以及定时执行
方法一: 既然是脚本串行执行,那在场景设计中必然是要用多个脚本,要注意的是需要将Scenario Schedule中的Schedule by设置为Group的模式.然后按实际需要依次设置每个脚本的Sc ...
- Cisco配置发送日志到日志服务器
Cisco配置发送日志到日志服务器logging 172.16.6.22logging onlogging trap 7 //指定日志消息的级别 (0:紧急(Emergencies) 1:告警(Al ...
- 过山车---hdu2063(最大匹配)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2063最大匹配模板题: #include <iostream> #include <c ...
- IT运营新世界大会:广通软件开启双态运维大时代
10月28日,第一届“IT运营新世界大会”在北京成功举办.大会上由10家ITOM领域的标杆企业宣布结成“ITOM联盟”. 广通软件(证券代码:833322)作为大会的创始成员全程推动见证了这一历史时刻 ...
- mysql 数据操作 单表查询 concat_ws() 定义显示格式
有个需求用concat以这种格式打印查询 mysql> select concat(name,':',age) from employee; +----------------------+ | ...
- .NET、NET Framewor以及.NET Core的关系(二)
什么是CLR,.NET虚拟机? 实际上,.NET不仅提供了自动内存管理的支持,他还提供了一些列的如类型安全.应用程序域.异常机制等支持,这些 都被统称为CLR公共语言运行库. CLR是.NET类型系统 ...
- Myeclipse文档注释如何提炼(导出)成自己的API帮助文档?
第一步: 源码注释规范,一定要用/** 两个*这一特殊的注释.注释上可以添加@author等特殊说明,下图是部分 javadoc 标记 信息,可以根据需要选用. 第二步: 确保整个工程的项目都添加 ...