html代码
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>错误界面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/css/demo.css">
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</head>
<body>
<p th:if="${message==null}">页面迷路了,要不待会再来?</p>
<p th:if="${message!=null}"><span th:text="${message}"></span></p>
</body>
Controller代码
package com.example.demo.advice;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class CustomizeExceptionHandler {
@ExceptionHandler(Exception.class)
ModelAndView handle(HttpServletRequest request, Throwable ex , Model model) {
HttpStatus status = getStatus(request);
String error = "乱码";
model.addAttribute("message","乱码");
return new ModelAndView("error");
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
开发工具为IDEA,框架为spring boot,html界面已设为UTF-8
下图为idea设置编码的位置
当Controller的代码使用的编码是gb2312时,html界面通过“${message}”取到的值是正常的。
将代码的编码设为与html界面相同的utf-8时,“${message}”取到的值却是乱码的。
为何使用相同的编码会导致乱码,而使用不同的编码却能解决问题?