1)过滤器类是一种特殊的Servlet类,可以在请求发给特
定的Servlet类处理之前,先执行过滤器类中的方法,将客户端发送的所有请求中的字符编码转换为utf-8;
定的Servlet类处理之前,先执行过滤器类中的方法,将客户端发送的所有请求中的字符编码转换为utf-8;
<span style="white-space:pre"> </span>
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;<span style="white-space:pre"> </span><pre name="code" class="html"><span style="white-space:pre"> </span>import java.io.IOException;
public class CharacterEncodingFilter implements Filter{private FilterConfig filterConfig;// 初始化信息,保存filterConfig对象public void init(FilterConfig filterConfig) throws ServletException{this.filterConfig = filterConfig;}public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain){try{HttpServletRequest httpRequest = (HttpServletRequest) request;HttpServletResponse httpResponse = (HttpServletResponse) response;String encoding = filterConfig.getInitParameter("encoding");httpRequest.setCharacterEncoding(encoding);httpResponse.setCharacterEncoding(encoding);filterChain.doFilter(request, response);} catch (ServletException e){filterConfig.getServletContext().log(e.getMessage());} catch (IOException e2){filterConfig.getServletContext().log(e2.getMessage());}}// 释放资源public void destroy(){this.filterConfig = null;}} 2)过滤器类需要在web.xml中配置使用,在web.xml中增加过滤器的配置:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><filter><filter-name>encodingFilter</filter-name><filter-class>CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
在jsp文件开头部分指定响应数据的编码字符集,控制了输出给客户端的文本字符集为utf-8;
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
HTML代码声明:在jsp代码中的HTML代码、或纯HTML网页文件中的<head>标记中给出下面定义,设定了HTML使用的字符集为utf-8:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">