spring mvc拦截器实现步骤

1.spring mvc.xml里面配置:

	
		
		
		    
			
			
		 
 	
	

2.拦截器类

 package com.itheima.springmvc.interceptor;

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

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

public class Interceptor1 implements HandlerInterceptor{

// Controller执行前调用此方法
// 返回true表示继续执行,返回false中止执行
// 这里可以加入登录校验、权限拦截等
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
	// TODO Auto-generated method stub
	System.out.println(" preHandle NO.1");
	String requestURI = request.getRequestURI();
	if(!requestURI.contains("/login")){
		String username = (String) request.getSession().getAttribute("USER_SESSION");
		//没有用户信息  未登录状态
		if(null == username){
			response.sendRedirect(request.getContextPath() + "/login.action");
			return false;
		}
	}
	return true;
}
// controller执行后但未返回视图前调用此方法
// 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
		throws Exception {
	// TODO Auto-generated method stub
	System.out.println("postHandle NO.2");
	
}
// controller执行后且视图返回后调用此方法
// 这里可得到执行controller时的异常信息
// 这里可记录操作日志
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
		throws Exception {
	// TODO Auto-generated method stub
	System.out.println("afterCompletion  NO.3");
	
}

3.controller写登录:

 //去登陆的页面
@RequestMapping(value = "/login.action",method = RequestMethod.GET)
public String login(){
	return "login";
}

@RequestMapping(value = "/login.action",method = RequestMethod.POST)
public String login(String username,HttpSession httpSession){
	//登录的XML
	//登录成功
	//把用户信息存放到Session中
	//任务:自定义设置session的过期时间
	httpSession.setAttribute("USER_SESSION", username);
	return "redirect:/item/itemlist.action";
}

}

你可能感兴趣的:(Function,Module,java教程,面试题等,springmvc)