代码如下:
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 CharacterFilter implements Filter {
String encoding
= null
;
@Override
public void destroy() {
encoding
= null
;
}
@Override
public void doFilter(ServletRequest request
, ServletResponse response
,
FilterChain chain
) throws IOException
, ServletException
{
if (encoding
!= null
) {
request
.setCharacterEncoding(encoding
);
response
.setContentType("text/html;charset=" + encoding
);
}
chain
.doFilter(request
, response
);
}
@Override
public void init(FilterConfig filterConfig
) throws ServletException
{
encoding
= filterConfig
.getInitParameter("encoding");
}
}
xml的配置:
<filter
>
<filter-name
>CharacterFilter
</filter-name
>
<filter-class
>filter.CharacterFilter
</filter-class
>
<init-param
>
<param-name
>encoding
</param-name
>
<param-value
>UTF-8
</param-value
>
</init-param
>
</filter
>
<filter-mapping
>
<filter-name
>CharacterFilter
</filter-name
>
<url-pattern
>/*
</url-pattern
>
</filter-mapping
>
转载请注明原文地址:https://ipadbbs.8miu.com/read-3522.html