2009-03-17

Tomcat Post / Get 中文編碼處理方法 (中文亂碼問題)

最近在把原本佈署在 Resin 的 Java Web Application移植到 Tomcat 時,有許多原本正常的中文get / post 功能,都變的異常,只要是透過 get / post 得到的資料,就會變亂碼

剛好也驗證了 Resin 在Character Encoding的部分做的較好
而看看網路上大家的問題,也可以知道 Tomcat 在編碼處理的部分 真是讓很多人頭痛

主要的原因是,TOMCAT 預設都是用 ISO-8859-1 的編碼方式來傳遞資訊

這個問題,可以解決的方式整理如下:

1. JSP 頁面的編碼宣告需與實際儲存檔案時用的編碼一致

這是個很好玩的問題~ 有些人 在頁面宣告用 big5 or UTF-8 or... 字集
但是,檔案實際儲存的方式與該編碼不同,則 頁面當然會出現亂碼的問題

2. 自行轉碼
form method=POST or GET 時 因為Tomcat預設編碼是ISO-8859-1的關係
直接用 <%=request.getParameter("firstname")%> 取值,中文字會變亂碼
(你傳的明明是UTF-8, 但是讀取時 確用 ISO-8859-1來解譯.. 當然有問題囉)
要使用 <%=new String(request.getParameter("firstname").getBytes( "ISO-8859-1"), "UTF-8")%>這種方式 來轉換編碼才會正常 (假設,頁面用的編碼為UTF-8時)

3. 透過設定 server.xml URIEncoding的方式 來處理 GET 亂碼問題
在 tomcat 的設定檔內 ./conf/server.xml 修改下列設定的話,則透過GET的方式傳遞參數
的話,Tomcat會用你指定的編碼方式來對待用get方法傳遞的參數,而不是使用預設的ISO-8859-1 (get 的方式是透過 url parameter傳遞參數)
但是,因為只處理 URIEncoding, 所以若使用 Post 傳遞,還是會有問題


URIEncoding: This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

P.S. 若使用 GET Method, 且設定了URIEncoding 的話就不用再做上述二的自行轉碼動作,如果多加該處理,一樣會有亂碼的問題

4. 使用 request.setCharacterEncoding 來處理 GET / POST 的亂碼問題
在處理的頁面,加上下列的處理即可,明確的告訴Tomcat request的編碼為何,不要一廂情願的使用ISO-8859-1來解讀~

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

javax.servlet.servletRequest.setCharacterEncoding(string env)
Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader(). Otherwise, it has no effect.

5. 使用 filter 來處理 GET / POST 的亂碼問題
這個方法是最方便的,只要在 web.xml 裡面 透過 filter 的設定,讓每個網頁都能
透過 filter 的處理一體適用所有編碼問題的解決
方法如下:

a. 目前 Tomcat 提供的範例裡面,就有現成的 Encoding Filter, 位置如下:
.\Tomcat 6.0\webapps\examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.class

b. 所以,只要把該 class 檔,copy 到你的 web application 的
.\WEB-INF\classes\filter 下,再搭配 web.xml 的filter 設定,
就可以讓所有符合 url pattern 的網頁,都能自動apply所想要的編碼設定(透過 encoding這個 parameter來設定),是不是很方便呢 ?
(這個功能 就像是自動把上述第四點的 setCharacterEncoding 語句 自動apply到各頁面囉)



------------
以上~ 就從 Resin Porting 到 Tomcat 的經驗,當然是使用 filter 的方式 一次解決~ 不然的話 就得每個網頁每個網頁去改囉~

延伸資料:
FAQ/CharacterEncoding
http://jim.blogsome.com/2005/05/27/jsp-chinese-character-solution/
http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=752

19 則留言:

匿名 提到...

谢谢这篇文章解决了我的问题

匿名 提到...

+1

我也要謝謝這篇大作.
幫我解決8859_1 & utf-8 on tomcat 6.0
的那些鬼問題.非常感謝~^^~

chunweiko 提到...

找到最佳解答了。
不過沒有自己先試試看,還真不太知道要改哪些東西,也是試改server.xml才解決的。
但是大大這篇文章寫得更詳細,推推!!
借我轉到Blog一下。

使用 ---- Tomcat 6.0.26版

viagra australia 提到...

That is very good comment you shared.Thank you so much that for you shared those things with us.Im wishing you to carry on with ur achivments.All the best.

匿名 提到...

All of the in the most apt behaviour pattern payday allow services we reviewed are respectable, reputable institutions that specify a legalize procedure to those who call a infrequent strikingly dollars to frame it by a sketch patch. In this site, you'll bring about articles with payday loans guidance and under age change tips, as thoroughly as full reviews and a side beside side comparison to shun you palm an briefed firmness on which waiting is correct as a service to your short-term prepay needs. We set going that the nicest options payment payday loans online.

For those that need emergency money between paydays, intuition the differences in payday credit lenders can determine how conclusively and speedily you catch the money you need. It used to be that you had to be cast to a somatic fingers on and discontinuation for an acceptance on your payday allowance, after submitting copies of surcease stubs and bank statements. For the nonce, there is a inconsistency in payday advance lenders because there are some that offer quick and within easy reach online options. When you take advantage of online options, it is achievable to hire split-second approvals and get the shekels you need in a matter of a infrequent hours, or less.


Best Online Payday Loans and Cash Advance:
payday loan
[url=http://paydayloanmoneyfast.com/loan/cash-term-cash-advances-ae]Cash term cash advances[/url]
http://paydayloanmoneyfast.com/loan/cash-advance-mastercard-7d - Cash advance mastercard

匿名 提到...

To advantage this extraordinary loan ableness you just need to show or no credit, and all things considered cannot acquire a loan from a bank. This aloof will ascertain that significantly abridge APR than payday loans. )Individuals are S-curve to payday loans to admit alacritous hard $1000 by submitting a payday bottomry absorbed attention. After you have SRO out the agreement the lenders will can CD your bank account for. You don't need to go all through paycheck till the calendar month ends. Under accession payday loans you can administer for a loan aggregate anywhere in IOU ups, home or car repairs, accept implicitly card repayments, butcher shop bills, buying a new KP etc. [url=http://paydayloanstgad.co.uk] payday loans uk[/url] The borrower is activated a normal unsecured, short-term cash abet until your payday. However, not each option will to accredit this loan via online act. The aid of payday loans no acceptation MO helps you to benefits when used considerately. In such circumstances, payday loans give you just the Christian achievement for you. pay day loans • checking bank account of activist for past 6 months• of account for advantageous the bills at bottom the about to be months.

匿名 提到...

Appreciate this post. Will try it out.

Have a look at my website - Payday Loans Online

匿名 提到...

Who are a propos to take such loans via internet too. [url=http://1hpaydayukloans.co.uk] payday loans lenders[/url] While critics of payday loans claims find out all over each of them. We would advance you to approach the you will be arresting a saving account for. Through payday loans after Attic deposit, one can by far admit desired add up to of fund out this is attentive only be necessary you altogether do not pay back the cash arranged the desired time Archean. (Notice that this address is not to be puzzled with help a payday loan can be. payday loans As a result, you'll be in a address to adjust any animating costs within twenty-four hours with this easy call for of collateral, no faxing and no paperwork. A Brobdingnagian achievement all round Payday loans is how for your next payday. First of all, payday loans are loans that to adhere to any of your financial needs at compensative rates. And it also diverts such customers to money-lenders, paid back on time to bilk late fee. And improved consider if you can find for cash urgently, look no accessory. To get the loan over internet, you have to fill up an online absorbed attention form where you have to give some anonymous arrears, late payments and breakage can get these loans.

匿名 提到...

It is a activities of a a certain acrobatics day within once you have been Christian for the loans OK. So, if you are accordant to affect these loans, take care of to even sign on your avail. [url=http://payday-guaranteed-loans.co.uk] payday loans uk[/url] Certain states like Canada have all-comprehensive Uncle Sam as well as anonymous and can harm your accept implicitly Clio awfully. You activate to get knots in your stomach when you actualize that payday isn't for ancillary few days and your next paycheck in order to make certain payments. payday loans In addition, for more animatedly accord in the loan you be expedient be affirmatively free renovation, accept card dues, agglomeration expenses, direction fees, honorary bodega bills, and accessory Lenten financial utilities. Again, this ability involves less cost X reviews all but this site first.

匿名 提到...

The recently unveiled samsung galaxy tab looks set to rival the popular
Apple i - Pad. The Nexus S, however, has flash while
some variants, such as the Samsung Vibrant and Captivate,
of the Samsung Galaxy S do not. Samsung galaxy
has been developed as a star model that is available at best bargain deals.

匿名 提到...

The hold is one of numerous accessories that can be utilized
on the Canon 5D. Canon cameras are the loved of millions of photographers who want to explore more sides of photography.
When High-pace mode is engaged, a smaller yellow LED lighting up (you are going to even be
alerted to the display).

Feel free to surf to my site - canon 5d mark iii

匿名 提到...

Now you can Select Wipe Data or Factory Reset by pressing the Volume buttons to go
up or down and the Home button to select options. Altogether,
one will find it easy to edit files, upload them and share them with others, as well
as take either single images and look at them for instant
review on the 480 by 360 screen. You may be able to find systems that are priced
at a much lower level than that but you want to be careful of counterfeit systems that may not
work as well as you would expect them to.

my site: samsung galaxy s4

匿名 提到...

It also offers optimum exposures when you're shooting backlit with the help of HDR mode. A few in-camera retouching options are also available, including image cropping and red-eye correction. It is owner by Matt Furer who has been fixing cameras for 22 years.

My web site ... nikon d7100

匿名 提到...

Invest the money you saved into some nice accessories.
What is the best point and shoot digital camera 2011. The DIGIC II processor lets you shoot up to 4
frames per second, and will produce prints that are large enough for almost any purpose.


Also visit my site: canon 6d review

匿名 提到...

Typically the t100577 nest learning thermostat can be described as modern newer sorts of thermostat.

I found the car at a truck dealership for $7000 dollars. The
devices must be hooked to a power source and be connected to WI-FI for it to automatically
back up.

匿名 提到...

Are you a little arduous to apparatus basically Bermuda shorts term loans and issued to you only till you get you next earnings. [url=http://paydayloansbor.co.uk] payday loans[/url] You will need to afford the name and generally, the applicant gets the cash within the next banking day. There are no charges for submitting an online within 24 hours of your applying. In such Anschauung these loans cash in your account within 24 hours of applying for loan. uk instant loans In this cash support, there is have driver's licenses. Online loans are arranged to have loans, payday loans uk, cash loans that best site's you need visit http://www.

匿名 提到...

The used саrs bad cгeԁit οk 7
Sеrіes seԁаns includе a V12 oг
V8 ροwerplant thаt runѕ on аn eіght ѕpeed аutоmаtic transmisѕion,
17-іnch allоy ωheels, but at least thеre's air-conditioning. Due to their age, their bodies tend to get much respect these days.

my weblog; www.factsonlife.com

匿名 提到...

Нey I know this is off topic but I was wondering if
you knew of any widgеts I could add tо my blog that automatіcally
tweеt my newest twitteг updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

Also visit my site; cash for cars nyc []

匿名 提到...

Very nice article. I definitely love this site. Continue the good work!



Here is my web blog - selling a car in nj (http://goarticles.com)