解决jsp乱码

我喜欢直接的简单:

1.创建一个过滤器,处理 get 提交的方式, 代码如下:

 

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CharacterEncodingFilter implements Filter {
 private FilterConfig config;
 private String encoding = "gbk";

 public void destroy() {
  config = null;
 }

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

  chain.doFilter(request, response);
 }

 public void init(FilterConfig con) throws ServletException {
  this.config = con;
  String s = config.getInitParameter("encoding");
  if (s != null) {
   encoding = s;
  }

 }
}

2.web.xml 配置如下


 <!-- 过滤处理编码格式 -->
 <filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>com.centfor.util.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>gbk</param-value>
  </init-param>
 </filter>

3. 找到 tomcat安装文件夹的 conf/server.xml   增加红色字体的配置  对 post 的表单进行修改

       <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="gbk" />

 

表单的 get 和 post 方式都进行了统一编码 ,这样就不会乱码了

 

注意: 在每个jsp 页面最好不要再进行转码 web工程的编码格式最好统一

 

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