史上最全面的前后台传参数、乱码问题解决

1、前台后台转码方案

描述:使用get请求和地址栏请求时,传递中文参数会出现乱码问题,我感觉这是最有效的解决方法。
解决:
前台传参之前转码:

//在name包含中文时,请求之前进行三次编码
var name =  encodeURI(encodeURI(encodeURI($('#name').val())));
var url = "chooseLike?name="+name;
location.href= url;

后台接收时

//接收时 tomcat会进行一次解码操作,只需要再解码两次
String name = java.net.URLDecoder.decode(java.net.URLDecoder.decode(name,"UTF-8"),"UTF-8"));

2、ssm项目xml配置

web.xml 中***web-app*** 标签下添加过滤器配置
此方法对路径传中文参数无效。。。。


  <filter> 
       <filter-name>characterEncodingFilterfilter-name> 
       <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> 
       <init-param> 
           <param-name>encodingparam-name> 
           <param-value>UTF-8param-value> 
       init-param> 
       <init-param> 
           <param-name>forceEncodingparam-name> 
           <param-value>trueparam-value> 
       init-param> 
   filter> 
   <filter-mapping> 
       <filter-name>characterEncodingFilterfilter-name> 
       <url-pattern>/*url-pattern> 
   filter-mapping>

3. 字符过滤器

定义自定义过滤器,设置编码
1.定义过滤器 CharacterFilter.java


public class CharacterFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		chain.doFilter(request, response);
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

}

2.在web.xmlweb-app 标签下添加过滤器配置


	<filter>
		<filter-name>Characterfilter-name>
		<filter-class>com.data.order.filter.CharacterFilterfilter-class>
	filter>
	<filter-mapping>
		<filter-name>Characterfilter-name>
		<url-pattern>/*url-pattern>
	filter-mapping>

4、通过request请求,获取并设置编码

后台接收数据时转码 new String()

String fileName = new String(request.getParameter("fileName").getBytes("iso-8859-1"),"utf-8");

你可能感兴趣的:(java,框架)