jsp亂碼問題處理方法
阿新 • • 發佈:2019-02-09
對於初學jsp的人來說,最頭疼的問題之一就是jsp的中文亂碼問題了,這個亂碼問題讓我除錯了好久,終於發現了顯示不亂碼的方法。
1、在要顯示資訊的頁面開頭加上
request.setCharacterEncoding("gb2312");
然後就可以正常顯示中文了。
2、一勞永逸的方法,使用過濾器。
SetCharacterEncodingFilter.java
package aaa; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class SetCharacterEncodingFilter implements Filter { protected FilterConfig filterConfig = null; protected String encoding = ""; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(this.encoding); response.setCharacterEncoding(this.encoding); response.setContentType("text/html;charset="+this.encoding); chain.doFilter(request, response); } public void destroy() { this.encoding = null; this.filterConfig = null; } }
web.xml頁面中配置過濾器
<filter> <description>CharacterEncodingFilter</description> <display-name>CharacterEncodingFilter</display-name> <filter-name>CharacterEncodingFilter</filter-name> <filter-class> aaa.SetCharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/s</url-pattern> </filter-mapping>
然後寫個Servlet,通過請求轉發跳轉到顯示資訊的頁面,就能顯示中文了。
請求轉發:req.getRequestDispatcher("xxx.jsp").forward(req, resp);