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

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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 开启包扫描 -->
<context:component-scan base-package="org.springsecurity.*"/> <!-- 不拦截静态资源 -->
<mvc:annotation-driven/>
<mvc:resources location="/static/" mapping="/static/**"/> <!-- 定义视图解析器 -->
<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.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>

5.CustomSuccessHandler.java

 package org.springsecurity.configuration;

 import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component; @Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /**
* 重定向登录成功后的URL
*/
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException { String targetUrl = determineTargetUrl(authentication);
if(response.isCommitted()) {
System.out.println("重定向失败!");
return ;
}
redirectStrategy.sendRedirect(request, response, targetUrl); } /**
* 根据用户角色给定URL
*
* @param authentication
* 用户权限信息
* @return
*/
private String determineTargetUrl(Authentication authentication) { String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for(GrantedAuthority a: authorities) {
roles.add(a.getAuthority());
}
if(isDba(roles)) {
url = "/dba";
} else if(isAdmin(roles)) {
url = "/admin";
} else if(isUser(roles)) {
url = "/home";
} else {
url = "accessDenied";
}
return url; } /**
* 判断是否具有USER角色
*
* @param roles
* 角色列表
* @return
*/
private boolean isUser(List<String> roles) { if(roles.contains("ROLE_USER")) {
return true;
}
return false; } /**
* 判断是否具有ADMIN角色
*
* @param roles
* 角色列表
* @return
*/
private boolean isAdmin(List<String> roles) { if(roles.contains("ROLE_ADMIN")) {
return true;
}
return false; } /**
* 判断是否具有DBA权限
*
* @param roles
* 角色列表
* @return
*/
private boolean isDba(List<String> roles) { if(roles.contains("ROLE_DBA")) {
return true;
}
return false; } public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
} public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
} }

6.HelloController.java

 package org.springsecurity.controller;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
public class HelloController { @RequestMapping(value = {"/", "/home**"}, method = RequestMethod.GET)
public String homePage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "welcome"; } @RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "admin"; } @RequestMapping(value = "/dba", method = RequestMethod.GET)
public String dbaPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "dba"; } @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) { model.addAttribute("user", getPrincipal());
return "accessDenied"; } @RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() { return "login"; } @RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout"; } 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>登录界面</title>
<link href="<c:url value='/static/css/bootstrap.css'/>" rel="stylesheet" />
<link href="<c:url value='/static/css/app.css'/>" rel="stylesheet" />
<link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
</head>
<body>
<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<div class="login-form">
<c:url value="/login" var="loginUrl"/>
<form action="${loginUrl }" method="post" class="form-horizontal">
<c:if test="${param.error != null }">
<div class="alert alert-danger">
<p>用户名或密码错误</p>
</div>
</c:if>
<c:if test="${param.logout != null }">
<div class="alert alert-success">
<p>注销成功</p>
</div>
</c:if>
<div class="input-group input-sm" style="padding-bottom: 10px;">
<label class="input-group-addon" for="username">
<i class="fa fa-user"></i>
</label>
<input type="text" class="form-control" id="username" name="username"
placeholder="请输入用户名" required>
</div>
<div class="input-group input-sm" style="padding-bottom: 10px;">
<label class="input-group-addon" for="username">
<i class="fa fa-lock"></i>
</label>
<input type="password" class="form-control" id="password" name="password"
placeholder="请输入密码" required>
</div>
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/>
<div class="form-actions">
<input type="submit" value="登录"
class="btn btn-block btn-primary btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

8.app.css

 html {
backgroud-color: #2F2F2F;
} body, #mainWrapper {
height: 100%;
} body, #mainWrapper, .form-control {
font-size: 14px!important;
} #mainWrapper {
height: 100%;
padding-left: 10px;
padding-right: 10px;
padding-bottom: 10px;
} #authHeaderWrapper {
clear: both;
width: 100%;
height: 3%;
padding-top: 5px;
padding-bottom: 5px;
} .login-container {
margin-top: 100px;
background-color: floralwhite;
width: 40%;
left: 30%;
position: absolute;
} .login-card {
width: 80%;
margin: auto;
} .login-form {
padding: 10%;
}

9.bootstrap.css(bootstrap官网下载即可)

10.admin.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>Admin page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to Admin Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>

11.dba.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>Dba page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to DBA Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>

12.welcome.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>Welcome page</title>
</head>
<body>
Dear <strong>${user }</strong>, Welcome to Welcome Page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>

13.accessDenied.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>AccessDenied page</title>
</head>
<body>
Dear <strong>${user }</strong>, You are not authorized to access this page.
<a href="<c:url value='/logout'/>">Logout</a>
</body>
</html>

14.效果预览

  14.1 登录界面

  

  14.2 登录失败

  

  14.3 admin登录

  

  14.4 dba登录

  

  14.4 user登录

  

  14.4 user登录后,通过url访问admin

  

  14.5 注销

  

  参考:http://www.yiibai.com/spring-security/spring-security-4-role-based-login-example.html

SpringSecurity学习四----------基于不同角色跳转到不同URL的更多相关文章

  1. SpringSecurity学习之基于数据库的用户认证

    SpringSecurity给我们提供了一套最基本的认证方式,可是这种方式远远不能满足大多数系统的需求.不过好在SpringSecurity给我们预留了许多可扩展的接口给我们,我们可以基于这些接口实现 ...

  2. TCP/IP协议学习(四) 基于C# Socket的Web服务器---静态资源处理

    目录 1. C# Socket通讯 2. HTTP 解析引擎 3. 资源读取和返回 4. 服务器测试和代码下载 Web服务器是Web资源的宿主,它需要处理用户端浏览器的请求,并指定对应的Web资源返回 ...

  3. {django模型层(二)多表操作}一 创建模型 二 添加表记录 三 基于对象的跨表查询 四 基于双下划线的跨表查询 五 聚合查询、分组查询、F查询和Q查询

    Django基础五之django模型层(二)多表操作 本节目录 一 创建模型 二 添加表记录 三 基于对象的跨表查询 四 基于双下划线的跨表查询 五 聚合查询.分组查询.F查询和Q查询 六 xxx 七 ...

  4. Android JNI学习(四)——JNI的常用方法的中文API

    本系列文章如下: Android JNI(一)——NDK与JNI基础 Android JNI学习(二)——实战JNI之“hello world” Android JNI学习(三)——Java与Nati ...

  5. SpringSecurity学习三----------通过Security标签库简单显示视图

    © 版权声明:本文为博主原创文章,转载请注明出处 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0& ...

  6. day 83 Vue学习四之过滤器、钩子函数、路由、全家桶等

    Vue学习四之过滤器.钩子函数.路由.全家桶等   本节目录 一 vue过滤器 二 生命周期的钩子函数 三 vue的全家桶 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 Vue的过滤 ...

  7. Python基础学习四

    Python基础学习四 1.内置函数 help()函数:用于查看内置函数的用途. help(abs) isinstance()函数:用于判断变量类型. isinstance(x,(int,float) ...

  8. jsp九大内置对象、四种作用域、跳转方式

    jsp有四种属性范围: page -> 页面级别,显然只有在一个页面内可用. request -> 请求级别 服务器跳转,一次请求之后消失. session -> 会话级别 客户端跳 ...

  9. struts2 Result Type四个常用转跳类型

    Result的四个常用转跳类型分别为 Dispatcher 用来转向页面,是Struts的默认形式 Redirect   重定向到一个URL Chain  用来处理Action链 RedirectAc ...

随机推荐

  1. JAVA SERVLET 属性范围样例

    package com.jeelearning.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; ...

  2. CF985A Chess Placing【思维】

    [链接]:CF985A [题意]:给你n和n/2个数ai,每个ai和奇数.偶数比较距离(注意选了奇数,偶数的距离就不要算了,反之同理),求最小的答案. [代码]: #include <iostr ...

  3. uva10857(状态压缩DP)

    uva10857 题意 兔子希望在平面上 n 个点上放蛋,每个点最多放一个蛋,初始兔子在 (0, 0) 点,这里有无数个蛋,兔子可以回到这个点取蛋,兔子的速度为 \(v * 2^{-i}\)(i 为携 ...

  4. APP专项测试 | 内存及cpu

    命令: adb shell dumpsys meminfo  packagename 关注点: 1.Native/Dalvik 的 Heap 信息 具体在上面的第一行和第二行,它分别给出的是JNI层和 ...

  5. JD2

    Business Requirement Support l Develops and communicates plan to manage vendor review of requirement ...

  6. 为添加了自定义域名的GitHub Pages添加SSL,启用强制HTTPS(小绿锁)

    直奔主题 为什么要使用https协议? 提高网站访问安全性,网络连接都是加密的 (PS:虽然SSL并不是无懈可击的,但是我们应该尽可能提高窃听成本). 目前越来越多的浏览器会判断当前站点支不支持htt ...

  7. command for ContextMenu in DataTemplate

    准备教程. 1. 无难度方式 <DataTemplate x:Key="DataTemplate1"> <StackPanel  > <toolkit ...

  8. [给自己扫盲]Node.js 究竟是什么?

    Node.js 究竟是什么? 一个 “编码就绪” 服务器 Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编写能 ...

  9. mysql 的常用查询

    Ø 基本常用查询 --select select * from student;   --all 查询所有 select all sex from student;   --distinct 过滤重复 ...

  10. hdu2846 Repository

    //--------------------------------------------------------------- /*---字典树应用问题.考虑到要查询的次数在10^6,显然直接插入 ...