1. 程式人生 > 實用技巧 >SpringMVC之解決中亂碼

SpringMVC之解決中亂碼

1、在web.xml中配置一個CharacterEncodingFilter

 <!--因為有快取的關係,解決中文亂碼的過濾器必須要配置在所有過濾器的最前面-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!--encoding的值是固定的,因為它是CharacterEncodingFilter中的一個屬性-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  

2、CharacterEncodingFilter原始碼如下

public class CharacterEncodingFilter extends OncePerRequestFilter {
	@Nullable
        // web.xml中<param-value>對應的值
	private String encoding;

	private boolean forceRequestEncoding = false;

	private boolean forceResponseEncoding = false;

	public CharacterEncodingFilter() {
	}

	public CharacterEncodingFilter(String encoding) {
		this(encoding, false);
	}

	public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
		this(encoding, forceEncoding, forceEncoding);
	}

	public CharacterEncodingFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
		Assert.hasLength(encoding, "Encoding must not be empty");
		this.encoding = encoding;
		this.forceRequestEncoding = forceRequestEncoding;
		this.forceResponseEncoding = forceResponseEncoding;
	}

	public void setEncoding(@Nullable String encoding) {
		this.encoding = encoding;
	}

	@Nullable
	public String getEncoding() {
		return this.encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceRequestEncoding = forceEncoding;
		this.forceResponseEncoding = forceEncoding;
	}

	public void setForceRequestEncoding(boolean forceRequestEncoding) {
		this.forceRequestEncoding = forceRequestEncoding;
	}

	public boolean isForceRequestEncoding() {
		return this.forceRequestEncoding;
	}

	
	public void setForceResponseEncoding(boolean forceResponseEncoding) {
		this.forceResponseEncoding = forceResponseEncoding;
	}

	public boolean isForceResponseEncoding() {
		return this.forceResponseEncoding;
	}

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String encoding = getEncoding();
		if (encoding != null) {
			if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
				request.setCharacterEncoding(encoding);
			}
			if (isForceResponseEncoding()) {
				response.setCharacterEncoding(encoding);
			}
		}
		filterChain.doFilter(request, response);
	}
}