filter_setEncoding_note

(1)通过struts内部的RequestProcessor来设置编码。

EncodingHandler.java

package com.test.util;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.RequestProcessor;

public class EncodingHandler extends RequestProcessor
{

	@Override
	protected boolean processPreprocess(HttpServletRequest request,
			HttpServletResponse response)
	{
		try
		{
			//当struts-config.xml中设置了此类的controller,所有请求会先经过这边做处理。
			// <controller processorClass="com.test.util.EncodingHandler"></controller>
			request.setCharacterEncoding("utf-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return true;
	}
	
}

 

(2)通过servlet 的filter来设置编码,更通用。

EncodingServlet.java

package com.test.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.HttpServlet;

public class EncodingServlet extends HttpServlet implements Filter
{
	private static final long serialVersionUID = 1L;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException
	{
		try
		{
			request.setCharacterEncoding("utf-8");
			filterChain.doFilter(request, response);
		}
		catch (Exception ex)
		{
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException
	{

	}

}

 

 

web.xml

 <filter>
  	<filter-name>encodingFilter</filter-name>
	<filter-class>com.test.filter.EncodingServlet</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

 

你可能感兴趣的:(java,apache,xml,struts,servlet)