Servlet项目字符编码如何设置?

一、前端开发时注意:

  1. 代码编辑软件使用UTF-8字符编码写文件,并通过语法标识告诉浏览器这些页面、JS、CSS文件使用的字符编码是UTF-8

 1 标识HTML页面字符编码,在HTML文件中,放<head>标签头部:
 2 <meta charset="UTF-8">
 3 
 4 标识JSP页面字符编码,在JSP文件中,放页面头部:
 5 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 6 
 7 标识CSS代码字符编码,在CSS文件中,放页面头部:
 8 @charset "UTF-8";
 9 
10 标识JS代码字符编码,在HTML或JSP文件中,写在script标签中:
11 <script charset="UTF-8" src="..."></script>

 

  2. 页面中对包含非ASCII码的URL都用JS内置的encodingURI()方法进行转码

1 //URL编码后: http://localhost:8080/test?a=%E6%B5%8B%E8%AF%95%E4%B8%AD%E6%96%87
2 location.href = encodeURI('http://localhost:8080/test?a=测试中文');

 

 

 

二、后端开发时注意:

  1. 写一个过滤器,过滤所有请求,将请求和响应数据都设置为UTF-8的字符编码;

 1 import javax.servlet.*;
 2 import java.io.IOException;
 3 
 4 public class CharSetFilter implements Filter {
 5     protected String encoding;//字符编码,从web.xml配置文件获取
 6 
 7     @Override
 8     public void init(FilterConfig filterConfig) throws ServletException {
 9         this.encoding = filterConfig.getInitParameter("encoding");
10     }
11 
12     @Override
13     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
14         if (encoding != null) {
15             servletRequest.setCharacterEncoding(encoding);
16             servletResponse.setCharacterEncoding(encoding);
17         }
18         filterChain.doFilter(servletRequest, servletResponse);
19     }
20 
21     @Override
22     public void destroy() {
23         encoding = null;
24     }
25 }

 

  2. 在web.xml文件中将这个<filter-mapping>标签前置,确保先执行它。

 1 <filter>
 2     <filter-name>CharSetFilter</filter-name>
 3     <filter-class>com.testservlet.demo.filter.CharSetFilter</filter-class>
 4     <init-param>
 5         <param-name>encoding</param-name>
 6         <param-value>utf-8</param-value>
 7     </init-param>
 8 </filter>
 9 <filter-mapping>
10     <filter-name>CharSetFilter</filter-name>
11     <url-pattern>/*</url-pattern>
12 </filter-mapping>

 

posted @ 2022-12-14 21:55  L_CrazyPerson  阅读(561)  评论(0)    收藏  举报