Servelt中文乱码问题处理
生活随笔
收集整理的這篇文章主要介紹了
Servelt中文乱码问题处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、request與response亂碼
?在Servlet中設(shè)置編碼方式,如下:
request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); 2、輸出jsp頁(yè)面亂碼
?場(chǎng)景:在Login.jsp中,當(dāng)用戶輸入中文時(shí),輸出的頁(yè)面內(nèi)容會(huì)出現(xiàn)亂碼;
?處理:在Servlet中,在獲取用戶輸入信息時(shí),進(jìn)行中文編碼,如下:
String username =new String(request.getParameter("username").getBytes("ISO-8859-1"),"utf-8");
3、tomcat亂碼
?在server.xml中添加URIEncoding="UTF-8",useBodyEncodingForURI="true"編碼方式,如下:
<Connector port="8888" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true"/>
4、使用Servlet過濾器設(shè)置統(tǒng)一編碼
??新建ServletSetEncoding過濾器類實(shí)現(xiàn)Filter接口中的方法,如下:
public class ServletSetEncoding implements Filter {private FilterConfig configer;private String charset = "UTF-8";public void init(FilterConfig config) throws ServletException {System.out.println("*** 過濾器初始化 ***");// 獲取web.xml中Servlet攔截器配置字符編碼配置信息String str = config.getInitParameter("encoding");System.out.println("Encoding:"+str);if (str != null) {charset = str;}}public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {System.out.println("*** 過濾器執(zhí)行 ***");// 設(shè)置編碼request.setCharacterEncoding(charset);response.setContentType("text/html;charset='" + charset + "'");chain.doFilter(request, response);}public void destroy() {configer = null;System.out.println("*** 過濾器銷毀 ***");}} ? 在web.xml配置過濾器,如下:
<filter><filter-name>ServletSetEncoding</filter-name><filter-class>com.test.filter.ServletSetEncoding</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param> </filter> <filter-mapping><filter-name>ServletSetEncoding</filter-name><url-pattern>/*</url-pattern> </filter-mapping>
總結(jié)
以上是生活随笔為你收集整理的Servelt中文乱码问题处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 个人履历表
- 下一篇: 音视频OSD——制作ASCII点阵字模并