JSP filter solves garbled characters

Source: Internet
Author: User

(1) preface:
To address the internationalization of web programs, character encoding must be performed anywhere using a UTF-8. (Including: Database settings: UTF-8, web pages also need to be set to: UTF-8)
The advantage of doing so is that it can solve the problem of not only Chinese character encoding on the web, all the character encoding are unified use of UTF-8, to achieve the internationalization of the language. While saving the data
The encoding conversion problem is also saved in the database.

Using Servlet in JSP or JSF applications, we use servlet filters for encoding conversion, that is, coding conversion to UFT-8.

(2) Servlet and JSP filters:

One of the most important new functions of servlet API 2.3 is the ability to define filters for servlet and JSP pages. Filters provide a powerful and standard alternative to non-standard servlet links supported by some early servers.
A filter is a program that runs on the server prior to the servlet or JSP page associated with it. The filter can be attached to one or more servlet or JSP pages, and the request information for accessing these resources can be checked. After that, the filter can be selected as follows:
-Call Resources in the conventional way (that is, call servlet or JSP pages ).
-Call resources with modified request information.
-Call the resource, but modify it before sending a response to the client.
-Stop this resource from calling, replace it with another resource, and return a specific status code or generate a replacement output.
Filters provide several important benefits.
First, it encapsulates public behavior in a modular or reusable way. You have 30 different Serlvet or JSP pages. Do you need to compress their content to reduce the download time? No problem: Construct a compression filter (see section 11th) and apply it to 30 resources.
Second, it can be used to separate Advanced Access decisions from presentation code. This is especially valuable for JSP, in which it is generally expected to focus almost the entire page on the performance, rather than on the business logic. For example, do you want to block access from some sites without modifying pages (these pages are subject to access restrictions? No problem: Create an access restriction filter (see section 8th) and apply it to the page to restrict access.
Finally, the filter enables you to make bulk changes to many different resources. You have a lot of existing resources. Can you do this without changing the company name? No problem: Construct a string replacement filter (see section 10th) and use it whenever appropriate.
However, it should be noted that the filter only works on servers compatible with Servlet Specification Version 2.3. If your web application needs to support old-version servers, you cannot use filters.

Creating a filter involves the following five steps:
1. Create a class to implement the filter interface. This class requires three methods: dofilter, init, and destroy. The dofilter method contains the main filtering code. The init method establishes the setting operation, while the destroy method is clear.
2. Put the filtering behavior in the dofilter method. The first parameter of the dofilter method is the servletrequest object. This object provides the filter with full access to the incoming information (including form data, cookies, and HTTP request headers. The second parameter is servletresponse, which is usually ignored in a simple filter. The last parameter is filterchain. As described in the next step, this parameter is used to call the servlet or JSP page.
3. Call the dofilter method of the filterchain object. The dofilter method of the filter interface takes a filterchain object as its parameter. When the dofilter method of this object is called, The next related filter is activated. If no other filter is associated with the servlet or JSP page, the servlet or JSP page is activated.
4. Register a filter for the servlet and JSP pages. Use the filter and filter-mapping elements in the deployment descriptor file (Web. XML.
5. Disable the activator servlet. Prevents users from bypassing the filter settings using the default servlet URL.

Dofilter method:
Public void dofilter (servletrequest request, servletresponse response, filterchain chain)
Throws servletexception, ioexception
{
Httpservletrequest Req = (httpservletrequest) request;
System. Out. println (req. getremotehost () + "tried to access" + Req. getrequesturl () + "on" + new date () + ".");
Chain. dofilter (request, response );
}

Deploy in Web. xml
They are: Filter and filter-mapping. The filter element registers a filter object with the system. The filter-mapping element specifies the URL applied to the filter object.
1. filter element
The filter element is located at the front of the deployment descriptor file (Web. XML), before all the filter-mapping, Servlet, or servlet-mapping elements. The filter element has the following six possible child elements:
: Icon is an optional element that declares an image file that IDE can use.
: Filter-name is a required element. It assigns a selected name to the filter.
: Display-Name: This is an optional element, which provides the short name used by IDE.
: Description is an optional element. It provides ide information and text documents.
: Filter-class: a required element. It specifies the fully qualified name of the filter implementation class.
: Init-Param is an optional element that defines the initialization parameters that can be read using the getinitparameter method of filterconfig. A single filter element can contain multiple init-Param elements.

2. Filter-mapping Element
The filter-mapping element is located before the Serlvet element after the filter element in the web. xml file. It contains the following three possible child elements ::
: The required filter-name element must match the name of the filter given when the filter element is declared.
: URL-pattern this element declares a pattern starting with a slash (/), which specifies the URL of the filter application. URL-pattern or servlet-name must be provided in all filter-mapping elements. However, you cannot provide multiple URL-pattern element items for a single filter-mapping element. If you want the filter to work in multiple modes, you can repeat the entire filter-mapping element.
: Servlet-Name: This element provides a name, which must match the name of the servlet or JSP page given by the servlet element. You cannot provide multiple servlet-name element items for a single filter-mapping element. If you want the filter to be suitable for multiple servlet names, repeat the filter-mapping element.

(3) create a character conversion filter in rational application developer:

1. New-web-filter: setcharacterencodingfilter

The following code is generated in Web. xml:
<Filter>
<Filter-Name> changecodefilter </filter-Name>
<Display-Name> changecodefilter </display-Name>
<Description> </description>
<Filter-class> com. CNC. setcharacterencodingfilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-Name> setcharacterencodingfilter </filter-Name>
<URL-pattern>/setcharacterencodingfilter </url-pattern>
</Filter-mapping>

2. Add the following code to the dofilter method of the filter:

Public void dofilter (servletrequest arg0, servletresponse arg1, filterchain arg2) throws ioexception, servletexception {
Arg0.setcharacterencoding ("UTF-8"); // sets the font encoding to UTF-8
Arg2.dofilter (arg0, arg1); // transfer control to the next Filter
}

3. Deploy in Web. xml

In the Web. xml filter-editor, select servlet ing-add-faces servlet.
The following code is generated in Web. xml:
<Filter-mapping>
<Filter-Name> setcharacterencodingfilter </filter-Name>
<Servlet-Name> faces servlet </servlet-Name>
</Filter-mapping>

(4) other reference information

A thorough solution to Chinese in Tomcat

(1) Chinese characters are displayed on the JSP page, but garbled characters are displayed:
The solution is to encode the JSP page <% @ page Language = "Java" contenttype = "text/html; charset = GBK" %>, because JSP into Java file encoding problem, some of the default server is ISO-8859-1, if a JSP directly input the Chinese, JSP treats it as a ISO8859-1 to deal with is certainly a problem, this can be confirmed by checking the Java intermediate file generated by Jasper.
(2) garbled characters occur when the request object is used to obtain the Chinese character code submitted by the customer:
The solution is to configure a filter, that is, a servelet filter. The Code is as follows:
Import java. Io. ioexception;
Import javax. servlet. filter;
Import javax. servlet. filterchain;
Import javax. servlet. filterconfig;
Import javax. servlet. servletexception;
Import javax. servlet. servletrequest;
Import javax. servlet. servletresponse;
Import javax. servlet. unavailableexception;

/**
* Example filter that sets the character encoding to be used in parsing
* Incoming request
*/
Public class setcharacterencodingfilter implements filter {

/**
* Take this filter out of service.
*/
Public void destroy (){
}
/**
* Select and set (if specified) the character encoding TO BE USED
* Interpret Request Parameters for this request.
*/
Public void dofilter (servletrequest request, servletresponse response,
Filterchain chain) throws ioexception, servletexception {

Request. setcharacterencoding ("GBK ");

// Transfer control to the next Filter
Chain. dofilter (request, response );
}

Public void Init (filterconfig) throws servletexception {
}
}
Configure web. xml
<Filter>
<Filter-Name> set character encoding </filter-Name>
<Filter-class> setcharacterencodingfilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-Name> set character encoding </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>
If you still see this situation, you can see if you have encountered the fourth situation and whether the data submitted by your form is submitted using get, in general, there is no problem in submitting a post statement. If so, let's take a look at the solution in step 4.
The following code processes the information containing Chinese characters:
Package dbjavabean;

Public class codingconvert
{
Public codingconvert ()
{
//
}
Public String togb (string unistr ){
String gbstr = "";
If (unistr = NULL ){
Unistr = "";
}
Try {
Byte [] tempbyte = unistr. getbytes ("iso8859_1 ");
Gbstr = new string (tempbyte, "gb2312 ");
}
Catch (exception ex ){
}
Return gbstr;
}

Public String touni (string gbstr ){
String unistr = "";
If (gbstr = NULL ){
Gbstr = "";
}
Try {
Byte [] tempbyte = gbstr. getbytes ("gb2312 ");
Unistr = new string (tempbyte, "iso8859_1 ");
} Catch (exception ex ){
}
Return unistr;
}
}
You can also directly convert it, first you encode the obtained string with the ISO-8859-1, and then store the encoding into a byte array, then convert the array into a string object. For example:
String STR = request. getparameter ("girl ");
Byte B [] = Str. getbytes ("ISO-8859-1 ");
STR = new string (B );
Any submitted information can be correctly displayed after the preceding conversion.
(3) The formget request is used on the server. when getparameter ("name") is returned, garbled characters are returned. It is useless to set Filter Based on tomcat or request. setcharacterencoding ("GBK"); also, the problem lies in the method for passing the processing parameters. If doget (httpservletrequest request, httpservletresponse response) is used in the servlet) if the method is used for processing, the preceding statements are written as follows:
Request. setcharacterencoding ("GBK ");
Response. setcontenttype ("text/html; charset = GBK ");
It does not work either. The returned Chinese characters are still garbled !!! If you change this function to dopost (httpservletrequest request, httpservletresponse response), everything will be OK.
Similarly, when two JSP pages are used to process form input, the reason why Chinese characters can be displayed is that the POST method is used for transmission, and the get method cannot be used.
It can be seen that you should pay attention to using the doget () method in servlet or the get method in JSP. After all, it involves passing parameter information through the browser, which may cause conflicts or mismatched common character sets.
The solution is:
1) Open the Tomcat server. xml file, locate the block, and add the following line:
Uriencoding = "GBK"
The complete information should be as follows:
<Connector Port = "8080" maxthreads = "150" minsparethreads = "25" maxsparethreads = "75" enablelookups = "false" redirectport = "8443" acceptcount = "100" DEBUG =" 0 "connectiontimeout =" 20000 "disableuploadtimeout =" true "uriencoding =" GBK "/>

2) Restart tomcat. Everything is OK.
You can find out the reason for adding the file $ tomcat_home/webapps/tomcat-docs/config/http.html. It should be noted that this place if you use the UTF-8 in the Process of delivery in Tomcat is also the case of garbled, if not, then change to another character set.

(4) The JSP page contains Chinese characters and buttons, but garbled characters appear when you view the page through the server:
Solution: first, the JSP file should not directly contain localized message text, but be obtained from the resource bundle using the <Bean: Message> tag. Put your Chinese text in application. in the properties file, this file is placed in the WEB-INF/classes/*, for example, I have a name in the page, the age of two labels, I first want to create an application. properties, the content should be name = "name" age = "Age", then I put this file under the WEB-INF/classes/properties/, then according
Application. properties file, encode and convert it, and create a Chinese resource file, assuming the name is application_cn.properties. The native2ascii command is provided in JDK to convert character encoding. In the DOS environment, find the directory of the file where you placed application. properties. In the DOS environment, execute the command to generate a GBK-Encoded chinese resource file application_cn.properties: native2ascii? Encoding GBK application. Properties
Application_cn.properties the application_cn.properties file: Name = \ u59d3 \ u540d age = \ u5e74 \ u9f84 will be generated after the above command is executed, configure in Struts-config.xml: <message-resources parameter = "properties. application_cn "/>. In this step, we have basically finished more than half of it. Then you need to write <% @ page Language = "Java" contenttype = "text/html; charset = GBK" on the JSP page"
%>, The label of the name is to write <Bean: Message key = "name">. When such a label appears on the page, the Chinese name appears, the same is true for age, and the processing of Chinese characters on buttons is the same.
(5) garbled characters are written to the database:
Solution: configure a filter, that is, a servelet filter. The Code is the same as in the second case.
If you directly connect to the database through JDBC, the configuration code is as follows: JDBC: mysql: // localhost: 3306/workshopdb? Useunicode = true & characterencoding = GBK to ensure that the code in the database is garbled.
If you are using a data source link, you cannot follow this method. First, you need to write it in the configuration file. In Tomcat 5.0.19, the data source is configured in C: \ Tomcat 5.0 \ conf \ Catalina \ localhost. The project I created is workshop, and the directory is under webapp, workshop. the xml configuration file is as follows:
<! -- Insert this context element into server. xml -->

<Context Path = "/Workshop" docbase = "Workshop" DEBUG = "0"
Reloadable = "true">

<Resource Name = "JDBC/workshopdb"
Auth = "Container"
Type = "javax. SQL. datasource"/>

<Resourceparams name = "JDBC/workshopdb">
<Parameter>
<Name> factory </Name>
<Value> org. Apache. commons. DBCP. basicperformancefactory </value>
</Parameter>
<Parameter>
<Name> maxactive </Name>
<Value> 100 </value>
</Parameter>
<Parameter>
<Name> maxidle </Name>
<Value> 30 </value>
</Parameter>


<Parameter>
<Name> maxwait </Name>
<Value> 10000 </value>
</Parameter>

<Parameter>
<Name> username </Name>
<Value> root </value>
</Parameter>
<Parameter>
<Name> password </Name>
<Value> </value>
</Parameter>

<! -- Class name for mm. MySQL JDBC driver -->
<Parameter>
<Name> driverclassname </Name>
<Value> com. MySQL. JDBC. Driver </value>
</Parameter>
<Parameter>
<Name> URL </Name>
<Value> <! [CDATA [JDBC: mysql: // localhost: 3306/workshopdb? Useunicode = true & characterencoding = GBK]> </value>
</Parameter>
</Resourceparams>

</Context>
Special attention should be paid to the coarse body, which is different from the direct connection of JDBC. If you are configuring correctly, when you enter Chinese characters, it is Chinese in the database, one thing to note is that you must use this line of code <% @ page Language = "Java" contenttype = "text/html; charset = GBK" %> On the page where the data is displayed. It should be noted that some front-end staff use dreamver to write code after writing a form, and change it to a JSP when writing a form, so there is a place to pay attention, that is, in dreamver, the action submission method is request. You need to submit it, because in the Process of JSP submission, it is closely related to post and
Get methods, but the Code submitted by the two methods is very different in coding. This is explained later.

From:
Http://hi.baidu.com/kayzombie/blog/item/63e664647d9262f8f7365495.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.