在web项目中,拦截器是不可或缺的,下面就拦截器来讲解一下代码
首先,要自定义一个拦截器并继承 HandlerInterceptor 接口
package com.xyh.Config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String flag = (String) session.getAttribute("user");
if(null == flag){
request.setAttribute("msg","您还未登录,请先登录");
request.getRequestDispatcher("test").forward(request,response);
}
return true;
}
}
通过session获取是否已经登录,若已登录,则放行,return true,若session 为空,则表示并未登录,则返回一条msg,转发到你自己的登录界面,让用户先登录,再进行下面的操作。
配置完自定义拦截器,还要在配置类里装配
package com.xyh;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/*")
.excludePathPatterns("/test")
.excludePathPatterns("/register")
.excludePathPatterns("/log")
.excludePathPatterns("/UserLogin")
.excludePathPatterns("/file")
.excludePathPatterns("/fileUpload")
.excludePathPatterns("/toregister");
}
}
@configuration表明是一个配置类,然后继承了WebMvcConfigurer接口,重写它的addInterceptor方法,也就是它里面的关于拦截器的方法,把自己的类名称通过new的方式注入进来,然后.addPathPatterns("/*")表示拦截所有请求,..excludePathPatterns("")表示不拦截一些请求,引号里写自己不想被拦截的地址