拦截器定义
实现HandlerInterceptor接口,实现接口方法。
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{
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 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");
}
}
拦截器配置
在springmvc.xml中配置拦截器
<!-- SPringmvc的拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 自定义的拦截器类 -->
<bean class="com.itheima.springmvc.interceptor.Interceptor1"/>
</mvc:interceptor>
</mvc:interceptors>
编写登录jsp
<title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/login.action" method="post">
用户名:<input type="text" name="username" placeholder="输入用户名">
<input type="submit" value="提交">
</form>
</body>
编写用户登录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){
httpSession.setAttribute("USER_SESSION", username);
return "redirect:/item/itemlist.action";
}