通常我们在做网站的时候,通常有一些页面是用户未登录不能访问的,因此我们需要实现方法拦截,当访问这些页面时我们要让用户跳到用户登录页面登陆。
第一步:在springmvc.xml中配置拦截器
<!-- SPringmvc的拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 自定义的拦截器类 -->
<bean class="com.itheima.springmvc.interceptor.Interceptor"/>
</mvc:interceptor>
</mvc:interceptors>
第二步:新建login.jsp
<form action="${pageContext.request.contextPath }/login.action" method="post">
用户名:<input type="text" name="username" value="safdsdafas">
<input type="submit" value="提交">
</form>
第三步:在controller有两个方法,一个是跳转到login.jsp页面,一个是登录方法
//跳转到登录页面
@RequestMapping(value = "/login.action",method = RequestMethod.GET)
public String tologin(){
return "login";
}
//登录
@RequestMapping(value = "/login.action",method = RequestMethod.POST)
public String login(String username,HttpSession httpSession){
httpSession.setAttribute("username", username);
return "redirect:/item/itemlist.action";
}
第四步:配置拦截器类
String requestURI = request.getRequestURI();
//这个页面请求不是login就判断是否已经登录
if (!requestURI.contains("/login")) {
String username = (String) request.getSession().getAttribute("username");
//判断session是否存在
if(username == null) {
response.sendRedirect(request.getContextPath()+"/login.action");
return false;
}
}
return true;