@
目录过滤器处理乱码问题
public class CharFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
web.xml配置
<filter> <filter-name>charfilter</filter-name> <filter-class>com.workhah.filter.CharFilter</filter-class> </filter> <filter-mapping> <filter-name>charfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
ssm项目使用了过滤器发现所有网页都出现了404错误。
首先,你要明白过滤器的原理。过滤器执行完 chain.dofilter(req,resp) 后,放行到你所在的 servlet 或 jsp ,执行完 servlet 或者 jsp 后,或重新回到过滤器执行完剩余代码,要是你在剩余代码中又有请求发出,程序就会发生发出多次请求错误。
总的来说,就是 chain.dofilter(req,resp) 下面的代码不能有请求,如果有,请加上 return。
用 springmvc 包下的过滤器
<!--encodingFilter--> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>