Java--get请求中文乱码问题解决!

一、使用过滤器(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;
import javax.servlet.http.HttpServletResponse;

public class SetCharacterEncodingFilter implements Filter{

	private String encoding="utf‐8";
	private boolean ignore=true;

	
	@Override
	public void destroy() {
		encoding=null;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if (this.ignore && (request.getCharacterEncoding() == null)) {
			if (encoding!=null) {
				request.setCharacterEncoding(encoding);
				response.setCharacterEncoding(encoding);
				System.out.println("doFilter");
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String encoding= filterConfig.getInitParameter("encoding");
		String ignore= filterConfig.getInitParameter("ignore");
		if (encoding!=null && !"".equals(encoding)) {
			this.encoding=encoding;
		}
		if (ignore!=null) {
			try {
				this.ignore=Boolean.valueOf(ignore);
			} catch (Exception e) {
				}
		}
		System.out.println("init");
	}
	
}

然后在web.xml中配置字符编码过滤器

<filter>
  	<filter-name>SetCharacterEncodingFilterfilter-name>
  	<filter-class>com.wuchaun.filter.SetCharacterEncodingFilterfilter-class>
  	<init-param>
  		<param-name>encodingparam-name>
  		<param-value>utf‐8param-value>
  	init-param>
  	<init-param>
  		<param-name>ignoreparam-name>
  		<param-value>trueparam-value>
  	init-param>
  filter>

二、修改tomcat的server.xml,在如图所示的位置添加 URIEncoding=“UTF‐8”(重点)
在这里插入图片描述

你可能感兴趣的:(小记,过滤器,乱码,web.xml,filter,servlet)