欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC 拦截器使用介绍

程序员文章站 2022-05-28 18:02:45
...

package com.zf.inteceptor;

import java.util.Iterator;
import java.util.Map;

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

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component("MyInteceptor")
public class MyInteceptor extends HandlerInterceptorAdapter{

	//该方法是在进入control之前会执行
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("preHandle......................");
		String requestUrl = request.getRequestURI();
		if (requestUrl.matches(".+goIndex.do.*")) {     //可以用这种方式对某个action进行拦截 ,如果不这样 默认就是对所有control都拦截
			if(request.getSession().getAttribute("loginUser") == null){
			   request.getRequestDispatcher("/login.jsp").forward(request , response);
                      }
		}
return super.preHandle(request, response, handler);}
	//该方法是在执行完control之后再执行
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
			System.out.println("postHandle......................");
			Map model = modelAndView.getModel();	//这里可以遍历执行完control之后,control方法返回的ModelAndView对象,并且可以修改里面的内容
			for (Iterator it = model.entrySet().iterator(); it.hasNext() ;) {
				System.out.println(it.next() + "\t\t-----------------------------------");;
			}	
		super.postHandle(request, response, handler, modelAndView);
	}
java进阶 http://www.javady.com/index.php/category/hign_xingneng
相关标签: spring拦截器