解决jsp插入数据库中的数据出现乱码问题

一般在jsp页面中添加下面三句 基本可以解决乱码问题,注意 前后台 数据库 编码一致

<%@   page   contentType="text/html;charset=utf-8"   %>     

<%@ page   pageEncoding="utf-8"%>  

<%request.setCharacterEncoding("utf-8");%>  

 (1)JSP页面显示乱码

对不同的WEB服务器和不同的JDK版本,处理结果就不一样。原因:服务器使用的编码方式不同和浏览器对不同的字符显示结果不同而导致的。解决办法:在JSP页面中指定编码方式(gb2312),即在页面的第一行加上:<%@ page contentType="text/html; charset=gb2312"%>

(2)表单提交中文时出现乱码

如果submit提交英文字符能正确显示,如果提交中文时就会出现乱码。原因:浏览器默认使用UTF-8编码方式来发送请求,而UTF- 8和GBK编码方式表示字符时不一样,这样就出现了不能识别字符。解决办法:通过request.setCharacterEncoding ("GBK")对请求进行统一编码,就实现了中文的正常显示。修改后的process.jsp代码如下:

<%@ page contentType="text/html; charset=GBK"%>

<% request.setCharacterEncoding("GBK"); %>

(3)Java Web配置过滤器进行字符编码

 <!-- 定义过滤器 -->

  <filter>

 <filter-name>encoding</filter-name>

 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

 <!-- 初始化 参数 设置编码是UTF-8 -->

 <init-param>

  <param-name>encoding</param-name>

  <param-value>UTF-8</param-value>

 </init-param>

 </filter>

 <!-- 设置过滤对象 -->

 <filter-mapping>

  <filter-name>encoding</filter-name>

  <!--对所有的都过滤,并走 过滤器 名称是encoding的所对应的类-->

  <url-pattern>/*</url-pattern>

 </filter-mapping>

(4) 拦截器端处理乱码

 protected void doGet(HttpServletRequest request, HttpServletResponse response)

   throws ServletException, IOException {

  // TODO Auto-generated method stub

  //设置编码格式统一为utf-8

  response.setContentType("text/html;charset=utf-8");

  request.setCharacterEncoding("UTF-8");

  ......

}

猜你喜欢

转载自blog.csdn.net/u014535666/article/details/82782327