Spring boot interceptor, intercept the problem of returning Chinese garbled characters

Viewed 205

Spring boot interceptor, intercept the problem of returning Chinese garbled characters.

Code structure as shown

enter image description here

code show as below

demoFilter

public class demoFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    response.getWriter().write("您好");
    return;

  }
}

FilterConfig

@Configuration
public class FilterConfig {

  @Bean
  public FilterRegistrationBean jwtFilter() {
    final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new demoFilter());
    registrationBean.addUrlPatterns("/*");
    return registrationBean;
  }

}

controller

@RestController
public class Demo {

  @RequestMapping(value = "demo", method = RequestMethod.GET)
  public String getStr(HttpServletRequest request, HttpServletResponse response) {
    return "demo";
  }
}

SpringApplication

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

Project start, visit http://localhost:8080/demo

Actual return:??

Expected return:您好

enter image description here

I added the following configuration to application.properties:

spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

Browser access, return:

enter image description here

Postman visits and returns correct results.

enter image description here

I would like to ask, how to solve this problem perfectly, so that the browser returns the correct Chinese.

1 Answers

It has been solved, and the following code is added to solve the problem:

response.setContentType("text/html;charset=UTF-8");

enter image description here

enter image description here

Related