Use Filter to change the Request's encoding

zhaozj2021-02-11  192

Reprinted please indicate: http://www.9cbs.net/develop/Article/17/17204.shtm

Author: ggyy1977@hotmail.com

Use Filter to change the Request's encoding

In front of the article, we discussed the character encoding problem of JSP and servlet under Tomcat!

Know that when there is no code to specify request, the data obtained from the client is ISO-8859-1 encoded (Request.getParameter () gets the passing parameter value);

But how can we change the Request's encoding?

There are many ways!

For example: at getRequestDispatcher ("/ jsp / jsptoserv / hello.jsp"). Forward (Request, Response);

Request's encoding, then the parameter value obtained in JSP / JSPTOSERV / HELLO.JSP is the formulated character.

This article we use Filter to modify the Request's encoding!

1) Write the Filter class first:

Package myfilter;

Import java.io.ioException; import javax.servlet. *;

Public class changecharsetfilter imports filter {

Protected String Encoding = NULL; / To formulate the encoding, configure protected filterconfig filter in web.xml;

Public void destroy () {

THIS.Encoding = null; this.filterconfig = NULL;

}

Public void Dofilter (ServletRequest Request, ServletResponse Response, Filterchain Chain) throws ioException, servletexception {

IF (Request.getCharacterencoding () == null) {string encoding = getencoding (); get the specified encoded name if (Encoding! = null) Request.setCharacterencoding (Encoding); Setup Code}

Chain.dofilter (Request, Response); // Have the opportunity to execute the next Filter

}

Public void init (filterconfig filterconfig) throws servletexception {

This.filterconfig = filterconfig; this.encoding = filterconfig.getinitParameter ("eNCoding"); // get encoding in Web.xml}

protected string getencoding () {

Return (this.encoding); // get the specified encoding

}

}

转载请注明原文地址:https://www.9cbs.com/read-4249.html

New Post(0)