ajax post 请求乱码

项目总体编码都为:GBK
过滤器JAVA代码
package com.sunstar.sos.filter;

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;
import javax.servlet.http.HttpServletRequest;


/**
 * 
 * <p>Title: ConditionAction.java</p>
 * 
 * <p>Description: 解决ajax post请求中文乱码filter类 </p>
 * 
 * 
 * @author 
 * @version 1.0
 */
public class RequestEncodingFilter implements Filter {

	/** ajax请求的编码 */
	public final String ajaxEncoding = "utf-8";

	private boolean ignore = false;

	/** url请求参数中用户标志是否是一个ajax请求的标志名称 */
	private String ajaxFlag = "__ajax__";

	public void destroy() {
	}

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

		if (ignore) {
			chain.doFilter(request, response);
			return;
		}

		HttpServletRequest req = (HttpServletRequest) request;

		// 这里不使用getParameter方法,否则会使后续setCharacterEncoding方法失效
		String queryString = req.getQueryString();

		// 如果请求url参数中含有flag(默认为__ajax__),则表明使用ajax请求,则编码设置为utf-8
		if (queryString != null && queryString.indexOf(ajaxFlag) != -1) {
			request.setCharacterEncoding(ajaxEncoding);

			// 调用一次getParameter方法,使得在此之后再调用setCharacterEncoding将会无效
			// (web框架会在之后再调用此方法,但是已经失效)
			// 参数不一定为ajaxFlag,可以是任何值
			request.getParameter(ajaxFlag);
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String value = filterConfig.getInitParameter("ignore");
		ajaxFlag = filterConfig.getInitParameter("ajaxFlag");

		if (ajaxFlag == null) {
			ajaxFlag = "__ajax__";
		}

		if (value == null) {
			ignore = false;
		} else if (value.equalsIgnoreCase("true")
				|| value.equalsIgnoreCase("yes")) {
			ignore = true;
		} else {
			ignore = false;
		}
	}

}



web.xml配置
	<filter>
		<filter-name>requestEncoding</filter-name>
		<filter-class>com.sunstar.sos.filter.RequestEncodingFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>requestEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


ajax请求:actionName.action?__ajax__

你可能感兴趣的:(Web,Ajax,xml,框架,servlet)