Link: http://blog.csdn.net/flyxxxxx/archive/2004/09/10/100319.aspx
Filter file:
Package filter;
Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java.net .*;
Public class characterencoding
Implements filter {
Protected filterconfig = NULL;
Private string encoding = NULL;
Public void destroy (){
Filterconfig = NULL;
Encoding = NULL;
}
Public void dofilter (servletrequest request, servletresponse response,
Filterchain chain) throws ioexception, servletexception {
Httpservletrequest Req = (httpservletrequest) request;
String S = Req. getrequesturi ();
String url = urldecoder. Decode (S, "UTF-8"); // when intertnet options in IE-> advanced options-> always send URLs as UTF-8 is selected.
Int K = URL. indexof ("? ");
String file = (k =-1? URL: URL. substring (0, k ));
File F = new file (filterconfig. getservletcontext (). getrealpath (File ));
If (F. exists () = false ){
Url = new string (S. getbytes ("ISO-8859-1"), encoding); // when a URL sent in UTF-8 is not selected
Url = urldecoder. Decode (URL, encoding );
}
Filterconfig. getservletcontext (). getrequestdispatcher (URL). Forward (req,
Response );
}
Public void Init (filterconfig) throws servletexception {
This. filterconfig = filterconfig;
Encoding = filterconfig. getinitparameter ("encoding ");
}
}
The above code is used for jdk1.4. If jdk1.3 is used, add the following method to the code above and change urlencoder. Decode (...) to decode (...):
Public static string decode (string S, string ENC) throws
Unsupportedencodingexception {
Boolean needtochange = false;
Stringbuffer sb = new stringbuffer ();
Int numchars = S. Length ();
Int I = 0;
If (Enc. Length () = 0 ){
Throw new unsupportedencodingexception (
"Urldecoder: empty string ENC parameter ");
}
While (I <numchars ){
Char c = S. charat (I );
Switch (c ){
Case '+ ':
SB. append ('');
I ++;
Needtochange = true;
Break;
Case '% ':
Try {
Byte [] bytes = new byte [(numchars-I)/3];
Int Pos = 0;
While (I + 2) <numchars )&&
(C = '% ')){
Bytes [POS ++] =
(Byte) integer. parseint (S. substring (I + 1, I + 3 ),
16 );
I + = 3;
If (I <numchars ){
C = S. charat (I );
}
}
If (I <numchars) & (C = '% ')){
Throw new illegalargumentexception (
"Urldecoder: incomplete trailing escape (%) pattern ");
}
SB. append (new string (bytes, 0, POs, ENC ));
}
Catch (numberformatexception e ){
Throw new illegalargumentexception (
"Urldecoder: Illegal hex characters in escape (%) pattern -"
+ E. getmessage ());
}
Needtochange = true;
Break;
Default:
SB. append (C );
I ++;
Break;
}
}
Return (needtochange? SB. tostring (): S );
}
In addition, you must add
Characterencoding
Filter. characterencoding
Encoding
GBK
Characterencoding
/*