JSP三种中文解决方案及区别

来源:互联网 发布:淘宝代销保证金 编辑:程序博客网 时间:2024/05/21 17:47


方法一:只是针对某一个字符串起作用
String name=request.getParameter("name");
name=new String(name.getBytes("ISO-8859-1"),"utf-8");


方法二:针对当前页面有效
request.setCharacterEncoding("gbk");
String  name=request.getParameter("name");

方法三:针对真个web站点有效
采用过滤器原理

  1. public class SetEncodingFilter implements Filter {
  2.     protected String encoding = null;
  3.     protected FilterConfig filterConfig = null;
  4.     protected boolean ignore = true;
  5.     public void destroy() {
  6.         this.encoding = null;
  7.         this.filterConfig = null;
  8.     }
  9.     public void doFilter(ServletRequest request, ServletResponse response,
  10.             FilterChain chain) throws IOException, ServletException {
  11.         if (ignore || (request.getCharacterEncoding() == null)) {
  12.             request.setCharacterEncoding(selectEncoding(request));
  13.         }
  14.         chain.doFilter(request, response);
  15.     }
  16.     public void init(FilterConfig filterConfig) throws ServletException {
  17.         this.filterConfig = filterConfig;
  18.         this.encoding = filterConfig.getInitParameter("encoding");
  19.         String value = filterConfig.getInitParameter("ignore");
  20.         if (value == null)
  21.             this.ignore = true;
  22.         else if (value.equalsIgnoreCase("true")
  23.                 || value.equalsIgnoreCase("yes"))
  24.             this.ignore = true;
  25.         else
  26.             this.ignore = false;
  27.     }
  28.     protected String selectEncoding(ServletRequest request) {
  29.         return (this.encoding);
  30.     }
  31.     public FilterConfig getFilterConfig() {
  32.         return filterConfig;
  33.     }
  34.     public void setFilterConfig(FilterConfig filterConfig) {
  35.         this.filterConfig = filterConfig;
  36.     }
  37. }

web.xml

  1.         <filter>
  2.         <filter-name>SetCharsetEncodingFilter</filter-name>
  3.         <filter-class>filter.SetEncodingFilter</filter-class>
  4.         <init-param>
  5.             <param-name>encoding</param-name>
  6.             <param-value>gbk</param-value>
  7.         </init-param>
  8.     </filter>
  9.     <filter-mapping>
  10.         <filter-name>SetCharsetEncodingFilter</filter-name>
  11.         <url-pattern>/*</url-pattern>
  12.     </filter-mapping>


原创粉丝点击