Problem Description
Developed a java web project, the development environment is
- tomcat7
- maven
- my shoe
- mysql
- idea
The java web project can run normally locally. After deploying to Tomcat8.5, the browser console can monitor that various css files are indeed loaded, but chrome and other browsing The browser cannot correctly identify css, parse css and apply it to html files, resulting in style confusion
problem causes
I compared the css loading situation in the browser in my local project that is running normally with the css deployed to the server.
-
Projects that are running normally
We found that in projects that are running normally Content-Type:text/css;charset=utf-8 -
Projects whose css was not parsed correctly after being deployed to Tomcat
We found itContent-Type:text/html;charset=utf-8
reason
返回的文档格式不正确
problem solved
In my project, there is a filter
with the following code inside it
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 处理请求乱码
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
// HttpServletRequest myRequest = new MyRequest(httpServletRequest);
处理响应乱码
// servletResponse.setContentType("text/json;charset=utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
I have set it up hereservletResponse.setContentType("text/html;charset=utf-8");
Comment this out first and the problem will be solved.
Since we still need to solve the problem of garbled characters, we modify the code as follows
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 处理请求乱码
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
// HttpServletRequest myRequest = new MyRequest(httpServletRequest);
处理响应乱码
// servletResponse.setContentType("text/json;charset=utf-8");
String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
if (requestURI.contains(".css")||requestURI.contains(".js")||requestURI.contains(".png")||requestURI.contains(".jpg")) {
filterChain.doFilter(servletRequest,servletResponse);
return;
}else{
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}
Code reference here: https://blog.csdn.net/dmyin/article/details/107759691