SpringSecurity学习三----------通过Security标签库简单显示视图
© 版权声明:本文为博主原创文章,转载请注明出处
1.项目结构
2.pom.xml
<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>org.springsecurity</groupId>
<artifactId>SpringSecurity</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringSecurity Maven Webapp</name>
<url>http://maven.apache.org</url> <!-- 统一版本 -->
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>4.3.5.RELEASE</spring.version>
<spring.security.version>4.2.1.RELEASE</spring.security.version>
</properties> <dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring依赖 -->
<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>
<!-- 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>
<!-- SpringSecurity标签库依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jsp、servlet依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringSecurity</finalName>
</build>
</project>
3.mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启包扫描 -->
<context:component-scan base-package="org.springsecurity.*"/> <!-- 定义视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
4.spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd"> <security:http auto-config="true">
<!-- 指定需要拦截的URL,并设置访问所需的角色 -->
<security:intercept-url pattern="/"
access="hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')"/>
<!-- 测试中发现SpringSecurity会自动在角色名称前加上ROLE_。即ROLE_USER == USER -->
<security:intercept-url pattern="/home**"
access="hasRole('USER') or hasRole('ADMIN')or hasRole('DBA')"/>
<!-- login-page:跳转到登录界面的请求名称
default-target-url:指定身份验证通过后默认执行的请求名称
authentication-failure-url:如果验证失败,则转向URL
username-parameter:表示登录时用户使用的是哪个参数,即用户名输入框的name
password-parameter:表示登录时密码使用的是哪个参数,即密码输入框的name
-->
<security:form-login login-page="/login" default-target-url="/home"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password"/>
<!-- 开启csrf,在登录或注销页面都必须包含_csrf.token -->
<security:csrf/>
</security:http> <security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<!-- 设置用户的密码和角色,authorities指定角色必须加上ROLE_,否则会报错403:Access is denied -->
<security:user name="admin" password="123456" authorities="ROLE_ADMIN" />
<security:user name="user" password="123456" authorities="ROLE_USER" />
<security:user name="dba" password="123456" authorities="ROLE_DBA" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager> </beans>
5.web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true"> <!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 加载spring-security配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</context-param> <!-- 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> </web-app>
6.HelloController.java
package org.springsecurity.controller; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController { @RequestMapping(value = {"/", "/home**"}, method = RequestMethod.GET)
public ModelAndView welcomePage() { ModelAndView model = new ModelAndView();
model.addObject("user", getPrincipal());
model.setViewName("success");
return model; } @RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView();
if(error != null){
model.addObject("error", "违法的用户名或密码!");
}
if(logout != null){
model.addObject("msg", "您已成功注销!");
}
model.setViewName("login");
return model; } private String getPrincipal() { String username = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(principal instanceof UserDetails) {
username = ((UserDetails) principal).getUsername();
} else {
username = principal.toString();
}
return username; } }
7.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body onload="focus()">
<h1>Spring Security 自定义登录界面</h1>
<div id="login-box">
<c:if test="${not empty error }">
<div class="error"><font color="red">${error }</font><br/><br/></div>
</c:if>
<c:if test="${not empty msg }">
<div class="msg"><font color="red">${msg }</font><br/><br/></div>
</c:if>
<!-- SpringSecurity3.x默认的登录拦截URL是/j_spring_security_check;
4.x默认的登录拦截URL是/login -->
<form name="loginForm" action="<c:url value='/login'/>" method="POST">
<table>
<tr>
<td>用户名:</td>
<!-- name必须与spring-security.xml中配置的username-parameter一致,否则登录认证会失败 -->
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密码:</td>
<!-- name必须与spring-security.xml中配置的password-parameter一致,否则登录认证会失败 -->
<td><input type="password" name="password"></td>
</tr>
<tr style="text-align: center;" >
<td colspan="2">
<input type="reset" value="重置"/>
<input type="submit" value="登录"/>
</td>
</tr>
</table>
<!-- 开启csrf后必须包含_csrf.token,否则报错:
403 Could not verify the provided CSRF token because your session was not found -->
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/>
</form>
</div>
</body>
<script type="text/javascript"> function focus(){//设置加载时鼠标焦点 document.loginForm.username.focus(); } </script>
</html>
8.success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to Home Page.
<a href="javascript:formSubmit()">Logout</a> <!-- 隐藏域,用于提交注销请求 -->
<c:url value="/logout" var="logoutUrl"/>
<!-- 假设注销请求是*,若*=logout(即等于默认的注销拦截URL),则实际请求是/login?logout
若*!=logout,则实际请求是/*。具体原因未知。。 -->
<form action="${logoutUrl }" method="POST" id="logoutForm">
<!-- 开启csrf后必须包含_csrf.token,否则报错:
403 Could not verify the provided CSRF token because your session was not found -->
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }">
</form> <br/><br/>
This part is visible to Everyone.
<sec:authorize access="hasRole('USER')"><!-- USER角色专有 -->
This part is visible to <font color="red">USER</font>.
</sec:authorize>
<sec:authorize access="hasRole('ADMIN')"><!-- ADMIN角色专有 -->
This part is visible to <font color="red">ADMIN</font>.
</sec:authorize>
<sec:authorize access="hasRole('DBA')"><!-- DBA角色专有 -->
This part is visible to <font color="red">DBA</font>.
</sec:authorize>
</body>
<script type="text/javascript"> function formSubmit(){//提交注销请求表单 document.getElementById("logoutForm").submit(); } </script>
</html>
9.效果预览
9.1 登录界面
9.2 ADMIN角色登录
9.3 DBA角色登录
9.4 USER角色登录
参考:http://www.yiibai.com/spring-security/spring-security-4-secure-view-layer-using-taglibs.html
SpringSecurity学习三----------通过Security标签库简单显示视图的更多相关文章
- JavaWeb学习之JSTL自定义标签库的使用、JSTL自定义函数库(7)
一.自定义标签,步骤 * 确定需求 * <my:date /> 输出当前系统的时间 yyyy-MM-dd hh:mm:ss:SSS * 编写Java类 新建包名:com.yxl.tag,新 ...
- java_web学习(五) JSTL标准标签库
1.什么是JSTL JSP标准标签库(JSTL)是一个JSP标签集合,它封装了JSP应用的通用核心功能. JSTL支持通用的.结构化的任务,比如迭代,条件判断,XML文档操作,国际化标签,SQL标签. ...
- 学习笔记_Java_day13_JSTL_自定义标签库(9)
自定义标签 1 自定义标签概述 1.1 自定义标签的步骤 其实我们在JSP页面中使用标签就等于调用某个对象的某个方法一样,例如:<c:if test=””>,这就是在调用对象的方法一样.自 ...
- python爬虫学习(三):使用re库爬取"淘宝商品",并把结果写进txt文件
第二个例子是使用requests库+re库爬取淘宝搜索商品页面的商品信息 (1)分析网页源码 打开淘宝,输入关键字“python”,然后搜索,显示如下搜索结果 从url连接中可以得到搜索商品的关键字是 ...
- Python爬虫学习三------requests+BeautifulSoup爬取简单网页
第一次第一次用MarkDown来写博客,先试试效果吧! 昨天2018俄罗斯世界杯拉开了大幕,作为一个伪球迷,当然也得为世界杯做出一点贡献啦. 于是今天就编写了一个爬虫程序将腾讯新闻下世界杯专题的相关新 ...
- JavaWeb学习笔记——JSTL核心标签库
- JavaWeb学习笔记——JSP标准标签库JSTL
- javaweb学习总结(二十八)——JSTL标签库之核心标签
一.JSTL标签库介绍 JSTL标签库的使用是为弥补html标签的不足,规范自定义标签的使用而诞生的.使用JSLT标签的目的就是不希望在jsp页面中出现java逻辑代码 二.JSTL标签库的分类 核心 ...
- javaWeb学习总结(9)- JSTL标签库之核心标签
一.JSTL标签库介绍 JSTL标签库的使用是为弥补html标签的不足,规范自定义标签的使用而诞生的.使用JSLT标签的目的就是不希望在jsp页面中出现java逻辑代码 二.JSTL标签库的分类 核心 ...
随机推荐
- selenium IE自动化问题汇总
驱动下载:http://selenium-release.storage.googleapis.com/index.html 没有修改IE的保护模式设置导致,通常看到报错信息如下: selenium. ...
- hashmap hashtable
作者:付佳豪链接:https://zhuanlan.zhihu.com/p/37607299来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 在面试的时候,java集合最 ...
- Uva 11077 Find the Permutation
可以发现最优的方案就是一个循环节内互换. 所以一个有n个元素,c个循环节的置换的交换次数(最少)是n-c. 然后就可以递推了,把i插入到前i-1个元素构成的置换中,要么新成立一个循环,要么加入到之前的 ...
- POJ 1769 Minimizing maximizer(DP+zkw线段树)
[题目链接] http://poj.org/problem?id=1769 [题目大意] 给出一些排序器,能够将区间li到ri进行排序,排序器按一定顺序摆放 问在排序器顺序不变的情况下,一定能够将最大 ...
- .xcodeprok cannot be opened because the project file cannot be parsed
用svn更新代码后,打开xcode工程文件出现 xxx..xcodeproj cannot be opened because the project file cannot be parsed. 这 ...
- 几个有用的PHP.ini配置项-路径和目录
几个有用的PHP.ini配置项-路径和目录 路径和目录1.include_path = string作用域:PHP_INI_ALL默认值:NULL此参数指定的路径是include().require( ...
- ASIHTTPRequest学习(三)
刚刚开始学习ASIHttpRequest,今天通过自己写的一个小demo分享一下学习心得. 首先,要想在ios项目中使用ASIHttpRequest,必须添加下列框架和类库: ASIHttpReque ...
- androd 获得wifi列表
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xm ...
- 【微信】微信小程序 微信开发工具中新创建的json文件,编译报错VM1781:2 pages/module/module.json 文件解析错误 SyntaxError: Unexpected end of JSON input
如果新创建报错:编译报错VM1781:2 pages/module/module.json 文件解析错误 SyntaxError: Unexpected end of JSON input 解决方法 ...
- 获得Oracle当前日期的年或月的第一天和最后一天
.当前日期的年份第一天和最后一天 第一天 select trunc(sysdate,'y') FROM DUAL; select trunc(sysdate,'yy') FROM DUAL; sele ...