在JSP页面中使用 跳转到相应的页面,中文正常显示,但是在Servlet中使用forward跳转到同样的页面,中文却会乱码。尝试了在Servlet中使用setCharacterEncoding,但同样还是乱码,并不能解决问题,后来加了一个过滤器,问题才解决,以下是过滤器代码:
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class EncodingFilter
*/
@WebFilter(filterName="encodingFilter",urlPatterns={"/*"})
public class EncodingFilter implements Filter {
/**
* Default constructor.
*/
public EncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
private String str="UTF-8";
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
//在这里加入下面两行代码
request.setCharacterEncoding(str);
response.setCharacterEncoding(str);
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}