Tomcat 9.0.x 配置UTF-8
在Tomcat 9.0.x中配置UTF-8字符编码主要涉及到以下几个方面:
设置服务器字符编码:
修改
<Tomcat安装目录>/conf/server.xml
文件,在<Connector>
标签中设置URIEncoding="UTF-8"
属性。设置应用字符编码:
在应用的
web.xml
中设置<jsp-config>
和<servlet>
的字符编码过滤器。设置请求和响应编码:
在Servlet中设置请求和响应的编码。
以下是相关的配置示例:
server.xml中Connector的配置:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
web.xml中的配置:
<web-app ...>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Servlet中设置编码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
...
}
以上配置确保了Tomcat接收和发送数据时使用UTF-8编码,适用于JSP、Servlet及其他Web组件。
评论已关闭