过滤器过滤response,设置成response.setContentType(“text/html;charset=utf-8“);导致CSS无法正常加载

Resource interpreted as Stylesheet but transferred with MIME type text/html 报错
在这里插入图片描述
方法一:
在这里插入图片描述
方法二:

@WebFilter("/")
public class EncodingFilter implements Filter{
    
    

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
    
    
		request.setCharacterEncoding("utf-8");
		String contentType = ((HttpServletRequest)request).getHeader("Accept");
		response.setContentType(contentType == null ? "text/html;charset=utf-8" : contentType + ";charset=utf-8");
		chain.doFilter(request, response);
	}
	
}

方法三:
获取url类型,只要是css或者js等其他资源就修改contentType

方法四:
使用ServletResponse的子类HttpServletResponse来设置过滤。完美解决!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhanghongbin159/article/details/114434872