struts2中的参数charset转换

时间:2010-03-04 18:51:39

标签: java struts2

我有一个struts2 Web应用程序,它接受许多不同字符集中的POST和GET请求,将它们转换为utf-8,在屏幕上显示正确的utf-8字符,然后将它们写入utf-8数据库。

我已经尝试过至少5种不同的方法来完成从windows-1250到utf-8的简单无失败字符集转换,并且所有这些方法都不起作用。 Utf-8是“更大的集合”,它应该没有问题(至少这是我的理解)。

你能否提出如何从windows-1250到utf-8进行字符集转换,并且struts2可能会使用params charset做一些奇怪的事情,这可以解释为什么我似乎无法正确使用它。

这是我最近的尝试:

    String inputData = getSimpleParamValue("some_input_param_from_get");
    Charset inputCharset = Charset.forName("windows-1250");
    Charset utfCharset = Charset.forName("UTF-8");

    CharsetDecoder decoder = inputCharset.newDecoder();
    CharsetEncoder encoder = utfCharset.newEncoder();

    String decodedData = "";
    try {
        ByteBuffer inputBytes = ByteBuffer.wrap(inputData.getBytes()); // I've tried putting UTF-8 here as well, with no luck
        CharBuffer chars = decoder.decode(inputBytes);

        ByteBuffer utfBytes = encoder.encode(chars);
        decodedData = new String(utfBytes.array());

    } catch (CharacterCodingException e) {
        logger.error(e);
    }

关于如何使其发挥作用的任何想法?

谢谢你,最诚挚的问候,

博若

1 个答案:

答案 0 :(得分:0)

我不确定你的情况。在Java中,String是Unicode,只有在必须从/向String转换为/从二进制表示转换时才处理字符集转换。 在您的示例中,当调用getSimpleParamValue(“some_input_param_from_get”)时,inputData应该已经具有“正确的”字符串,从字节流(从客户端浏览器传送到Web服务器)到字符串的转换应该已经采用部分(Web服务器的责任+应用程序的Web层)。 为此,我为web trasmission强制执行UTF-8,在web.xml中放置一个过滤器(在Struts之前),例如:

public class CharsetFilter implements Filter {

    public void destroy() {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        req.setCharacterEncoding("UTF-8");

        chain.doFilter(req, res);
        String contentType = res.getContentType(); 
        if( contentType !=null && contentType.startsWith("text/html"))
            res.setCharacterEncoding("UTF-8");
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

如果你不能这样做,并且如果你的getSimpleParamValue()在charset转换中“错误”(例如:它假设字节流是UTF-8并且是windows-1250)你现在有一个“不正确”的字符串,并且你必须尝试通过撤消和重做字节到字符串的转换来恢复它 - 在这种情况下你必须知道错误的和正确的字符集 - 更糟糕的是,处理丢失的字符的可能性(如果它被解释为UTF8,我可能找到了非法的char序列)。 如果你必须在Struts2动作中处理这个问题,我会说你遇到了问题,你应该在它之前/之后明确地处理它(在上层web层 - 或者在数据库驱动程序或文件编码或其他任何方面)< / p>