当前位置: 代码迷 >> Web前端 >> URL乱码有关问题处理
  详细解决方案

URL乱码有关问题处理

热度:141   发布时间:2012-11-25 11:44:31.0
URL乱码问题处理
首先是过滤器,通过过滤器可以设置所有的post请求
<filter>
        <filter-name>struts2</filter-name>
        <filter-class>info.frady.filter.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

此代码重写了struct2的过滤器,可以将struct2的过滤器直接用此替换

此过滤器的代码如下
package info.frady.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

public class FilterDispatcher extends StrutsPrepareAndExecuteFilter {
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String url = httpRequest.getRequestURI();
			super.doFilter(request, response, filterChain);
	}
}


以上处理后,所有的post请求都OK了,那么get请求的链接确实需要传递中文,怎么处理
自己手动加下编码处理下,以下为工具类
package info.frady.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class UrlUtil {
	public static final String encode(String s, String encoding) {
		try {
			return URLEncoder.encode(s, encoding);
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}
	public static final String dncode(String s, String encoding) {
		try {
			return URLDecoder.decode(s, encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return s;
		}
	}
	public static final String encodeDefault(String s) {
		try {
			return URLEncoder.encode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return s;
		}
	}
}



在使用的使用,自己拼接url为UrlUtil.encodeDefault(userName)
这样url就被编码成类似这样%E4%B8%AD%E6%96%87

然后,还有然后,需要配置下tomcat
<Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="UTF-8" />


以上所说的仅为utf8,如果你的项目为GBK,请对照修改响应的文件。
  相关解决方案