81,094
社区成员
发帖
与我相关
我的任务
分享
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;
public class SetCharacterEncodingFilter implements Filter {
/*
* (非 Javadoc)
*
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 选择使用的字符编码
if (ignore ¦ ¦ (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null) {
request.setCharacterEncoding(encoding);
}
// 将控制权交给下一个Filter
chain.doFilter(request, response);
}
}
/*
* (非 Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter( "encoding ");
String value = filterConfig.getInitParameter( "ignore ");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase( "true "))
this.ignore = true;
else if (value.equalsIgnoreCase( "yes "))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
}
<filter>
<filter-name> SetCharacterEncodingFilter </filter-name>
<filter-class> SetCharacterEncodingFilter </filter-class>
<init-param>
<param_name> encoding </param_name>
<param-value> GBK </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> SetCharacterEncodingFilter </filter-name>
<url_pattern> /* </url_pattern>
</filter-mapping>
/**
* Convert the specified string to an input stream, encoded as bytes
* using the specified character encoding.
*
* Character encoding names can be found at
* IANA.
*
* @param input the string to convert
* @param encoding the encoding to use, null means platform default
* @throws IOException if the encoding is invalid
* @return an input stream
* @since Commons IO 1.1
*/
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
return new ByteArrayInputStream(bytes);
}