Action里取值乱码问题

本文介绍了一种解决Struts框架中表单提交数据出现乱码的方法。通过在Tomcat的配置文件server.xml中设置URIEncoding参数为UTF-8,并结合自定义过滤器SetCharacterEncodingFilter,成功解决了中文乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  今天做了一个简单的structs的添加功能,在action里得到值总是乱码,

1 。 我写了过滤器类

public class SetCharacterEncodingFilter implements Filter {

  protected String encoding = null;
 
  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 = selectEncoding(request);
            if (encoding != null) {
                request.setCharacterEncoding(encoding);
            }
        }

        // Pass control on to the next filter
        chain.doFilter(request, response);

 }

 public void init(FilterConfig filterConfig) throws ServletException {
  
  this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");

 }
    protected String selectEncoding(ServletRequest request) {

        return this.encoding;
    }

}

 

2. 在web.xml加了配置

  <filter>
  <filter-name>Set Character Encoding</filter-name>
  <filter-class>
   com.shanxiu.test1.common.SetCharacterEncodingFilter
  </filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>Set Character Encoding</filter-name>
  <url-pattern>*.do</url-pattern>
 </filter-mapping>

我调式了很多次,每次请请求也就走过滤器类的doFilter(),可就是得到值还是乱码。我对那个值进行

new String(friendform.getFdetail().getBytes("ISO8859-1"),"UTF-8"); 处理后,这个值不乱码了,可总不能为

每一个值这样去处理,同事也在帮我看,她在看tomcat里的server.xml

发现在 <Connector> 加了 URIEncoding="UTF-8" 也就是下面这样后,

    <Connector
port="8080"               maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />

试运行一下,不乱码了。写出来,上其他遇到此类情况的朋友。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值