乱码是j2ee中一个比较常见的问题。遇到一两个问题的情况下,可以用new String(request.getParameter(xxx).getBytes("ISO-8859-1"),"UTF-8")来解决。遇到多的情况下,就最好用过滤器。
过滤器只需要注意2个地方即可——类和web.xml
1.在web.xml上面的发布如下:
-
- <fileter>
- <!-- 类名 -->
- <filter-name>SetCharsetEncodingFilter</filter-name>
- <!-- 类的路径 -->
- <filter-class>SetCharacter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>utf-8</param-value>
- </init-param>
- <filter-mapping>
- <filter-name>SetCharsetEncodingFilter</filter-name>
- <!-- 设置所有的文件遇到过滤器都要被拦截 -->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </fileter>
复制代码
2、过滤类
-
- 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;
-
- public class SetCharacter implements Filter {
- protected String encoding = null;
- protected FilterConfig filterConfig = null;
- protected boolean ignore = true;
- public void init(FilterConfig arg0) throws ServletException {
- this.encoding = arg0.getInitParameter("encoding");
- String value = arg0.getInitParameter("imnore");
- if (value == null) {
- this.ignore = true;
- } else if (value.equalsIgnoreCase("true")) {
- this.ignore = true;
- } else if (value.equalsIgnoreCase("yes")) {
- this.ignore = true;
- }
- }
-
- public void doFilter(ServletRequest arg0, ServletResponse arg1,
- FilterChain arg2) throws IOException, ServletException {
- if (ignore || (arg0.getCharacterEncoding() == null)) {
- String encoding = selectEncoding(arg0);
- if (encoding != null)
- arg0.setCharacterEncoding(encoding);
- }
- arg2.doFilter(arg0, arg1);
- }
-
- private String selectEncoding(ServletRequest arg0) {
- return (this.encoding);
- }
-
- public void destroy() {
- this.encoding = null;
- this.filterConfig = null;
- }
-
- }
复制代码
在web.xml文件中,以下语法用于定义映射:
1、以“/”开头和以“/*”结尾的是用来做路径映射。
2、以前缀“*.”开头的是用来做扩展映射。
3、以“/”是用来定义default servlet映射。
4、剩下的都是用来定义详细映射。比如:/aa/bb/cc.action
以上就是解决Java J2EE乱码问题的思路,分享给大家,希望大家遇到类似问题可以顺利解决。 |