1. 程式人生 > >interceptor攔截器

interceptor攔截器

ase patch response del ppi pack 設置 and bject

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地址,比如一些登陸、註冊、驗證碼、和可以不登錄操作的接口。

至此結束。

interceptor攔截器