spring 执行过程时 过滤器先执行,拦截器后执行
- 过滤器 Filter 的使用。
package cn.waimaolang.demo.middleware;
import cn.waimaolang.demo.utils.HttpResultUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @title 过滤器 根据 urlPatterns 的路径 进行过滤请求
*/
@WebFilter(urlPatterns = {"/home/*"},filterName = "IndexFilter")
public class IndexFilter implements Filter
{
@Autowired
HttpResultUtils httpResultUtils;
/**
* 框架启动的时候执行
* 容器加载的时候调用
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init IndexMiddleware");
}
/**
* 请求被拦截的时候进行调用
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setAttribute("name","wangjun");
if(true){
System.out.println("我是过滤器 xxx");
// 允许继续执行 -> 走控制器
filterChain.doFilter(servletRequest,servletResponse);
}else{
// 返回错误 ,禁止进入控制器
response.setContentType("application/json;charset=utf-8");//指定返回的格式为JSON格式
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String json = JSON.toJSONString(httpResultUtils.fail("过滤器阻止你进入xxx"));
out.write(json);
out.close();
}
}
/**
* 容器被销毁的时候被调用
*/
@Override
public void destroy() {
System.out.println("destroy loginFilter");
}
}
- 拦截器的使用
(两步 1.自定义一个Interceptor 2. 注册)
// 定义一个拦截器
package cn.waimaolang.demo.middleware;
import cn.waimaolang.demo.utils.HttpResultUtils;
import com.alibaba.fastjson.JSON;
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.PrintWriter;
/**
* 拦截器
*/
public class IndexIntercepter implements HandlerInterceptor
{
@Autowired
HttpResultUtils httpResultUtils;
/**
* 进入controller方法之前执行
*/
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler
) throws Exception {
// 权限验证
String Secret = request.getHeader("Secret");
if( StringUtils.isEmpty(Secret) || !Secret.equals("xxxxx")){
// 权限验证失败
response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setStatus(403);
PrintWriter out = response.getWriter();// 这一句一定要在前面三句的后面,否则会导致设置ContentType无效
out.write(JSONObject.toJSONString(new ApiResultResponse(403,"禁止访问,退出登陆")));
out.close();
return false;// 权限验证失败,不允许进入控制器
}
return true; // 进入控制器
}
/**
* 调用完controller之后,视图渲染之前
*/
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView
) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/**
* 一个请求完成之后,通常用于资源清理
*/
@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex
) throws Exception {
System.out.println("执行完成 xxxx....");
HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
}
}
//注册拦截器
package cn.waimaolang.demo.configura;
import cn.waimaolang.demo.middleware.IndexIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* web mvc 模式的 拦截器配置
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer
{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册多个Interceptor 注意路径的写法
registry.addInterceptor(new IndexIntercepter()).addPathPatterns("/home/*");
//registry.addInterceptor(new TwoIntercepter()).addPathPatterns("/api2/*/**");
//注册某个拦截器的时候,同时排除某些不拦截的路径
//registry.addInterceptor(new TwoIntercepter()).addPathPatterns("/api2/*/**").excludePathPatterns("/api2/xxx/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
3.springboot 监听器教程
http://note.youdao.com/noteshare?id=c5df28a39ba57038089a20aad5011369&sub=ACDF29C77E04421298903C2BE6C7E822
网友评论