怎么设置了过滤器还是有乱码?
设置了字符过滤的代码,怎么还是有乱码?
package com.imooc.bbs.global;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class EncodingFilter implements Filter {
private String encoding = "UTF-8";
public void init(FilterConfig filterConfig) throws ServletException {
/* 判断一下配置文件中有没有设置编码格式
如果有,则使用配置的
如果没有,则使用默认值UTF-8*/
if (filterConfig.getInitParameter("encoding") != null) {
encoding=filterConfig.getInitParameter("encoding");
}
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
/* 设置request和response的编码格式,并放行访问链接*/
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request,response);
}
public void destroy() {
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!--配置字符过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.imooc.bbs.global.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置默认servlet,对静态资源进行处理-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/assets/*</url-pattern>
<url-pattern>/js/*</url-pattern>
<url-pattern>/vendor/*</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!-- 配置springMVC的全局servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
9
收起
正在回答 回答被采纳积分+1
2回答
好帮手慕阿满
2021-05-16 14:23:24
同学你好,从图片上看是字体图标乱码,建议同学在过滤器的doFilter()方法中,增加如下代码,对前台页面的静态资源放行,如:
String url = request.getRequestURI();
if(url.indexOf("/static/") == -1){
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
}
filterChain.doFilter(request,response);
然后删除target文件,清空浏览器缓存,重启项目再试试。
祝学习愉快~
4. SSM到Spring Boot入门与综合实战
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星