About using a Filter filter in the Struts framework to solve the Chinese character encoding problem

xiaoxiao2021-03-06  39

A simple question, as long as two steps can be.

1. At the beginning of Web.xml, add a statement on the Filter filter, specify the class used by the filter, the encoding to use, and the scope of scope of the filter

:

setENCODING

Classic COM.YOURCompany.struts.Filterencoding for filters

Encoding

Specify the code GBK

setENCODING

Effective path / *

Note that the value of of the two places is the same as the Servlet's statement.

2. Filter class Filterencoding writing:

Note: Implement the Javax.Servlet.Filter interface, rewrite three methods: (Init (FilterConfig FilterConfig), Dofilter (ServletRequest Request, ServletResponse Response, Filterchain Chain), Destroy ())

It is mainly to obtain the encoding to be used from the web.xml, and then set the request to the acquired encoding type. The sample code is as follows:

Package com.Yourcompany.struts;

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;

/ **

* @Author n-liang

*

* Todo to change the Template for this generated Type Comment Go To to

* WINDOW - Preferences - Java - Code Style - Code Templates

* /

Public class filterencoding usments filter {

Private filterconfig filterfig = null;

PRIVATE STRING ENCODING = NULL;

/ * (non-javadoc)

* @see javax.servlet.filter # init (javax.servlet.filterConfig)

* /

Public void init (filterconfig filterconfig) throws servletexception {this.filterconfig = filterconfig;

this.encoding = filterconfig.getinitParameter ("encoding");

}

/ * (non-javadoc)

* @see javax.servlet.filter # DOFILTER (javax.servlet.servletRequest, javax.servlet.servletResponse, javax.servlet.filterchain)

* /

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

String encoding = this.encoding;

IF (Encoding! = NULL)

{

Request.setCharacterencoding (Encoding);

}

Chain.dofilter (Request, Response);

}

/ * (non-javadoc)

* @see javax.servlet.filter # destroy ()

* /

Public void destroy () {

THIS.Encoding = NULL;

THIS.FILTERCONFIG = NULL;

}

}

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

New Post(0)