jsp乱码问题处理方法

来源:互联网 发布:淘宝商品推广 编辑:程序博客网 时间:2024/06/07 02:39

对于初学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);






0 0
原创粉丝点击