手把手教你整合maven+spring项目(3)

 在上一篇博客里我们讲解了如何用maven项目整合Springmvc,今天我们将围绕Spring Security 来介绍,Spring Security 提供了基于javaEE的企业应用软件全面的安全服务,如果你的项目对于安全和访问要求比较高,强烈轻易你在项目中使用Spring Security模块,这里是Spring Security的中文官网介绍https://springcloud.cc/spring-security-zhcn.html,下面我们就通过一个登录注销功能来揭开Spring Security的面纱,项目代码在上一篇博客的基础上实现。

第一步:修改pom.xml配置添加Spring Security所需要的核心jar包spring-security-web和spring-security-config,这里博主使用的是3.2.3的版本号。




	4.0.0

	com.zds
	MavenDemo
	0.0.1-SNAPSHOT
	war

	MavenDemo Maven Webapp
	http://maven.apache.org

	
		UTF-8
		1.7
		1.7
	

	
		
			junit
			junit
			4.11
			test
		
		
			javax
			javaee-api
			7.0
			provided
		
		
			jstl
			jstl
			1.2
		

		
			org.springframework
			spring-webmvc
			4.1.6.RELEASE
			jar
			compile
		
		
			org.springframework
			spring-core
			4.1.6.RELEASE
		
		
			org.springframework
			spring-context
			4.1.6.RELEASE
		
		
			org.springframework.security
			spring-security-web
			3.2.3.RELEASE
		
		
			org.springframework.security
			spring-security-config
			3.2.3.RELEASE
		
		
			org.springframework
			spring-tx
			4.1.6.RELEASE
		
		
			org.springframework
			spring-jdbc
			4.1.6.RELEASE
		
		
			org.springframework
			spring-context-support
			4.1.6.RELEASE
		
		
			log4j
			log4j
			1.2.15
			
				
					javax.jms
					jms
				
				
					com.sun.jdmk
					jmxtools
				
				
					com.sun.jmx
					jmxri
				
			
		
	

配置好pom.xml后,保存修改,然后在src/main/resources目录下添加spring-security.xml,具体配置如下


	
	    
	    
	    
		
		
		
		
		
	
	
	 
	  
	    
		
		
	    
	  
	 

简单的介绍一下,Login-page对应的是后台的登陆方法,default-target-url对应的是登陆成功后跳转的地方,authentication-falure-url对应的事登陆失败(如账号或密码错误)后跳转的地方。然后我们就可以修改Index.jsp,添加一个跳转向登陆页面的超链接(当然Index页面可有可无,这里为了利用之前写好的index页面),具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


点击登录账号
 this is mavendemo 第一天 


然后我们需要在后台的LoginController.java里添加对应的login方法来跳转到login.jsp,
@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.addObject("title", "Spring Security Hello World");
			model.addObject("message", "This is login page!");
			model.setViewName("login");
		return model;
	}

添加完毕后,需要在WEB-INF的jsp文件夹下新建一个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"%>




${title}




Login with Username and Password

${error}
${msg}
账号:
密码:
输入登陆信息后,spring security用对输入的账号和密码对之前spring-security.xml里所配置的用户信息进行匹配,如果账号和密码都对,则跳转到xml里default-target-url对应的请求,如果失败,则跳转到authentication-failure-url对应的请求,当然xml里的用户信息我们也可以从数据库中获取,具体的java实现方式我们将在下一篇博客里介绍。登陆成功后请求转发到了/welcome,所以我们需要在LoginController.java里添加welcome方法:
@RequestMapping("/welcome")
	public ModelAndView demo(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		
		String contextPath = request.getContextPath();
		mav.addObject("contextPath" , contextPath);
		mav.addObject("title", "Spring Security Hello World");
		mav.addObject("message", "This is welcome page!");
		mav.setViewName("welcome");
		return mav;
	}

然后在WEB-INF的jsp文件夹下新建一个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"%>
<%@page session="true"%>





标题: ${title}

消息 : ${message}

Welcome : ${pageContext.request.userPrincipal.name} | Logout注销

pageContext.request.userPrincipal.name表示登陆用户的名字,之前index.jsp里的查看图片功能我们放在了welcome.jsp里,这就实现了对资源的保护,不登录不能访问这些资源,最后就是注销功能,对应的是LoginController.java里的logout方法,具体代码如下:
@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";
	}
这是比较符合spring规范的注销操作,注销调用执行以下操作:
  • HTTP的会话失效,那么解除绑定到它的任何对象;
  • 将删除 SecurityContext 的身份验证,以防止并发请求的问题;
  • 显式地清除当前线程上下文值;
就这样,不需要在应用程序中的任何其他地方处理注销,注销信息后重定向到了登陆页面,并提示用户已注销成功。LoginController.java的完整版代码如下:
package com.zds.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.web.authentication.logout.SecurityContextLogoutHandler;
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 LoginController {
	
	@RequestMapping("/view")
	public ModelAndView view(HttpServletRequest request){
		//获取请求中的path参数
		String path = request.getParameter("path") + "";
		//新建视图变量
		ModelAndView mav = new ModelAndView();
		//获取web项目的根路径,方便我们取到Img下的图片
		String contextPath = request.getContextPath();
		//保存路径到内存中
		mav.addObject("contextPath" , contextPath);
		//设置跳转的页面名称
		mav.setViewName(path);
		return mav;
	}
	@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.addObject("title", "Spring Security Hello World");
			model.addObject("message", "This is login page!");
			model.setViewName("login");
		return model;
	}
	@RequestMapping("/welcome")
	public ModelAndView demo(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		
		String contextPath = request.getContextPath();
		mav.addObject("contextPath" , contextPath);
		mav.addObject("title", "Spring Security Hello World");
		mav.addObject("message", "This is welcome page!");
		mav.setViewName("welcome");
		return mav;
	}
	@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";
	}
}

第二步:启动tomcat运行项目,浏览器输入http://localhost:8080/MavenDemo/显示页面如下手把手教你整合maven+spring项目(3)_第1张图片

点击登陆账号,跳转页面如下:

手把手教你整合maven+spring项目(3)_第2张图片

登陆成功后welcome页面如下:

手把手教你整合maven+spring项目(3)_第3张图片

点击注销(即退出登陆)显示页面如下:

手把手教你整合maven+spring项目(3)_第4张图片

好了,到目前为止,Spring Security登录注销功能已介绍完了,在下一篇博客里我们将介绍如何用java代码实现数据库用户信息的获取,这样就不必在xml里配置用户信息了,如何对密码进行md5加密验证等等。


你可能感兴趣的:(Spring,Security,maven)