先创建一个LoginInterceptor类
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Autowired
CategoryService categoryService;
@Autowired
OrderItemService orderItemService;
/**
* 预处理
* 在执行controller方法钱执行该方法
* return true通过
* false拦截
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String contextPath=session.getServletContext().getContextPath();
String[] noNeedAuthPage = new String[]{//不需要登录就能访问的请求名称
"home",
"checkLogin",
"register",
"loginAjax",
"login",
"product",
"category",
"search"};
String uri = request.getRequestURI();
System.out.println("uri"+uri);
System.out.println("contextPath"+contextPath);
uri = StringUtils.remove(uri, contextPath);//从uri去掉根路径
// System.out.println(uri);
if(uri.startsWith("/fore")){//判断访问路径是不是以/fore开头
String method = StringUtils.substringAfterLast(uri,"/fore" );
//将字符串数组转化为list用contains判断当前请求时候是否需要登录
if(!Arrays.asList(noNeedAuthPage).contains(method)){
User user =(User) session.getAttribute("user");
// 判断用户是否登录
if(null==user){
response.sendRedirect("loginPage");
return false;
}
}
}
return true;
}
/**
* 执行完controller方法之后,进行跳转之前执行该方法
*/
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
/**
* 执行完controller方法之后,进行跳转之后再执行该方法
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
interceptor类创建完后,在springmvc.xml中配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<!-- 配置需要拦截的方法-->
<mvc:mapping path="/fore*"/>
<!-- 配置拦截器对象-->
<bean class="com.wb.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>