JSP 页面和数据库交互中文乱码库问题

首先要保证JSP页面的页面编码和数据库的编码一致。这里使用utf-8作为统一编码字符类型,步骤如下。
<1>整个项目在eclipse下设置UTF8编码
鼠标选中项目,右键单击,选择下面的properties,点击dialog中的Resource选择设置编码为utf8(默认为GBK)
JSP 页面和数据库交互中文乱码库问题_第1张图片
<2>数据库设置属性:

Set charset utf8

这里写图片描述
<3>在用JDBC链接数据库的时候,在驱动语句后加上
?useUnicode=true&characterEncoding=UTF-8
完整如下
jdbc:mysql://localhost:3306/ylsn_db?useUnicode=true&characterEncoding=UTF-8

在每个JSP页面头中添加以下三句话:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%request.setCharacterEncoding("UTF-8");%> 
    <meta charset="UTF-8">

以上三个步骤还是不行的话就再写一个filter类来对所有页面的传输数据进行转码
新建一个filter类
这里写图片描述
直接使用下面的代码:

package filter;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class SetCharacterEncodingFilter implements Filter {
    class Request extends HttpServletRequestWrapper
    {
        public Request(HttpServletRequest request) {
            super(request);
        }
        public String toUTF8(String input) {
            try {
                byte[] bytes = input.getBytes("ISO8859-1");
                return new String(bytes, "utf-8");
            } catch (Exception ex) {
            }
            return null;
        }
        private HttpServletRequest getHttpServletRequest()
        {
            return (HttpServletRequest) super.getRequest();
        }
        public String getParameter(String name)
        {
            return
                    toUTF8(getHttpServletRequest().getParameter(name));
        }
        public String[] getParameterValues(String name)
        {
            String values[] =getHttpServletRequest().getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = toUTF8(values[i]);
                }
            }
            return values;
        }
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse
    response,FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpreq = (HttpServletRequest) request;
        if (httpreq.getMethod().equals("POST")) {
            request.setCharacterEncoding("utf-8");
        } else {
            request = new Request(httpreq);
        }
        chain.doFilter(request, response);
    }
    public void init(FilterConfig filterConfig) throws
    ServletException {
    }  
}

在web.xml 配置文件写上

<filter>
    <filter-name>SetCharacterEncodingFilterfilter-name>
    <filter-class>filter.SetCharacterEncodingFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>SetCharacterEncodingFilterfilter-name>
    /*
  filter-mapping>

/*表示对全部url进行过滤转码
以上步骤应该能解决JSP页面与数据库交互的中文乱码问题了。

你可能感兴趣的:(JSP)