Filter过滤器可以处理请求,对请求的参数、属性进行调整;常用于处理字符编码
一. 创建Filter类
package com.xdu.studyspringboot.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行了MyFilter方法");
filterChain.doFilter(servletRequest,servletResponse);
}
}
二. 创建Filter配置类
package com.xdu.studyspringboot.config;
import com.xdu.studyspringboot.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebApplicationConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new MyFilter());
bean.addUrlPatterns("/user/*");
return bean;
}
}
三. 测试
package com.xdu.studyspringboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class FilterController {
@RequestMapping("/user/manager")
@ResponseBody
public String userManager(){
return "user/manager";
}
@RequestMapping("/query")
@ResponseBody
public String queryUser(){
return "query";
}
}
访问/user/manager会执行doFilter方法,访问/query不执行doFilter方法