JavaWeb设置字符编码过滤器
一、不用框架时设置字符编码过滤器
代码如下(示例):
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
@WebFilter("*")
public class CharacterEncodingFilter implements Filter {
private String encoding = "utf-8";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String encodingStr = filterConfig.getInitParameter("encoding");
if (!encodingStr.isEmpty()) {
encoding = encodingStr;
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
在初始化时先获取字符编码,然后在doFilter()方法里设置字符编码。
filterChain.doFilter(servletRequest, servletResponse);
这一行是在设置完编码后放行的语句。
二、使用SpringMVC框架设置字符编码过滤器
1. 使用xml配置文件
代码如下(示例):
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
在web.xml中加入这段代码就可以了,在param-value这个标签中可以设计具体的字符编码。
2. 使用配置类
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceResponseEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};
}
}
创建一个继承AbstractAnnotationConfigDispatcherServletInitializer 的类,然后加入这段代码就可以了。