SpringMVC拦截器

   <!-- Springmvc的异常处理器 -->
<!--         <bean class="com.itheima.springmvc.exception.CustomExceptionResolver"/> -->
 
<!-- SPringmvc的拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 自定义的拦截器类 -->
<bean class="com.itheima.springmvc.interceptor.Interceptor1"/>
</mvc:interceptor>
<!--  <mvc:interceptor>
<mvc:mapping path="/**"/>
自定义的拦截器类
<bean class="com.itheima.springmvc.interceptor.Interceptor2"/>
</mvc:interceptor> -->
</mvc:interceptors>

----------------------------------------------------------------------------------------------------------- 
 
public class Interceptor1 implements HandlerInterceptor{
 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("方法前 1");
//判断用户是否登陆  如果没有登陆  重定向到登陆页面   不放行   如果登陆了  就放行了
// URL  http://localhost:8080/springmvc-mybatis/login.action
//URI /login.action
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到登录login,是get方式传递过去
return false;
}
}
return true;
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("方法后 1");
 
}
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("页面渲染后 1");
 
}
 
 
 
}

---------------------------------
 
一般情况下 用Session.getAttibute(String key)来获得Session对象中含有的关键字是key的对象。key 是通过Session.setAttibute(String key ,Object obj)自己设定的一个索引关键字!Session对象怎么来的的呢 可以通过request.getSession()来获得!
所以现在就明白了:通过request.getsession()获得session 对象 再调用它的getAttibute(String key)方法来获得含有关键字“PASSPORT_NICKNAME”的对象

-------------------------------------------------------------------------
 //去登陆的页面
@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){
httpSession.setAttribute("USER_SESSION", username);
return "redirect:/item/itemlist.action";
}

---------------------------------------------------------------------------------
 <body> 
<form action="${pageContext.request.contextPath }/login.action" method="post">
用户名:<input type="text" name="username" value="safdsdafas">
<input type="submit" value="提交">
</form>
</body>
原文地址:https://www.cnblogs.com/MAPO/p/8473094.html