1.编写login.jsp(页面一定要清理session缓存 不然前端拦截会有上一次的缓存出现 误导拦截效果)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 将数据提交到control层的login.action-->
<form action="${pageContext.request.contextPath }/login.action" method="post">
<!-- 这句话是相当重要 清理session缓存 -->
<%@ page language="java" %>
<%
session.invalidate();
%>
<label>账号:</label>
<br>
<input type="text" name="username">
<br>
<label>密码:</label>
<br>
<input type="password" name="password">
<br>
<input type="submit" value="确定">
</form>
</body>
</html>
2.编写拦截器Interceptor.class
package com.itheima.springmvc.interceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.itheima.springmvc.pojo.User;
public class interceptor implements HandlerInterceptor {
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
//判断用户是否登录
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
String requestURI = request.getRequestURI();
if(!requestURI.contains("/login.action")&&!requestURI.contains("/toLogin.action")){//放行/login.action和/toLogin.action
String username = (String) request.getSession().getAttribute("username");
if(username ==""){//判断空字符串的方式 username != null 这种方式是错的
response.sendRedirect(request.getContextPath()+"/toLogin.action");//如果为空跳转到登录页面
return false;
}
}
return true;
}
}
3.在springMVC.xml中配置拦截器
<mvc:interceptors><!-- 这里可以配置多个拦截器-->
<mvc:interceptor>
<mvc:mapping path="/**"/><!-- 拦截所有 拦截需要的目的地别拦截错了-->
<bean class="com.itheima.springmvc.interceptor.interceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
4.编写controller层
@RequestMapping("toLogin.action")
public String login(){
return "login";
}
@RequestMapping("login.action")
public String login(
String username,
String password,
HttpSession httpSession){
httpSession.setAttribute("username", username);
return "redirect:/item/itemlist.action";
}