数据库写入中文出现乱码的处理方式

乱码的处理方式:

1.数据库本身是否支持utf-8。即 数据库创建的时候,字符集是否选择了utf-8。

2.数据库链接(URL)是否加上了characterEncoding=GBK

3.页面上是否是utf-8的编码格式(共有三处

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

4.struts.xml进行国际化配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    
    <!-- 国际化配置 -->
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    
    <package name="default" namespace="/" extends="struts-default">

5.使用过滤器,加上request.setCharacterEncoding,response.setCharacterEncoding

package maya.util;

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;
import javax.servlet.annotation.WebFilter;

/**
 * Servlet Filter implementation class CharacterEncoding
 */
@WebFilter("/CharacterEncoding")
public class CharacterEncoding implements Filter {

    /**
     * Default constructor. 
     */
    public CharacterEncoding() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //utf-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
  <display-name>Struts Blank</display-name>
  
 <filter>
    <filter-name>encoding</filter-name><!-- 过滤器别称,自定义 -->
    <filter-class>maya.util.CharacterEncoding</filter-class><!--指向过滤器的路径+类名-->
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern><!-- 过滤所有页面 -->
  </filter-mapping> 
原文地址:https://www.cnblogs.com/jonsnow/p/6549770.html