加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 教程 > 正文

讨论tomcat下的jsp和servlet的字符编码问题

发布时间:2023-05-29 13:36:45 所属栏目:教程 来源:
导读:在前面的文章里面,我们讨论了在tomcat下的jsp和servlet的字符编码问题!

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

但是我们怎
在前面的文章里面,我们讨论了在tomcat下的jsp和servlet的字符编码问题!
 
知道当没有指定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>
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!