验证中...
片段 1 片段 2 片段 3
过滤器配置
原始数据 复制代码
第一种方式:
首先配置过滤器
public class JwtFilter extends GenericFilterBean implements Filter{
@Override
public void destroy() {
System.out.println("过滤器被销毁");
}
@Override
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse)res;
String path = request.getContextPath();
String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path;
//客户端将token封装在请求头中,格式为(Bearer后加空格):Authorization:Bearer +token
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
/*throw new ServletException("Missing or invalid Authorization header.");*/
response.sendRedirect("hellp.html");
}
//去除Bearer 后部分
final String token = authHeader.substring(7);
try {
//解密token,拿到里面的对象claims
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
//将对象传递给下一个请求
request.setAttribute("claims", claims);
}
catch (final SignatureException e) {
throw new ServletException("Invalid token.");
}
chain.doFilter(req, res);
}
/*@Override
public void init(FilterConfig arg0) throws ServletException{
System.out.println("过滤器被初始化");
}*/
}
上述中Jwt类继承GenericFilterBean或者实现Filter接口,之后重写其中的doFilter方法即可。
之后在SpringBoot程序入口加入一个过滤器的Bean
@Bean
protected FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/api/*");
return registrationBean;
}
第二种:
在过滤器中加入注解
@Order(1)
@WebFilter(filterName = "JwtFilter",urlPatterns = "/apia/*")
其中order表示过滤等级,越小优先级越高,之后加入WebFilter注解,之后在程序入口加入如下注解即可:
@ServletComponentScan
拦截器配置
原始数据 复制代码
首先创建一个拦截器类,实现HandlerInterceptor接口,重写其中的三个方法
public class TestIntercepter implements HandlerInterceptor {
//在请求处理之前进行调用(Controller方法调用之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.printf("preHandle被调用");
return true; //如果false,停止流程,api被拦截
}
//请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle被调用");
}
//在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion被调用");
}
}
之后创建一个拦截器的配置类,继承WebMvcConfigurerAdapter类,重写其中的addInterceptors
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
/**
* 配置静态资源
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
super.addResourceHandlers(registry);
}
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns 用于添加拦截规则
//excludePathPatterns 用于排除拦截
registry.addInterceptor(new TestIntercepter()).addPathPatterns("/**")
.excludePathPatterns("/hlladmin/login") //登录页
.excludePathPatterns("/hlladmin/user/sendEmail") //发送邮箱
.excludePathPatterns("/hlladmin/user/register") //用户注册
.excludePathPatterns("/hlladmin/user/login"); //用户登录
super.addInterceptors(registry);
}
}
如果需要调用Service层的对象,在拦截器注册中定义拦截器的Bean,然后在注册的时候调用该方法而不是new一个对象即可。
@Bean
public TestIntercepter testIntercepter() {
return new TestIntercepter();
}
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns 用于添加拦截规则
//excludePathPatterns 用于排除拦截
registry.addInterceptor(testIntercepter()).addPathPatterns("/**")
.excludePathPatterns("/hlladmin/login") //登录页
.excludePathPatterns("/hlladmin/user/sendEmail") //发送邮箱
.excludePathPatterns("/hlladmin/user/register") //用户注册
.excludePathPatterns("/hlladmin/user/login"); //用户登录
super.addInterceptors(registry);
}
监听器配置
原始数据 复制代码
监听器的配置有2中方案,一种通过代码注册的方式,在程序启动入口加入一个Bean
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new IndexListener());
return servletListenerRegistrationBean;
}
第二种通过注解的形式
@WebListener
public class TestListen implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("监听器初始化启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("监听器初始化结束");
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助

12_float_left_people 12_float_left_close