拦截器的左右就是
进门得买票不买票不让进
就是你在访问一个网站时你得有这个网站的会员账号你如果没有这个网站的会员账号你就不能访问这个网站除了登录页面的其他页面,也就是你没票,和爬山一样。
你可以去买票,你也可以不买票,你只要有办法你一样能进的去。
不过到底拦截器还是有很大的作用的。
使用拦截器分为几个步骤:
1. 把 拦截器 文件 Interceptor1.java 放到 与控制器 同级目录
2. 需要拦截器 放到 启动类中 , 把登陆 放到拦截器之外
3. 登陆时候 建立 session 名称为 name 的 个给其赋值 。
首先在启动类中加入代码
启动类需要实现WebMvcConfigurer这个接口
@Override
public void addInterceptors(InterceptorRegistry registry){
InterceptorRegistration ir=registry.addInterceptor(new Interceptor1());
ir.addPathPatterns("/**");
// ir.excludePathPatterns("/stu/save","/stu/getClassGid","/stu/pageList","/stu/getClassAll","/index/index","/index/right","/stu/news","/stu/pageList","/stu/indexData","/stu/getEditData","/stu/getClass","/stu/del","/stu/edit","/stu/login","/stu/index","/stu/add","/js/**","/html/**","/images/**","/css/**");
ir.excludePathPatterns("/stu/login","/js/**","/html/**","/images/**","/css/**");
}
在ir.excludePathPatterns里放开不被拦截的
把上面这个代码放到和控制器一个包
起名字为Interceptor1 因为在上面实例化的这个,改名一定要一起改
还有一点 存入session的时候一定要注意下面获取session的名字不然还是会报拦截器的错误的!
package com.msfh.news.controller;
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;
public class Interceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
HttpSession session=request.getSession();
Object ob=session.getAttribute("uname");
if (ob!=null) {
return true;
}
session.setAttribute("preurl",request.getRequestURI());
StringBuffer url = request.getRequestURL();
String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
response.sendRedirect("/in/login");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler,ModelAndView model) throws Exception{
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler,Exception ex) throws Exception{
}
}