1、编写过滤器类:需要实现Filter接口,并重写三个方法:
(1)先设置字符编码:
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
(2)重写init、destroy、doFilter方法
public class TestFilter2 implements Filter {
public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletResponse responseH = (HttpServletResponse) resp;
// responseH.setHeader("Access-Control-Allow-Origin", "*");
responseH.setHeader("Access-Control-Allow-Origin", "http://localhost:8090");
responseH.setHeader("Access-Control-Allow-Credentials", "true");
responseH.setHeader("Access-Control-Allow-Methods", "*");
responseH.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
responseH.setHeader("Access-Control-Expose-Headers", "*");
chain.doFilter(req, resp); //本行代码表示,如果还有其他的过滤器,就调用其他的过滤器,这一行代码必须写在DoFilter方法的最后面 } public void init(FilterConfig config) throws ServletException { } }
//给过滤器添加注解配置@WebFilter(filterName = "本类名",urlPatterns = "/*"),则不需要再去web.xml中注册了
//若不添加注解配置,则需要在web.xml中注册,才能使用:
<filter>
<filter-name>LocalFilter(过滤器名)</filter-name>
<filter-class>com.kuangchi.Green_Transport.filter.LocalFilter(过滤器类名)</filter-class>
</filter>
<filter-mapping>
<filter-name>LocalFilter</filter-name>
<url-pattern>/*</url-pattern> <!--过滤的路径,*代表访问所有路径的时候都会先访问这个过滤器-->
</filter-mapping>
//以上此种过滤器中设置请求头属性并设置web.xml中过滤器的设置方法,适用于SpringMVC 4.2以下版本,如果是SpringMVC 4.2及以上版本,用下面的添加方法在MVC相关的配置类里就可以了:
@configuration
public class WebConfig extends webMvcConfigurerAdapter{
@override
public void addCorsMapping (CorsRegistry registry){
registry.addMapping("/**/*").allowedOrigins("*");
}
}