您的位置:首页 > 编程语言 > Java开发

关于java的编码问题,个人的一个补充

2005-09-19 23:00 696 查看
java的编码问题,这里特指web方案的问题
一定要随时注意编码的改变情况,一般的都是form,url到request,以及数据库的另种转化操作,这些,在其它网上有能找到不再说了.
我只要用了一个过滤器来完成上述工作
public class CharacterEncodingFilter implements Filter {
  /**
  * The default character encoding to set for requests that pass through
  * this filter.
  */
  protected String encoding = null;
/**
  * The filter configuration object we are associated with. If this value
  * is null, this filter instance is not currently configured.
  */
  protected FilterConfig filterConfig = null;
/**
  * Should a character encoding specified by the client be ignored?
  */
  protected boolean ignore = true;
public void init(FilterConfig filterConfig) throws javax.servlet.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;
}
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, javax.servlet.ServletException {
    // Conditionally select and set the character encoding to be used
    if (request.getCharacterEncoding() == null) {
      String encoding2 = selectEncoding(request);
      if (encoding2 != null)
        request.setCharacterEncoding(encoding2);
  }
// Pass control on to the next filter
    chain.doFilter(request, response);
}
  public void destroy() {
    this.encoding = null;
    this.filterConfig = null;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
在web.xml里
<filter>
    <filter-name>CharacterEncoding</filter-name>
    <filter-class>com.rising.common.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GBK</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <servlet-name>*.do</servlet-name>
  </filter-mapping>
...
<url-pattern>*.jsp</url-pattern>
相关url的模式,不再详细解析了
这里还有一个,当里在直接在页面里用
<a href="err.jsp?msg=错误">aaa</a>
这里链接过去是正确的
但在servlet里用response.sendRedirect("err.jsp?msg=错误");就是出现乱码
这个东东花了我好长时间没有搞定,最乱静下心来想想,原因如下:
超级链接方式的中文:[code]<a href="err.jsp?msg=错误">aaa</a>,如者直接在浏览器地址里输入的url信息,最后是能过我的过滤器经过GBK编号后进来request的
而在response.sendRedirect("err.jsp?msg=错误");的中文信息是代码直接进入,并没有通过GBK编码
而在err.jsp页面读err信息时,又用过滤器的GBK解码,故没有相对应,所以出错了.
总结:servlet中直接用response.sendRedirect(url)中url有中文信息,必须要手动编码,这时过滤器并不会给你这里的代码编码的

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: