1.在jsp页面上输入中文,请求页面不出现乱码
①保证ContentType="text/html;charset=utf-8" 与 pageEncoding="utf-8"一致
②保证浏览器显示的字符编码也和请求的jsp页面的编码一致
2.获取中文的参数值(默认参数在传输过程中使用的编码为ISO-8859-1)
①对于post请求:只要在获取请求之前调用request.setCharacterEncoding("utf-8")就可以
②对于get请求:前面的操作无效
此时要修改Tomacat的配置文件Server.xml的内容,查找Connector节点,添加useBodyEncodingForURI="true"
同时在myelipse或者eclipse中的server.xml中也要做同样的修改,然后重启服务器。
3.设置中文乱码的过滤器EncodingFilter
①在配置文件web.xml中设置:
<context-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </context-param> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.atguigu.bookstores.filters.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
②过滤器代码如下:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String encoding=filterConfig.getServletContext().getInitParameter("encoding"); request.setCharacterEncoding(encoding); chain.doFilter(request, response); } private FilterConfig filterConfig=null; public void init(FilterConfig fConfig) throws ServletException { this.filterConfig=fConfig; }