struts,Oracle 数据库 乱码解决方法

来源:互联网 发布:sql语言具有什么功能 编辑:程序博客网 时间:2024/05/20 22:27
1.Struts 乱码问题的解决。
解决的方法只有一个,设置request.setCharacterEncoding(encoding);
处理方式有很多种,这儿列举3种。
1.1 直接转换
1.2
使用过滤器 (这种比较好)

1.1 直接转换
String name1=new String(name.getBytes("iso-8859-1"),"gb2312");
不是很好,如果参数太多,转换代码就很多

1.2 使用过滤器
请参照tomcat 实例中【webapps/jsp-examples/WEB-INF/classes/filters】SetCharacterEncodingFilter.java类,和【/jsp-examples/WEB-INF】中web.xml的设置,
SetCharacterEncodingFilter.java 可以不用修改。
web.xml 中设置为你的转换格式。
eg:
SetCharacterEncodingFilter.java

package com.hz;

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 String encoding = null;
    protected FilterConfig filterConfig = null;
    protected boolean ignore = true;
   
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
    throws IOException, ServletException {
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;
    }

    protected String selectEncoding(ServletRequest request) {
        return (this.encoding);
    }
}

web.xml 中的设置

    <filter>
        <filter-name>Set Character Encoding</filter-name>
        <filter-class>com.hz.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>gb2312</param-value>
        </init-param>
        <init-param>
            <param-name>ignore</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Set Character Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

往数据库中添加数据出现乱码,我是因为数据库编码和程序编码不一样引起的。

总结:
JSP,Struts 乱码,采用过滤器,网上查了很多资料,结果都不正确,后来参照Tomcat的实例,一下就解决了。所以,网上的资料虽多,很多都没有用,采用什么技术,直接去开发技术的官网,找相应的解决方法。或参照相应正确的实例, 往往更快。
 
原创粉丝点击