You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IDEA+Tomcat开发Java Web中文查询乱码问题求助

解决中文查询乱码问题的关键修正与配置方案

首先我得先指出你代码里的一个致命逻辑错误,这大概率是中文转码完全不生效的直接原因:

if(name != null && name.trim().isEmpty()){ // 这里判断逻辑写反了!
    name = new String(name.getBytes("ISO-8859-1"),"utf-8");
    product.setName(name);
}

你现在的逻辑是:只有当name不为null且是空字符串的时候才执行转码,这和你想要的「有中文内容时转码」完全相反!应该改成判断name非空字符串时才处理:

if(name != null && !name.trim().isEmpty()){
    name = new String(name.getBytes("ISO-8859-1"),"utf-8");
    product.setName(name);
}

修正完代码逻辑后,还需要处理Tomcat对GET请求的编码默认行为问题——POST请求可以通过request.setCharacterEncoding("UTF-8")统一设置,但GET请求的参数默认是用ISO-8859-1解码的,这里给你两个更彻底的解决方案:

1. 直接配置Tomcat的URI编码

找到Tomcat安装目录下的conf/server.xml,在你的HTTP Connector标签里添加编码配置:

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           URIEncoding="UTF-8"
           useBodyEncodingForURI="true"/>

URIEncoding="UTF-8"会让Tomcat用UTF-8解码所有GET请求的URI参数,useBodyEncodingForURI="true"则会让GET请求复用POST请求的编码设置,彻底避免手动转码的麻烦。

2. 全局编码过滤器(推荐跨环境兼容)

如果不想修改Tomcat配置,或者需要在不同环境下保持一致的编码处理,可以添加一个全局过滤器,统一处理所有请求的编码:

public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        
        // 统一设置请求和响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        
        // 专门处理GET请求的参数转码
        if ("GET".equalsIgnoreCase(req.getMethod())) {
            chain.doFilter(new EncodingRequestWrapper(req), resp);
        } else {
            chain.doFilter(req, resp);
        }
    }
    
    // 自定义RequestWrapper来处理GET参数的编码转换
    private static class EncodingRequestWrapper extends HttpServletRequestWrapper {
        private final HttpServletRequest request;
        
        public EncodingRequestWrapper(HttpServletRequest request) {
            super(request);
            this.request = request;
        }
        
        @Override
        public String getParameter(String name) {
            String value = request.getParameter(name);
            if (value == null) return null;
            try {
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("转码失败", e);
            }
        }
        
        @Override
        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> originalMap = request.getParameterMap();
            Map<String, String[]> newMap = new HashMap<>(originalMap.size());
            
            for (Map.Entry<String, String[]> entry : originalMap.entrySet()) {
                String[] values = entry.getValue();
                String[] decodedValues = new String[values.length];
                for (int i = 0; i < values.length; i++) {
                    try {
                        decodedValues[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException("批量转码失败", e);
                    }
                }
                newMap.put(entry.getKey(), decodedValues);
            }
            return newMap;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}

然后在web.xml中配置这个过滤器,让它拦截所有请求:

<filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>com.your.package.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

最后别忘了验证数据库连接编码

确保你的MySQL连接URL里指定了UTF-8编码,比如:

jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

如果数据库连接没有指定编码,即使前面的步骤都正确,查询返回的数据也可能出现乱码。

修正完以上内容后,重启Tomcat再测试中文查询,应该就能解决乱码问题了。

内容的提问来源于stack exchange,提问作者Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:00