首页 > 编程语言 > Spring interceptor拦截器配置及用法解析
2020
10-15

Spring interceptor拦截器配置及用法解析

fifter、servlet、interceptor

fifter用来处理请求头、请求参数、编码的一些设置,然后转交给servlet,处理业务,返回

servlet现在常用的spring,servlet拦截/到DispatcherServlet,交由spring管理

interceptor,servlet请求之后可以实现HandlerInterceptor做到preHandle、postHandle、afterCompletion在controller之前、之后、渲染之后

登陆

业务中常用的登陆、注册,大部分用cookie、session来做,这时候就涉及到拦截判断用户是否登陆、是否有权限?至此引出interceptor:

  package com.bs.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bs.controller.BaseController;
import com.bs.entity.Member;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		Member member = BaseController.getMemberByCookie(request);
		System.out.println(member);
		if(member == null){
			response.sendRedirect("/officialweb/login.html"); 
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}
}

java代码如上,然后在servlet.xml中配置如下:

 <!-- 拦截器 --> 
 <!--     多个拦截器,顺序执行 -->
  <mvc:interceptors> 
     <mvc:interceptor> 
      <mvc:mapping path="/**"/>
      <mvc:exclude-mapping path="/**/cloud/**" />
      <mvc:exclude-mapping path="/**/login/**" />
      <bean class="com.bs.interceptor.LoginInterceptor"></bean> 
    </mvc:interceptor> 
  </mvc:interceptors>

mvc:mapping拦截的path地址,mvc:exclude-mapping不拦截的path地址,比如一些登陆、注册、验证码、和可以不登录操作的接口。

至此结束。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧