通过filter来改变request编码

当没有指定request的编码的时候,从客户端得到的数据是iso-8859-1编码的(request.getParameter()得到传递的参数值);

但是我们怎么来改变request的编码呢?

方法有很多种!

比如:在getRequestDispatcher("/jsp/jsptoserv/hello.jsp").forward(request, response);之前修改

request的编码,那么在jsp/jsptoserv/hello.jsp中得到的参数值就是制定的编码的字符。

本文我们使用Filter来修改request的编码!

 

1)首先编写filter类:

package myFilter;


import java.io.IOException;
import javax.servlet.*;

public class ChangeCharsetFilter implements Filter {


    protected String encoding = null;/要制定的编码,在web.xml中配置

    protected FilterConfig filterConfig = null;

        public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }

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

            if (request.getCharacterEncoding() == null){
            String encoding = getEncoding();得到指定的编码名字
            if (encoding != null)
                request.setCharacterEncoding(encoding);设置request的编码
        }

         chain.doFilter(request, response);///有机会执行下一个filter

    }

    public void init(FilterConfig filterConfig) throws ServletException {

          this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");///得到在web.xml中配置的编码
  
    }


    protected String getEncoding() {

        return (this.encoding);///得到指定的编码

    }


}

 


2。编辑web.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>myFilter.ChangeCharsetFilter </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GB2312</param-value>//指定编码为GB2312
        </init-param>
     </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>对于所有的request改变其编码
    </filter-mapping>

</web-app>
///

3。

写一个a.jsp

<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head></head>
<body>
<%
String name=request.getParameter("name");///本来这里得到字符是iso-8859-1编码的,不能直接

在Console中输出的,但是现在改变了request的编码方式,此时的name的编码是GB2312,所以能正确在Console中显示的。

System.out.println(name);

%>
<form action="a.jsp" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<%=name%>
</body>
</html>

完!

关于中文处理的问题就写这些了!

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值