拦截器实现用户权限验证

 代码:

loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




登录页面


登录页面

${requestScope.message }

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>




首页



欢迎[${sessionScope.user.username }]访问


封面书名作者价格
${book.name } ${book.author } ${book.price }
Book.java

package com.bean;

import java.io.Serializable;

public class Book implements Serializable {
	private Integer id;				// id	
	private String name;			// 书名
	private String author;			// 作者
	private Double price;			// 价格
	private String image;			// 封面图片
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Book( String image,String name, String author, Double price) {
		super();
		this.image = image;
		this.name = name;
		this.author = author;
		this.price = price;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "Book [id=" + id + ", name=" + name + ", author=" + author + ", price=" + price + ", image=" + image + "]";
	}

}

User.java

package com.bean;

import java.io.Serializable;

public class User implements Serializable {
	private Integer id;			// id
	private String loginname;	// 登录名
	private String password;	// 密码
	private String username;	// 用户名
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "User [id=" + id + ", loginname=" + loginname + ", password=" + password + ", username=" + username + "]";
	}
	
	
}

AuthorizationInterceptor.java

package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bean.*;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/* 
 *  拦截器必须实现HandlerInterceptor接口
 */ 
public class AuthorizationInterceptor  implements HandlerInterceptor {

	// 不拦截"/loginForm"和"/login"请求
	private static final String[] IGNORE_URI = {"/loginForm", "/login"};
	
	 /* 
     * 该方法将在整个请求完成之后执行, 主要作用是用于清理资源的,
     * 该方法也只能在当前Interceptor的preHandle方法的返回值为true时才会执行。 
     */  
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception)
			throws Exception {
		System.out.println("AuthorizationInterceptor afterCompletion --> ");
		
	}
	/* 
     * 该方法将在Controller的方法调用之后执行, 方法中可以对ModelAndView进行操作 ,
     * 该方法也只能在当前Interceptor的preHandle方法的返回值为true时才会执行。 
     */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView mv) throws Exception {
		System.out.println("AuthorizationInterceptor postHandle --> ");
		
	}

	 /* 
     * preHandle方法是进行处理器拦截用的,该方法将在Controller处理之前进行调用,
     * 该方法的返回值为true拦截器才会继续往下执行,该方法的返回值为false的时候整个请求就结束了。 
     */  
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
		System.out.println("AuthorizationInterceptor preHandle --> ");
		// flag变量用于判断用户是否登录,默认为false 
		boolean flag = false; 
		//获取请求的路径进行判断
		String servletPath = request.getServletPath();
		// 判断请求是否需要拦截
        for (String s : IGNORE_URI) {
            if (servletPath.contains(s)) {
                flag = true;
                break;
            }
        }
        // 拦截请求
        if (!flag){
        	// 1.获取session中的用户 
        	User user = (User) request.getSession().getAttribute("user");
        	// 2.判断用户是否已经登录 
        	if(user == null){
        		// 如果用户没有登录,则设置提示信息,跳转到登录页面
        		 System.out.println("AuthorizationInterceptor拦截请求:");
        		 request.setAttribute("message", "请先登录再访问网站");
        		 request.getRequestDispatcher("loginForm").forward(request, response);
        	}
        	else{
        		// 如果用户已经登录,则验证通过,放行
        		 System.out.println("AuthorizationInterceptor放行请求:");
        		 flag = true;
        	}
        }
        return flag;
		
	}

}

FormController.java

package com.control;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/*
 * 动态页面跳转控制器
 */
@Controller
public class FormController{

	@RequestMapping(value="/{formName}")
	 public String loginForm(@PathVariable String formName){
		// 动态跳转页面
		return formName;
	}
}

UserController.java

package com.control;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bean.User;

/*
 * 处理用户请求控制器
 */
@Controller
public class UserController {
/*
 * 处理/login请求
 */
	@RequestMapping(value="/login")
	public ModelAndView login(String loginname,String password,ModelAndView mv, HttpSession session){
		// 模拟数据库根据登录名和密码查找用户,判断用户登录
		if(loginname != null && loginname.equals("haige") && password!= null && password.equals("123456")){
			// 模拟创建用户
			User user = new User();
			user.setLoginname(loginname);
			user.setPassword(password);
			user.setUsername("管理员");
			// 登录成功,将user对象设置到HttpSession作用范围域
			session.setAttribute("user", user);
			// 转发到main请求
			mv.setViewName("redirect:main");
		}
		else{
			// 登录失败,设置失败提示信息,并跳转到登录页面
			mv.addObject("message", "登录名或密码错误,请重新输入!");
			mv.setViewName("loginForm");
		}
		return mv;
	}
}

BookController.java

package com.control;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bean.Book;

/*
 * 处理图书请求控制器
 */
@Controller
public class BookController {
	 /*
	  * 处理/main请求
	  */
	@RequestMapping(value="/main")
	 public String main(Model model){
		// 模拟数据库获得所有图书集合
		List book_list=new ArrayList();
		book_list.add(new Book("java.jpg","疯狂Java讲义(附光盘)","李刚 编著",74.2));
		book_list.add(new Book("ee.jpg","轻量级Java EE企业应用实战","李刚 编著",59.2));
		book_list.add(new Book("android.jpg","疯狂Android讲义(附光盘)","李刚 编著",60.6));
		book_list.add(new Book("ajax.jpg","疯狂Ajax讲义(附光盘)","李刚 编著",66.6));
		// 将图书集合添加到model当中
		model.addAttribute("book_list", book_list);
		// 跳转到main页面
		return "main";
	}
}

截图:

拦截器实现用户权限验证_第1张图片


拦截器实现用户权限验证_第2张图片

拦截器实现用户权限验证_第3张图片

你可能感兴趣的:(Spring,MVC,框架学习笔记)