代码之家  ›  专栏  ›  技术社区  ›  bozo

Struts2中的参数字符集转换

  •  0
  • bozo  · 技术社区  · 16 年前

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

    我已经尝试了至少5种不同的方法,从Windows-1250到UTF-8进行简单的无损字符集转换,但所有方法都不起作用。UTF-8是“更大的集合”,应该可以毫无问题地工作(至少这是我的理解)。

    你能提出如何从Windows-1250到UTF-8进行字符集转换吗?Struts2是否对参数字符集做了一些奇怪的事情,这就解释了为什么我不能正确地进行转换。

    这是我最近的尝试:

        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 回复  |  直到 16 年前
        1
  •  0
  •   leonbloy    16 年前

    我不确定你的情况。在Java中,一个字符串是Unicode,一个只处理字符集转换,当必须从字符串转换为/从二进制表示转换。 在您的示例中,当调用getSimpleParamValue(“some_input_param_from_get”)时,inputData应该已经具有“correct”字符串,从字节流(从客户端浏览器传输到Web服务器)到字符串的转换应该已经参与(Web服务器的响应性+应用程序的Web层)。 为此,我对Web传输强制使用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 {
        }
    }
    

    如果无法执行此操作,并且在字符集转换(例如:假定字节流是UTF-8,是Windows-1250)中,如果getSimpleParamValue()“errs”,则现在有一个“不正确”字符串,必须尝试通过撤消和重做字节到字符串的转换来恢复该字符串-在这种情况下,必须知道错误和正确的字符集-以及,worse,处理丢失字符的可能性(如果它被解释为utf8,我会发现非法字符序列)。 如果您必须在struts2操作中处理这个问题,我会说您遇到了问题,您应该在它之前/之后(在上层Web层中,或者在数据库驱动程序或文件编码中)明确地处理它。