© 版权声明:本文为博主原创文章,转载请注明出处

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标签库简单显示视图的更多相关文章

  1. JavaWeb学习之JSTL自定义标签库的使用、JSTL自定义函数库(7)

    一.自定义标签,步骤 * 确定需求 * <my:date /> 输出当前系统的时间 yyyy-MM-dd hh:mm:ss:SSS * 编写Java类 新建包名:com.yxl.tag,新 ...

  2. java_web学习(五) JSTL标准标签库

    1.什么是JSTL JSP标准标签库(JSTL)是一个JSP标签集合,它封装了JSP应用的通用核心功能. JSTL支持通用的.结构化的任务,比如迭代,条件判断,XML文档操作,国际化标签,SQL标签. ...

  3. 学习笔记_Java_day13_JSTL_自定义标签库(9)

    自定义标签 1 自定义标签概述 1.1 自定义标签的步骤 其实我们在JSP页面中使用标签就等于调用某个对象的某个方法一样,例如:<c:if test=””>,这就是在调用对象的方法一样.自 ...

  4. python爬虫学习(三):使用re库爬取"淘宝商品",并把结果写进txt文件

    第二个例子是使用requests库+re库爬取淘宝搜索商品页面的商品信息 (1)分析网页源码 打开淘宝,输入关键字“python”,然后搜索,显示如下搜索结果 从url连接中可以得到搜索商品的关键字是 ...

  5. Python爬虫学习三------requests+BeautifulSoup爬取简单网页

    第一次第一次用MarkDown来写博客,先试试效果吧! 昨天2018俄罗斯世界杯拉开了大幕,作为一个伪球迷,当然也得为世界杯做出一点贡献啦. 于是今天就编写了一个爬虫程序将腾讯新闻下世界杯专题的相关新 ...

  6. JavaWeb学习笔记——JSTL核心标签库

  7. JavaWeb学习笔记——JSP标准标签库JSTL

  8. javaweb学习总结(二十八)——JSTL标签库之核心标签

    一.JSTL标签库介绍 JSTL标签库的使用是为弥补html标签的不足,规范自定义标签的使用而诞生的.使用JSLT标签的目的就是不希望在jsp页面中出现java逻辑代码 二.JSTL标签库的分类 核心 ...

  9. javaWeb学习总结(9)- JSTL标签库之核心标签

    一.JSTL标签库介绍 JSTL标签库的使用是为弥补html标签的不足,规范自定义标签的使用而诞生的.使用JSLT标签的目的就是不希望在jsp页面中出现java逻辑代码 二.JSTL标签库的分类 核心 ...

随机推荐

  1. 使用overtrue/socialite实现第三方登陆

    composer下载包 将申请的配置内容放在.ENV文件中 在services.php文件中引用 控制器 其他第三方登陆同理,拿到client_id,client_secret 和redirect_u ...

  2. 51nod 1649.齐头并进-最短路(Dijkstra)

    1649 齐头并进 题目来源: CodeForces 基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题 在一个叫奥斯汀的城市,有n个小镇(从1到n编号),这些小镇通过 ...

  3. NYOJ16 矩形嵌套 【DAG上的DP/LIS】

    矩形嵌套 时间限制:3000 ms | 内存限制:65535 KB 难度:4 描述 有n个矩形,每个矩形可以用a,b来描述,表示长和宽.矩形X(a,b)可以嵌套在矩形Y(c,d)中当且仅当a<c ...

  4. Python_Tips[3] -> sort/sorted 排序函数

    排序函数 / Sort Function list自带的sort函数可以实现对列表的排列功能,具有同样功能的还有sorted函数. 基本形式 列表有自己的sort方法,其对列表进行原址排序,既然是原址 ...

  5. 四. Java继承和多态6. 多态对象的类型转换

    这里所说的对象类型转换,是指存在继承关系的对象,不是任意类型的对象.当对不存在继承关系的对象进行强制类型转换时,java 运行时将抛出 java.lang.ClassCastException 异常. ...

  6. Android Developer -- Bluetooth篇 开发实例之一 扫描设备

    第一步:声明Bluetooth Permissions <!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.p ...

  7. JavaScript的filter用法

    Js的有些操作会改变原来的对象:有些操作则不会改变原来对象. 数组的filter方法就不会改变原来数组 利用filter,可以巧妙地去除Array的重复元素: 'use strict'; var r, ...

  8. 安装Webmin1.860(RPM方式)

    Webmin是基于web的功能强大的管理工具,管理员可以通过Webmin以图文方式方便的管理CentOS 7系统.本文介绍如何在CentOS 7中安装Webmin. 1.去官网获取最新的RPM链接 2 ...

  9. python 常用的模块(collections)转

    collections是Python内建的一个集合模块,提供了许多有用的集合类. namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: >>> ...

  10. github 丢失的本地提交

    open git bash git reflog git reset xxxxxxx