jsp乱码2

(转载 OursBlanc 北极熊)

原先从没有重视乱码,因为我总以为java已经完美的解决了这个问题,而且在以前的jsp参数传递中也从没有出现过乱码。但,问题还是存在的,这两天的界面突然不能显示中文。什么 charset="GB2312"啦,什么<meta>了,什么request.setCharactorEncoding()啦,都试过了,还是不行。从网上搜了半天,也都是上面几种解决方法。这样最郁闷了:从百度里输入“jsp乱码”,哗哗,一大堆,真高兴,可是点开才知道,表面现象下的残酷。都不是我遇到的这种情况。

         唉,最后只好强制转换了……String str=new String(request.getParameter("productName").getBytes("ISO-8859-1"),"GB2312");       好大一串!! 不得以,还是加上了个servlet过滤器:

package servlet;

import java.io.IOException;
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.UnavailableException;

public class ChangeTypeFilter implements Filter {
 protected String encoding = null;
 protected FilterConfig filterConfig = null;
 protected boolean ignore = true;

 public void destroy() {
  this.encoding = null;
  this.filterConfig = null;
 }

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {

 // 设置正确的编码方式
 if (ignore || (request.getCharacterEncoding() == null)) {
  String encoding = selectEncoding(request);
  if (encoding != null)
   request.setCharacterEncoding(encoding);
 }

 // 传递到下一层过滤器
 chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException {

 this.filterConfig = filterConfig;
 this.encoding = filterConfig.getInitParameter("encoding";
 String value = filterConfig.getInitParameter("ignore";
 if (value == null)
  this.ignore = true;
 else if (value.equalsIgnoreCase("true")
  this.ignore = true;
 else if (value.equalsIgnoreCase("yes")
  this.ignore = true;
 else
  this.ignore = false;

}

protected String selectEncoding(ServletRequest request) {
 return (this.encoding);
}

}



  编好了过滤器之后,还要在TOMCAT中配置过滤器。

      打开WEB-INF目录下的web.xml文件,添加下面的内容:

<filter>
 <filter-name>Set Character Encoding</filter-name>
 <filter-class>servlet.ChangeTypeFilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>GB2312</param-value>
 </init-param>
</filter>

<filter-mapping>
 <filter-name>Set Character Encoding</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>



你可能感兴趣的:(tomcat,jsp,Web,servlet,百度)