页面乱码

xiaoxiao2021-02-28  75

最近在做项目的时候,遇到一个乱码问题:

后台中文,前端编程???乱码。找了很多办法。下面解析一下知识点

一、页面:

1. 指定jsp文件里内容的的编码方式

   <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

2. 指定html文件里内容的编码方式    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 3. 当响应用户的请求时,输出到用户浏览器上的编码方式

   <%@ page contentType="text/html"; charset="gb2312"%>    相当于生成的代码 response.setContentType("text/html; charset=gb2312");

二、request

1. 把用户传递过来的参数作为指定的编码 request.setCharacterEncoding("gb2312");

2. 对比    request.setCharacterEncoding("gb2312");               //设置输入编码格式    response.setContentType("text/html; charset=gb2312"); //设置输出编码格式

三、response

首先,response返回有两种,一种是字节流outputstream,一种是字符流printwrite。

//这句话的意思,是让浏览器用utf8来解析返回的数据 response.setHeader("Content-type", "text/html;charset=UTF-8"); String data = "中国"; OutputStream ps = response.getOutputStream(); //这句话的意思,使得放入流的数据是utf8格式 ps.write(data.getBytes("UTF-8"));

再说字符流,要输出中国,需要设置response.setCharacterEncoding("UTF-8");

//这句话的意思,是让浏览器用utf8来解析返回的数据 response.setHeader("Content-type", "text/html;charset=UTF-8"); //这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859 response.setCharacterEncoding("UTF-8"); String data = "中国"; PrintWriter pw = response.getWriter(); pw.write(data);

经验:1,如果中文返回出现??字符,这表明没有加response.setCharacterEncoding("UTF-8");这句话。

            2,如果返回的中文是“烇湫”这种乱码,说明浏览器的解析问题,应该检查下是否忘加response.setHeader("Content-type", "text/html;charset=UTF-8");这句话。

--------------------------------------------------------------分割线----------------------------------------------------------------------

但是,我要说的重点不是这个

导致我掌握这些知识点之后还出现乱码的原因是,我把设置编码格式的语句放在的PringWriter后面了,必须要放在前面才会有效果。

这是为什么呢,最后在printWriter的API中找到答案。在调用PrintWriter中的getWrite方法的时候,如果没有指定编码格式,那么编码格式就会默认为: ISO-8859-1

PrintWriter getWriter() throws IOException Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.

转载请注明原文地址: https://www.6miu.com/read-2249998.html

最新回复(0)