ITeye博客

JSP中的乱码配置

majm · 2012-03-10 10:38 · Java Web · 编程语言 · Markdown

2.2.1. 先解决响应中的乱码 因为服务器要先从本地读取jsp文件,然后经过处理后写入响应,所以我们首先要知道的就是jsp文件的

编码格式。从问题的源头着手解决。

在咱们用的windowxp下,文件默认的编码格式是gb2312。

我们要在http的响应(response)中添加编码信息,使用如下方式:

<%@ page contentType="text/html; charset=gb2312"%>

还需要在html中指定编码格式。

POST乱码 <% request.setCharacterEncoding("gb2312"); %> GET乱码 直接点击超链接,form的默认提交方式都是GET。

POST方式下的解决方式还算简单,因为POST方式下提交的数据都是以二进制的方式附加在http请求的

body部分发送,只需要在后台指定编码格式就足矣解决。

GET方式下会将参数直接附加到url后面,这部分参数无法使用request.setCharacterEncoding()处理,

结果就是get形式的所有中文都变成了乱码。

<% String username = request.getParameter("username"); byte bytes = username.getBytes("iso-8859-1"); String result = new String(bytes, "gb2312"); out.print(result); %> <%=new String(new String(request.getParameter("username").getBytes("iso-8859-1"),

"gb2312")%>

批量设置请求编码 public class EncodingFilter implements Filter {

public void init(FilterConfig config) throws ServletException {}

public void destroy() {}

public void doFilter(ServletRequest request,
        ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {

    request.setCharacterEncoding("gb2312");
    chain.doFilter(request, response);
}

}

web.xml中的配置 EncodingFilter anni.EncodingFilter

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。