Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
亂碼是我們在程序開發(fā)中經(jīng)常碰到且讓人頭疼的一件事,尤其是我們在做javaweb開發(fā),如果我們沒有清楚亂碼產(chǎn)生的原理,碰到亂碼問題了就容易摸不著頭腦,無從下手。
亂碼主要出現(xiàn)在兩部分,如下:
第一,瀏覽器通過表單提交到后臺(tái),如果表單內(nèi)容有中文,那么后臺(tái)收到的數(shù)據(jù)可能會(huì)出現(xiàn)亂碼。
第二,后端服務(wù)器需要返回給瀏覽器數(shù)據(jù),如果數(shù)據(jù)中帶有中文,那么瀏覽器上可能會(huì)顯示亂碼。
接下來我們逐一分析亂碼產(chǎn)生的原因,以及如何解決亂碼問題。
這里又分為get請求和post請求。
get請求
get請求,請求參數(shù)中帶有中文,后臺(tái)接收會(huì)出現(xiàn)亂碼,原因是tomcat默認(rèn)編碼是“ISO-8859-1”,所以tomcat會(huì)使用“ISO-8859-1”對中文進(jìn)行編碼,該編碼不支持中文,所以后臺(tái)接收到就亂碼了。解決方式有兩種。
post請求
post請求,出現(xiàn)亂碼的原因同get請求,解決方式比較簡單,如下:
request.setCharacterEncoding("utf-8");
設(shè)置請求參數(shù)的編碼格式為“utf-8”,這樣就不會(huì)有問題了。
后端返回?cái)?shù)據(jù)給瀏覽器,一般也有兩種形式,一種是response.getOutputStream(),一種是response.getWriter()。
兩者區(qū)別以及使用規(guī)則
因此,調(diào)用requonse.getWriter()方法時(shí)可實(shí)現(xiàn)文本字符串?dāng)?shù)據(jù)輸出,調(diào)用response.getOutputStream()方法可現(xiàn)實(shí)字節(jié)流數(shù)據(jù)的輸出。所以,如果要輸出圖片等二進(jìn)制數(shù)據(jù)時(shí),需要使用response.getOutputStream。
注意,getOutputStream()和getWriter()不能同時(shí)使用,否則會(huì)拋出”getWriter() has already been called for this response“異常。
區(qū)別講完了,下面我們主要還是通過實(shí)踐分析下亂碼產(chǎn)生的原理。
response.getOutputStream().print()
返回英文數(shù)據(jù)就不說了,沒什么問題,看下返回中文是什么效果;
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.getOutputStream().print(str);
}
結(jié)果如下:
分析:
OutPutStream是輸出二進(jìn)制數(shù)據(jù)的,所以需要對字符串改成二進(jìn)制輸出,Tomcat使用的是"ISO8859-1"編碼對其進(jìn)行轉(zhuǎn)換,而中文對”ISO859-1“不支持,所以就拋異常了。
response.getOutputStream.write()
同樣的,我們再來看下輸出中文會(huì)怎么樣。
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.getOutputStream().write(str.getBytes());
}
頁面輸出結(jié)果如下:
涓浗鍔犳補(bǔ)錛屾姹夊姞娌?
分析:
在java中,String的getBytes()方法是得到一個(gè)操作系統(tǒng)默認(rèn)的編碼格式的字節(jié)數(shù)組,我電腦的系統(tǒng)是macos,默認(rèn)編碼格式是utf-8,返回給瀏覽器是utf-8編碼格式的字節(jié)數(shù)組,但是瀏覽器默認(rèn)是"gbk"編碼解析,所以就亂碼了。
既然這樣,那我們換成“gb2312”編碼(gb2312編碼是gbk編碼的一種)試試呢?
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.getOutputStream().write(str.getBytes());
}
頁面輸出:
中國加油,武漢加油
原理我們弄清楚了,但是在項(xiàng)目開發(fā)中,我們需要編碼統(tǒng)一,最常用的就是中文字符編碼"UTF-8",可是按照我們的理解,如果我們直接response.getOutputStream().write(str.getBytes("utf-8"));肯定會(huì)亂碼,我們需要用某種方式,告訴瀏覽器,你要用我指定的“utf-8”編碼接受我返回的中文。response.setContentType("text/html;charset=UTF-8")這樣就完事了,看看效果吧。
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.setContentType("text/html;charset=utf-8");
response.getOutputStream().write(str.getBytes("utf-8"));
}
頁面輸出:
中國加油,武漢加油
response.getWriter()
前面已經(jīng)總結(jié)過了,response.getWriter()跟response.getOutputStream()不一樣,outputStream是輸出二進(jìn)制的,writer是輸出字符串的。response.getWriter()輸出也有兩種方法,一種是print(),一種是write(),其實(shí)兩者在處理亂碼這一塊沒有什么區(qū)別,就不分開講述了。
示例:
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.getWriter().print(str);
}
頁面輸出:
?????????
分析:
同樣的,Tomcat默認(rèn)的編碼是ISO 8859-1,當(dāng)我們輸出中文數(shù)據(jù)的時(shí)候,Tomcat會(huì)依據(jù)ISO 8859-1碼表給我們的數(shù)據(jù)編碼,中文不支持這個(gè)碼表呀,所以出現(xiàn)了亂碼。
這個(gè)時(shí)候response.setContentType("text/html;charset=UTF-8")又派上用場了。
@RequestMapping("/helloworld.do")
public void helloworld(HttpServletRequest request, HttpServletResponse response) throws IOException {
String str = "中國加油,武漢加油";
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(str);
}
頁面輸出:
中國加油,武漢加油
在這里,response.setContentType("text/html;charset=UTF-8")做了兩件事,response.setCharacterEncoding("UTF-8");和response.setHeader("Content-Type", "text/html;charset=UTF-8");具體就是,第一,輸出中文”中國加油,武漢加油“的時(shí)候,對中文進(jìn)行”utf-8“編碼;第二,告訴瀏覽器,你也要用"utf-8"來顯示我返回的中文。
對于springMVC項(xiàng)目,如何解決亂碼問題呢?項(xiàng)目中一般會(huì)在web.xml中配置編碼過濾器。配置如下:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
這樣能保證請求的參數(shù)按照指定的編碼格式進(jìn)行編碼,簡單翻看下過濾器源碼如下:
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
代碼中有兩處重要的地方值得注意,分別是request.setCharacterEncoding(this.encoding);和response.setCharacterEncoding(this.encoding);前者表示我們對請求過來的參數(shù)使用指定的"utf-8"進(jìn)行編碼,后者便是,返回給瀏覽器時(shí),后端返回字符的編碼是“utf-8”。
好了,經(jīng)過以上分析是不是亂碼也沒有那么可怕了。只要明白其中的緣由,解決起來就是一行代碼或者幾行配置的事兒了,如果大家覺得有幫助,不妨點(diǎn)贊支持一下?
文亂碼問題是比較常見和煩人的問題,本文通過一個(gè)小程序介紹了如何通過Servlet從上一個(gè)頁面獲取參數(shù),
方法很簡單:調(diào)用request.getParameter(String s)方法。
解決中文亂碼問題的方法是:
首先要設(shè)置response響應(yīng)的格式:response.setContextType("text/html;charSet=GBK");
然后在加上request.setCharacterEncoding("GBK")
需要注意的是這是解決post方式提交的內(nèi)容的中文亂碼問題。
解決get方式提交內(nèi)容的中文亂碼問題的方法:
在Tomcat->conf文件夾->server.xml-->connecter標(biāo)簽里加上:
URIEncoding="GBK"(注意:在xml里面“=”兩邊不要有空格)
關(guān)于Post和Get之間的區(qū)別可以看我轉(zhuǎn)載的另一篇博文:
HTTP POST GET 本質(zhì)區(qū)別詳解
例子:
1.threeparams.html
2.ThreeParams.java
補(bǔ)充:
上面的這個(gè)例子.html中每個(gè)name都不一樣,如果有多個(gè)一樣的name時(shí),可以按如下的方法來獲取:
1)Enumeration paramNames = request.getParameterNames()
調(diào)用此方法獲得所有參數(shù)的名字,返回一個(gè)Enumeration
2) while(paramNames.hasMoreElements()){
String paramName = (String)paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
...
html是什么?html文檔基本結(jié)構(gòu)
html(hyper text markup language):超文本標(biāo)記語言.它不是一種編程語言,而是一種標(biāo)記語言,它有一套標(biāo)記標(biāo)簽(markup tag).html使用標(biāo)記標(biāo)簽來描述網(wǎng)頁.html文檔也叫web頁面
你可以使用html來建立自己的web站點(diǎn).
網(wǎng)頁主要由3部分組成:
■html:結(jié)構(gòu)(structure)
■css:表現(xiàn)(presentation)
■javascript:行為(behavior)
html實(shí)例:
<!doctype html>
<html>
<body>
<h1>我是第一個(gè)標(biāo)題</h2>
<p>我是第一個(gè)段落</p>
</body>
</html>
●<html>元素定義了整個(gè)html文檔,這個(gè)元素有個(gè)開始標(biāo)簽<html>,有個(gè)結(jié)束標(biāo)簽</html>
●<head>元素必須包含文檔的標(biāo)題(title),可以包含腳本,樣式,meta信息以及其他更多的信息
●<body>元素定義文檔的主體,<body>元素包含文檔的所有內(nèi)容(比如文本,超鏈接,圖像,表格和列表等等)
二 創(chuàng)建你的第一個(gè)html頁面
html文件是文本文件,因此你可以使用任何文本編輯器來創(chuàng)建你的第一個(gè)網(wǎng)頁.
給大家推薦幾款常用的編輯器:
●Notepad++
●Sublime Text
●HBuilder
●EditPlus
在編輯器中輸入:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>我的第一個(gè)段落.</p>
</body>
</html>
保存為first.html(后綴名也可以是.htm,推薦使用.html)
注意:對于中文網(wǎng)頁需要使用<meta charset="utf-8">聲明編碼,否則會(huì)出現(xiàn)亂碼.有些瀏覽器會(huì)設(shè)置GBK為默認(rèn)編碼,則你需要設(shè)置為<meta charset="gbk">
<title>標(biāo)簽定義了html文檔的標(biāo)題,在所有html文檔中是必需的
<title>元素:
●定義瀏覽器工具欄中的標(biāo)題
●提供頁面被添加到收藏夾時(shí)的標(biāo)題
●顯示在搜索引擎結(jié)果的頁面標(biāo)題
<html>
<head>
<meta charset="utf-8">
<title>我的第一個(gè)頁面</title>
</head>
<body>
<p>我的第一個(gè)段落.</p>
</body>
</html>
在editplus中運(yùn)行的結(jié)果:
*請認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。