话不多说,直接上货!
拦截器的作用
拦截器提供了一种机制,在访问action前后进行一些操作,因为拦截器的这个特性,那么我们就可以利用拦截器做一些事情,比如监控访问人数,拦截一些非法请求,记录访问日志,身份验证之类的
构建拦截器
2.1 创建拦截器
1.创建类实现HandlerInterceptor接口
2.HandlerInterceptor有三种拦截方式
`preHandle` :在访问controller调用之前
`postHandle` :请求访问controller之后,渲染视图之前
`afterCompletion` :请求访问controller之后,渲染视图之后
3.返回值为boolean
true: 请求在经过验证校验以后,是OK的,是可以放行的
false: 请求被拦截,被驳回,验证出现问题
代码示例:
package com.imooc.interceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import static com.imooc.controller.BaseController.REDIS_USER_TOKEN;
public class UserTokenInterceptor implements HandlerInterceptor {
/**
* 拦截请求,在访问controller调用之前
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("进入拦截器");
/**
* false: 请求被拦截,被驳回,验证出现问题
* true: 请求在经过验证校验以后,是OK的,是可以放行的
*/
return true;
}
/**
* 请求访问controller之后,渲染视图之前
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* 请求访问controller之后,渲染视图之后
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2.2 注册拦截器
1.创建类实现WebMvcConfigurer接口
2.注册创建的拦截器
@Bean
public UserTokenInterceptor userTokenInterceptor() {
return new UserTokenInterceptor();
}
3.重写addInterceptors 添加监听的路径
addPathPatterns 添加监听的路径地址
excludePathPatterns 排除一些路径
代码示例:
package com.imooc.config;
import com.imooc.interceptor.UserTokenInterceptor;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public UserTokenInterceptor userTokenInterceptor() {
return new UserTokenInterceptor();
}
/**
* 注册拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userTokenInterceptor())
.addPathPatterns("/hello")
.addPathPatterns("/shopcart/add")
.addPathPatterns("/shopcart/del")
.addPathPatterns("/address/list")
.addPathPatterns("/address/add")
.addPathPatterns("/address/update")
.addPathPatterns("/address/setDefalut")
.addPathPatterns("/address/delete")
.addPathPatterns("/orders/*")
.addPathPatterns("/center/*")
.addPathPatterns("/userInfo/*")
.addPathPatterns("/myorders/*")
.addPathPatterns("/mycomments/*")
.excludePathPatterns("/myorders/deliver")
.excludePathPatterns("/orders/notifyMerchantOrderPaid");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
拦截器错误信息返回前端
因为拦截器返回的结果是布尔类型的,所有不能直接返回信息,那怎么办呢,我们可以利用output输出流来写入response中,这样前台就可以获取到了。
代码如下:
public void returnErrorResponse(HttpServletResponse response,
String result) {
OutputStream out = null;
try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/json");
out = response.getOutputStream();
out.write(result.getBytes("utf-8"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文链接:
https://blog.csdn.net/qq_38446413/article/details/105819433
更多精彩推荐
☞GitHub标星10,000+,Apache项目ShardingSphere的开源之路
☞加拿大API平台如何做到30%为中国明星项目?创业老兵这样说……
你点的每个“在看”,我都认真当成了喜欢