JSR315 将默认的 JSP 文件编码指定为 ISO-8859-1。这是 JSP 引擎用来读取 JSP 文件的编码,它与 servlet 请求或响应编码无关。
如果您的 JSP 文件中有非拉丁字符,请将 JSP 文件另存为带有 BOM 的 UTF-8 或在 JSP 页面的开头设置 pageEncoding:
<%@page pageEncoding="UTF-8" %>
但是,您可能希望将所有 JSP 页面的默认值全局更改为 UTF-8。这可以通过web.xml 完成:
<jsp-config>
<jsp-property-group>
<url-pattern>/*</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
或者,当使用带有(嵌入式)Tomcat 的 Spring Boot 时,通过TomcatContextCustomizer:
@Component
public class JspConfig implements TomcatContextCustomizer {
@Override
public void customize(Context context) {
JspPropertyGroup pg = new JspPropertyGroup();
pg.addUrlPattern("/*");
pg.setPageEncoding("UTF-8");
pg.setTrimWhitespace("true"); // optional, but nice to have
ArrayList<JspPropertyGroupDescriptor> pgs = new ArrayList<>();
pgs.add(new JspPropertyGroupDescriptorImpl(pg));
context.setJspConfigDescriptor(new JspConfigDescriptorImpl(pgs, new ArrayList<TaglibDescriptor>()));
}
}
要让 JSP 与 Spring Boot 一起使用,请不要忘记包含以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
要制作“可运行”的 .war 文件,请重新打包:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
. . .