Using the servlet Filter-resolves Chinese problems

Source: Internet
Author: User

using the servlet Filter-resolves Chinese problems

(1) Preface:
To resolve the internationalization of Web programs, you must encode characters anywhere using UTF-8. (includes: Database set to: Utf-8,web page also set to: UTF-8)
The advantage of this is that you can solve the problem of more than Chinese character encoding on the web, all character encodings are unified using UTF-8, and the internationalization of language is realized. While saving the data to the
The database also eliminates the problem of coding conversion.

Using the servlet in a JSP or JSF application, we use the servlet filter to encode the conversion, that is, to make the encoding conversion to UFT-8.


(2) Introduction to Servlet and JSP filter filter:

One of the most important new features of the

Servlet API version 2.3 is the ability to define filters for servlet and JSP pages. Filters provide a powerful and standard alternative to nonstandard "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. Filters can be attached to one or more servlet or JSP pages, and can examine request information to access those resources. After that, the filter can make the following choices:
-Invoke the resource in a normal way (that is, call a servlet or JSP page).
-invokes the resource with the modified request information.
-invokes the resource, but modifies it before sending the response to the client
-blocks the resource from being invoked, replacing it with another resource, returning a specific status code, or generating a replacement output. The
filter provides several important benefits.
     First, it encapsulates public behavior in a modular or reusable fashion. You have 30 different Serlvet or JSP pages that need to compress their content to reduce download time. No problem: Construct a compression filter (see section 11th) and apply it to 30 resources.
    Second, it enables the separation of advanced access decisions from the presentation code. This is particularly valuable for JSPs, which generally want to focus almost the entire page on performance rather than on business logic. For example, you want to block access from some sites without modifying the pages that are subject to access restrictions. No problem: Create an Access restriction filter (see section 8th) and apply it to the page you want to restrict access to.
    Finally, filters allow you to make bulk changes to many different resources. You have a lot of existing resources, and these resources, in addition to the company name to change the other things remain unchanged, can do it. No problem: Construct a string substitution filter (see section 10th) and use it whenever appropriate.
    Note, however, that filters are only useful for servers that are compatible with the Servlet specification version 2.3. If your Web application needs to support legacy servers, you cannot use filters.

Setting up a filter involves the following five steps:
1. Create a class that implements the filter interface. This class requires three methods, namely: Dofilter, Init, and destroy. The Dofilter method contains the main filtering code, the Init method establishes the setup operation, and the Destroy method is clear.
2, in the Dofilter method into the filter behavior. The first parameter of the Dofilter method is the ServletRequest object. This object provides the filter with full access to 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, which is used to invoke the servlet or JSP page as described in the next step.
3, call the Filterchain object Dofilter method. The Dofilter method of the filter interface takes a Filterchain object as one of its parameters. Activates the next associated filter when calling the Dofilter method of this object. If no other filter is associated with a servlet or JSP page, the servlet or JSP page is activated.
4. Register filters for the corresponding 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 filter settings with 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
are: Filter and filter-mapping. The filter element registers a filter object with the system, and the filter-mapping element specifies the URL to which the filter object applies. The
1.filter element
Filter element is located in the front of the deployment descriptor file (Web.xml), before all filter-mapping, servlet, or servlet-mapping elements. The filter element has the following six possible child elements:
:icon  This is an optional element that declares an image file that the IDE can use.
:filter-name  This is a required element, which assigns a selected name to the filter.
:d isplay-name  This is an optional element that gives the short name used by the IDE.
:d escription  This is also an optional element that gives information about the IDE and provides a text document.
:filter-class  This is a required element that specifies the fully qualified name of the filter implementation class.
:init-param  This is an optional element that defines the initialization parameters that can be read using the Filterconfig Getinitparameter method. A single filter element can contain multiple init-param elements.

2.filter-mapping element
The filter-mapping element precedes the Serlvet element after the filter element in the Web.xml file. It contains the following three possible child elements::
: Filter-name This required element must match the name given to the filter when declared with the filter element.
: Url-pattern This element declares a pattern that starts with a slash (/) that specifies the URL to which the filter applies. Url-pattern or servlet-name must be provided in all filter-mapping elements. However, you cannot supply multiple Url-pattern element items to a single filter-mapping element. If you want the filter to be suitable for more than one pattern, repeat the entire filter-mapping element.
: Servlet-name This element to give a name that must match the name of the servlet or JSP page that was given the servlet element. You cannot supply multiple servlet-name element items to a single filter-mapping element. Repeat this filter-mapping element if you want the filter to be appropriate for multiple servlet names.


(3) The establishment of character conversion filters in rational application Developer:

1. New-web-filter: Setcharacterencodingfilter

will produce the following code in the 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"); Set font encoding to UTF-8
Arg2.dofilter (arg0, arg1);//pass control to next filter
}

3. Deployment in Web.xml

In the Web.xml filter-Editor Select: servlet mapping-add-Faces servlet
will produce the following code in the Web.xml:
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<servlet-name>faces servlet</servlet-name>
</filter-mapping>


(4) Other reference information

The complete solution of Tomcat under Chinese

(a) jsp page is Chinese, but see is garbled after:
The solution is to <%@ page language= "java" contenttype= "TEXT/HTML;CHARSET=GBK" in the code of the JSP pages, because the encoding problem when the JSP turns into a Java file, By default, some servers are iso-8859-1, if a JSP directly into the Chinese, JSP as a iso8859-1 to deal with is certainly problematic, this, we can see Jasper generated by the Java intermediate file to confirm
(b) When using the request object to obtain the customer submitted Chinese character code, there will be garbled:
The solution is: To configure a filter, which 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 is used in parsing the
* 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 is used to
* Interpret request parameters for this request.
*/
public void Dofilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {

Request.setcharacterencoding ("GBK");

Pass control to next filter
Chain.dofilter (request, response);
}

public void init (Filterconfig 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're still in this situation, you're going to go down and see if it's you. Fourth, your form submitted by the data is not submitted with get, generally speaking with post is not a problem, if so, you look at the fourth solution.
There is the processing of information containing Chinese characters, the processing code is:
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 make a direct conversion, first you encode the acquired string with Iso-8859-1, then store the encoding in a byte array, and then convert the array to a string object, for example:
String str=request.getparameter ("Girl");
Byte b[]=str.getbytes ("iso-8859-1");
Str=new String (B);
Any information submitted will be displayed correctly with the above conversion.
(iii) Request at the service end in Formget requests. The GetParameter ("name") is returned with garbled characters, and the filter set by Tomcat is not used or request.setcharacterencoding ("GBK"); Or whether the problem is with the method of handling parameter passing: If you are working with the doget (HttpServletRequest request, HttpServletResponse Response) method in the servlet, even if you write it in front of you:
Request.setcharacterencoding ("GBK");
Response.setcontenttype ("TEXT/HTML;CHARSET=GBK");
Also do not work, the return of Chinese or garbled ... If you change this function to Dopost (httpservletrequest request, httpservletresponse response) everything is OK.
Similarly, in the two JSP page processing form input is able to display Chinese because the Post method is used to pass, the change to get method is still not.
This shows that in the servlet using the Doget () method or in the JSP using the Get method to pay attention to. This, after all, involves passing parameter information through the browser, which is likely to cause conflicts or mismatches in common character sets.
The solution is:
1 Open Tomcat's Server.xml file, locate the block, and add the following line:
Uriencoding= "GBK"
The complete should read as follows:
<connector port= "8080" maxthreads= "minsparethreads=" maxsparethreads= "a" enablelookups= "false" Redirectport= "8443" acceptcount= "debug=" 0 "connectiontimeout=" 20000 "disableuploadtimeout=" true "URIEncoding=" GBK "/>

2 Restart Tomcat, all OK.
Need to join the reason you can go to study $TOMCAT _home/webapps/tomcat-docs/config/http.html under the document can know why. Need to note: This place if you use UTF-8 when in the process of passing in Tomcat is also to appear garbled situation, if not, then change other character sets.

(four) JSP page has Chinese, the button above also has Chinese, but through the server to view the page when there are garbled:
The solution is: first in the JSP file should not directly include localized message text, but should be through the <bean:message> tag from resource bundle to get the text. You should put your Chinese text into the application.properties file, this file is placed under web-inf/classes/*, for example, I have a name on the page, age two label, I first is to build a application.properties, the contents should be Name= "name" age= "age", and then I put this file under Web-inf/classes/properties/, Next, according to the application.properties file, encode and convert him, create a Chinese resource file, assuming the name is application_cn.properties. The NATIVE2ASCII command is provided in the JDK, which enables the conversion of character encodings. In the DOS environment, locate the directory where you placed the Application.properties file, execute the command in the DOS environment, and generate the GBK encoded Chinese resource file Application_ CN.PROPERTIES:NATIVE2ASCII encoding GBK application.properties application_ Cn.properties execution of the above command will generate the following application_cn.properties file: name=/u59d3/u540d age=/u5e74/u9f84, Configure in Struts-config.xml: <message-resources parameter= "Properties. Application_cn "/>. To this step, basically completed the half, and then you will be on the JSP page to write the <%@ page language= "java" contenttype= "TEXT/HTML;CHARSET=GBK"%&GT;, the label to the name is to write <bean:message key= "name", such as the appearance of the page will appear in Chinese name, age this is the same, the button on the processing of Chinese characters is the same.
(v) Writing to the database is garbled:
The solution: To configure a filter, which is a servelet filter, the code is the same as the second.
If you are directly linked to the database through JDBC, configure the code as follows: JDBC:MYSQL://LOCALHOST:3306/WORKSHOPDB?USEUNICODE=TRUE&AMP;CHARACTERENCODING=GBK, This ensures that the code in the database is not garbled.
If you're using a data source link you can't write like this, first you're going to be writing in a configuration file, where you configure the data source in Tomcat 5.0.19 under C:/tomcat 5.0/conf/catalina/localhost, The project I built is workshop, the directory is placed below WebApp, workshop.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.BasicDataSourceFactory</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>
Bold places to pay special attention to, and JDBC Direct link when there is a difference, if you are configured correctly, when you enter Chinese in the database is Chinese, there is a point to note that you are displaying the data page is also to use <%@ page language= "Java" Contenttype= "TEXT/HTML;CHARSET=GBK"%> this line of code. It should be noted that some of the front desk staff in the writing code is written in Dreamver, wrote a form when he changed to a JSP, so there is a place to pay attention to, that is the action in the dreamver of the submission method is request, you need to bring him over, Because in the process of submitting a JSP is a very tight post and get two ways, but the two ways the code submitted in the coding aspect is still very different, this is explained in the following place. 3

Above is I in the development system solves the Chinese question, does not know can solve everybody's question, the time is hurried, does not have the timely consummation, the writing is also not very good, some places estimate is not to be lied to. Everyone can give me advice and hope to make progress together.

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.