JavaWeb开发知识总结(filter)

来源:互联网 发布:钢结构厂房起脊算法 编辑:程序博客网 时间:2024/05/15 05:38

JavaWeb开发知识总结(Filter)

1. 过滤器概述

Filter:过滤器,可以过滤客户端向服务器发送的请求。

Filter用途:用于过滤访问服务器的IP地址,用户自动登陆及响应压缩等。

2. 过滤器的使用

J2EE在javax.servlet.Filter中提供了一个过滤器的接口Filter,实现自定义的过滤器需要实现该接口,并在项目的配置文件web.xml 中进行配置该过滤器即可。

自定义类实现Filter接口:

/** * 自定义类实现Filter接口,过滤客户端向服务器发送的请求 */public class FilterDemo1 implements Filter {    // 过滤器的销毁方法    @Override    public void destroy() {        System.out.println("filter destory...");    }    // 过滤请求的方法    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        System.out.println("servletdemo1 filter doFilter...");        // 该方法是允许请求通过,不调用该方法是将请求进行拦截并阻塞,请求的资源不能被访问到        chain.doFilter(request, response);    }    // 过滤器初始化方法    @Override    public void init(FilterConfig arg0) throws ServletException {        System.out.println("filter init...");    }}

项目配置文件中配置过滤器:

<!--web.xml配置文件--><?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><!-- 过滤器的配置 --><filter>    <!--过滤器的名称-->    <filter-name>FilterDemo1</filter-name>    <!--过滤器的class的完全限定名-->    <filter-class>com.filter.FilterDemo1</filter-class></filter><!--过滤器的映射--><filter-mapping>    <!--过滤器的名称-->    <filter-name>FilterDemo1</filter-name>    <!--要过滤的资源,过滤所有的资源文件-->    <url-pattern>/*</url-pattern></filter-mapping></web-app>

3. Filter接口

3.1 Filter的生命周期

Filter过滤器创建:服务器启动时会创建过滤器对象;

Filter过滤器销毁:服务器关闭时会销毁过滤器对象;

Filter过滤器作用原理:客户端向服务器请求时,符合该过滤器的请求都会调用doFilter方法进行处理。

3.2 Filter过滤器过滤资源的配置(重点)

过滤拦截请求是在Filter的配置文件中进行配置的,过滤器会根据自身配置的拦截资源的规则进行过滤请求。过滤资源配置有三种方式:<url-pattern>过滤资源规则<url-pattern><servlet-name>需要拦截的Servlet名称</servlet-name><dispatcher>过滤资源的类型</dispatcher>

<!--web.xml配置文件--><?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><!-- 过滤器的配置 --><filter>    <!--过滤器的名称-->    <filter-name>FilterDemo1</filter-name>    <!--过滤器的class的完全限定名-->    <filter-class>com.filter.FilterDemo1</filter-class></filter><!--过滤器的映射--><filter-mapping>    <!--过滤器的名称-->    <filter-name>FilterDemo1</filter-name>    <!--要过滤的资源-->    <!--过滤方式1:url-pattern -->    <url-pattern>/*</url-pattern>    <!--过滤方式2:servlet-name -->    <servlet-name>Servlet名称</servlet-name>    <!--过滤方式3:dispatcher -->    <dispatcher>过滤类型</dispatcher></filter-mapping></web-app>

<url-pattern>配置方式:只能过滤request 请求,访问资源的路径配置方式,和Servlet的访问路径配置相似

路径访问的过滤:和Servlet的访问路径配置相似,但过滤器执行优先级只和在配置文件中过滤器映射 <filter-mapping> 的顺序有关。

# <url-pattern>的配置:配置的路径没有优先级(和Servlet的配置不同),执行的顺序按照mapping配置的顺序1.  完全路径匹配:以/开始. 如:/demo/demo.jsp 该过滤器只拦截对demo/demo.jsp请求2.  目录匹配    :以/开始,以\*结束.  如:/* 拦截所有的请求  /demo/*  过滤对demo下资源的请求    3.  扩展名匹配  :不能以/开始,以\*开始.  如:\*.do 拦截所有的以do为扩展名的资源的访问

配置方式:

<!--web.xml配置文件-->...<!-- 过滤器的配置 --><filter>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--过滤器的class的完全限定名-->      <filter-class>com.filter.FilterDemo1</filter-class></filter><!--过滤器的映射--><filter-mapping>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--要过滤的资源-->      <!--过滤方式1:url-pattern -->      <url-pattern>/*</url-pattern></filter-mapping>...

注意事项:Filter的拦截只和配置的顺序有关,而Servlet中访问路径的上述三种配置是有优先级之分的,两个的含义不同。

<servlet-name>配置方式:只能过滤request 请求,在Filter的映射中配置要拦截对指定名称的Servlet的访问

配置方式:

<!--web.xml配置文件-->...<!-- 过滤器的配置 --><filter>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--过滤器的class的完全限定名-->      <filter-class>com.filter.FilterDemo1</filter-class></filter><!--过滤器的映射--><filter-mapping>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--要过滤的资源-->      <!--过滤方式2:servlet-name -->      <servlet-name>Servlet名称</servlet-name></filter-mapping>...

<dispatcher>配置方式(重点):参数有四个REQUEST,FORWARD,INCLUDE,ERROR,可以配置多个参数,可以拦截这四种方式资源访问

dispatcher有四个参数,可以配置多个,四个参数的含义如下:

dispatcher参数 参数说明 REQUEST 是dispatcher配置的默认值,过滤所有的request方式的请求 FORWORD 过滤所有的资源转发 INCLUDE 过滤所有的页面的包含(静态包含和动态包含)动作 ERROR 过滤错误页面的跳转,错误页面是指配置的全局的错误页面

配置方式:

<!--web.xml配置文件-->...<!-- 过滤器的配置 --><filter>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--过滤器的class的完全限定名-->      <filter-class>com.filter.FilterDemo1</filter-class></filter><!--过滤器的映射--><filter-mapping>      <!--过滤器的名称-->      <filter-name>FilterDemo1</filter-name>      <!--要过滤的资源-->      <!--过滤方式3:dispatcher -->      <dispatcher>REQUEST</dispatcher>  <!--过滤request请求,可以省略 -->      <dispatcher>FORWORD</dispatcher>  <!--过滤资源的转发 -->      <dispatcher>INCLUDE</dispatcher>  <!--过滤资源的包含操作 -->      <dispatcher>ERROR</dispatcher>  <!--过滤错误页面的跳转 --></filter-mapping>...

3.3 Filter过滤器的配置对象-FilterConfig

FilterConfig类是过滤器的配置类,该类和Servlet的配置类相似,可以读取在Filter配置中的初始化参数以及获取ServletContext对象。

FilterConfig类常用方法:

常用API 类型 说明 String getFilterName() 成员方法 获取Filter的名称,指在配置文件总配置的名称 String getInitParameter(String name) 成员方法 获取Filter的指定名称的初始化参数 Enumeration getInitParameterNames() 成员方法 获取Filter的所有初始化参数名称的枚举形式 ServletContext getServletContext() 成员方法 获取全局的ServletContext对象

案例:通过FilterConfig对象获取Filter的初始化参数

// FilterDemo2.javapublic class FilterDemo2 implements Filter {    public void init(FilterConfig filterConfig) throws ServletException {          // 获得当前的Filter的名称:          String filterName = filterConfig.getFilterName();          System.out.println(filterName);          // 获得初始化参数:          String username = filterConfig.getInitParameter("username");          String password = filterConfig.getInitParameter("password");          System.out.println(username+"--"+password);          // 获得所有的初始化参数的名称:          Enumeration<String> en = filterConfig.getInitParameterNames();          while(en.hasMoreElements()){                String name = en.nextElement();                String value = filterConfig.getInitParameter(name);                System.out.println(name+"--"+value);          }    }}
<!--web.xml配置文件,配置Filter的初始化参数-->...<filter>  <filter-name>FilterDemo2</filter-name>  <init-param>    <param-name>username</param-name>    <param-value>somnus</param-value>  </init-param>  <init-param>    <param-name>password</param-name>    <param-value>somnus</param-value>  </init-param>  <filter-calss>com.filter.FilterDemo2</filter-calss></filter>...

3.4 Filter的过滤器链–FilterChain类

过滤器链就是多个过滤器呈链式结构,过滤器会按照顺序执行,并在服务器响应时再次反序执行过滤器。FilterChain 接口提供了一个方法doFilter() 方法调用下一个过滤器,过滤器执行的过程如下:

FilterChain执行原理

多个<filter-mapping> 标签配置的过滤器组成过滤器链,过滤器链中的过滤器按照<filter-mapping> 标签配置的顺序进行执行,当目标资源予以响应后再按照过滤器链执行的反序再次执行过滤器doFilter() 后续的代码逻辑。

4. 综合案例

4.1 利用Filter和Cookie实现用户的自动登陆

当用户第一次登陆时,将登陆用户的信息保存在Cookie(设置保存的时间)中,当用户下次访问主页面时通过Filter进行过滤,获取用户浏览器中的Cookie中信息,并从数据库中查询Cookie中的用户名和密码是否正确,正确则记录登陆状态。

<!--login.jsp--><%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html><html lang="zh-CN"><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->    <title>黑马商城后台管理</title>    <!-- Bootstrap -->    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/shop/css/bootstrap.min.css" />    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->    <script type="text/javascript" src="${pageContext.request.contextPath }/shop/js/jquery-2.1.1.min.js"></script>    <!-- Include all compiled plugins (below), or include individual files as needed -->    <script type="text/javascript" src="${pageContext.request.contextPath }/shop/js/bootstrap.min.js"></script>    <script type="text/javascript">        // 验证码图片的刷新        $(function() {            $("#iconCode").click(function(){                $("#iconCode").attr("src","${pageContext.request.contextPath }/CheckImgServlet?time="+new Date());            });            $("#changIconCode").click(function(){                $("#iconCode").attr("src","${pageContext.request.contextPath }/CheckImgServlet?time="+new Date());            });        });    </script></head><body>    <div class="container">        <!--获取登陆校验的信息-->        <c:if test="${ msg != null }">            <div class="row">                <div class="col-lg-offset-2 col-lg-8 alert alert-danger alert-dismissible text-center" role="alert">                    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>                    ${msg }                </div>            </div>        </c:if>        <!--添加-->        <div class="row">            <div class="col-lg-offset-2 col-lg-8" style="padding: 0px;">                <div class="panel panel-info">                    <!-- Default panel contents -->                    <div class="panel-body" style="background-color: #F7F7F7;">                        <div class="row">                            <div class="col-lg-offset-2 col-lg-3">                                <h3>Please sign in</h3>                                <hr />                            </div>                        </div>                        <div class="row">                            <div class="col-lg-offset-2 col-lg-8">                                <form class="form-horizontal" action="${pageContext.request.contextPath }/UserLoginServlet" method="post">                                    <div class="form-group">                                        <div class="col-sm-offset-1 col-sm-10 input-group" >                                            <span class="input-group-addon" id="icon1">                                                <span class="glyphicon glyphicon-user" aria-hidden="true"></span>                                            </span>                                            <input type="text" style="height: 40px;" class="form-control" name="username" placeholder="请输入用户名" aria-describedby="icon1">                                        </div>                                    </div>                                    <div class="form-group">                                        <div class="col-sm-offset-1 col-sm-10 input-group" >                                            <span class="input-group-addon" id="icon2">                                                <span class="glyphicon glyphicon-lock" aria-hidden="true"></span>                                            </span>                                            <input type="password" style="height: 40px;" class="form-control" name="password" placeholder="请输入密码" aria-describedby="icon2">                                        </div>                                    </div>                                    <div class="form-group">                                        <div class="col-sm-offset-1 col-sm-4" style="padding-left: 0px">                                            <div class="input-group">                                                <span class="input-group-addon" id="icon2">                                                    <span class="glyphicon glyphicon-bookmark" aria-hidden="true"></span>                                                </span>                                                <input type="text" style="height: 40px;" class="form-control" name="code" placeholder="请输入验证码" aria-describedby="icon2">                                            </div>                                        </div>                                        <!-- 验证码 -->                                        <div class="col-sm-3" style="padding-left: 0px">                                            <img alt="验证码加载失败" id="iconCode" src="${pageContext.request.contextPath }/CheckImgServlet">                                        </div>                                        <div class="col-sm-3 text-center" style="padding-left:0px;margin-top:6px;">                                            <span>看不清,<button type="button" id="changIconCode" class="btn btn-link">换一张</button></span>                                        </div>                                    </div>                                    <div class="form-group">                                        <div class="col-sm-offset-1 col-sm-10">                                            <div class="checkbox">                                                <label>                                                    <input type="checkbox" name="autoLogin" value="true">记住密码                                                </label>                                            </div>                                        </div>                                    </div>                                    <div class="form-group">                                        <div class="col-sm-offset-1 col-sm-10">                                            <button type="submit" class="btn btn-primary">登  陆</button>                                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                                            <button type="reset" class="btn btn-warning">重  置</button>                                        </div>                                    </div>                                </form>                            </div>                        </div>                    </div>                </div>            </div>        </div>    </div>    <!-- /container --></body></html>
<!--index.jsp--><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>商城主页</title></head><body><h2>    <c:if test="${ existUser == null }">    <a href="${pageContext.request.contextPath }/shop/login.jsp">登录</a>    <a href="#">注册</a>    </c:if>    <c:if test="${ existUser != null }">    <font>欢迎您:${ existUser.nickname}</font>    <a href="#">安全退出</a>    </c:if>    <a href="#">购物车</a></h2></body></html>
package com.itheima.web.servlet;/** * 用户登陆的Servlet    UserLoginServlet.java */public class UserLoginServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 设置request缓冲区中的编码,防止中文乱码        request.setCharacterEncoding("UTF-8");        // 获取验证码        String code = request.getParameter("code");        // 直接访问该Servlet时,code为null        // 如果验证码为空时,code为空字符串,直接跳转到登陆页面        if("".equals(code)) {            // 设置错误提示消息            request.setAttribute("msg", "验证码不能为空");            // 转发到登陆页面            request.getRequestDispatcher("/shop/login.jsp").forward(request, response);            return;        }        // 当验证码不为空时再验证验证码        String incode = (String) request.getSession().getAttribute("iconCode");        // 如果验证码不正确直接跳转到登陆页面进行提示        if(!code.equalsIgnoreCase(incode)) {            // 设置错误提示消息            request.setAttribute("msg", "验证码错误");            // 转发到登陆页面            request.getRequestDispatcher("/shop/login.jsp").forward(request, response);            return;        }        // 如果验证码正确后,在判断用户名和密码是否正确        // 接收用户名和密码进行分装        User user = new User();        Map<String, String[]> parameterMap = request.getParameterMap();        try {            BeanUtils.populate(user, parameterMap);            // 调用业务层进行用户名和密码的验证            UserService userService = new UserService();            User existUser = userService.loginUser(user);            // 判断登陆的用户是否存在,不存在则跳转到登陆页面并进行提示            if(existUser == null) {                // 设置错误提示消息                request.setAttribute("msg", "用户名或密码错误");                // 转发到登陆页面                request.getRequestDispatcher("/shop/login.jsp").forward(request, response);                return;            }            // 用户校验通过后,判断是否选择自动登陆            String autoLogin = request.getParameter("autoLogin");            // 如果选中自动登陆,则将用户的登陆信息保存在Cookie中            if("true".equals(autoLogin)) {                Cookie cookie = new Cookie("autoLogin", existUser.getUsername()+"-"+existUser.getPassword());                // 设置Cookie的有效路径是整个工程                cookie.setPath(request.getContextPath());                // 设置Cookie的有效时间是2周                cookie.setMaxAge(60 * 60 * 24 * 14);                // 将Cookie写到客户端                response.addCookie(cookie);            }            // 将登陆的用户信息保存在session            request.getSession().setAttribute("existUser", existUser);            // 跳转到index.jsp            response.sendRedirect(request.getContextPath() + "/shop/index.jsp");        } catch (Exception e) {            e.printStackTrace();            throw new  RuntimeException();        }    }}
package com.itheima.web.filter;/** * 用户自动登陆的过滤器     AutoLoginFilter.java */public class AutoLoginFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {}    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        // 用户登陆成功的信息保存在session中,先判断session中是否含有登陆用户的信息        // session中有登陆用户的信息,直接放行        HttpServletRequest hrequest = (HttpServletRequest) request;        User existUser = (User) hrequest.getSession().getAttribute("existUser");        if(existUser != null) {            chain.doFilter(request, response);            return;        }        // session中没有,判断Cookie中是否有用户登陆的信息        Cookie[] cookies = hrequest.getCookies();        Cookie findCookie = CookieUtils.findCookie(cookies, "autoLogin");        // 从Cookie中没有用户名和密码的信息,则直接放行        if(findCookie == null) {            chain.doFilter(request, response);            return;        }        // Cookie中有用户名和密码的信息,到数据库中进行查询该用户的用户名和密码是否正确,防止Cookie被篡改        // 获取Cookie中存储的用户名和密码信息,存储时格式:用户名-密码        String cookieValue = findCookie.getValue();        String username = cookieValue.split("-")[0]; // 获取用户名        String password = cookieValue.split("-")[1]; // 获取密码        User user = new User(); // 封装user类        user.setUsername(username);        user.setPassword(password);        // 从数据库总查询该用户名和密码是否正确        UserService userService = new UserService();        try {            existUser = userService.loginUser(user);        } catch (SQLException e) {            e.printStackTrace();        }        // 查询用户信息和密码正确,则将用户的登陆信息保存到session域中        if(existUser != null) {            hrequest.getSession().setAttribute("existUser", existUser);            chain.doFilter(request, response);            return;        }        // 查询用户名和密码错误,则直接放行        chain.doFilter(request, response);    }    @Override    public void destroy() {}}
<!--web.xml配置文件--><?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>JavaWeb_day22_filter</display-name>  <!-- 验证码图片的Servlet -->  <servlet>    <servlet-name>CheckImgServlet</servlet-name>    <servlet-class>com.itheima.web.servlet.CheckImgServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>UserLoginServlet</servlet-name>    <servlet-class>com.itheima.web.servlet.UserLoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>CheckImgServlet</servlet-name>    <url-pattern>/CheckImgServlet</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>UserLoginServlet</servlet-name>    <url-pattern>/UserLoginServlet</url-pattern>  </servlet-mapping>  <!-- 自动登陆的过滤器 -->  <filter>    <filter-name>AutoLoginFilter</filter-name>    <filter-class>com.itheima.web.filter.AutoLoginFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>AutoLoginFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping></web-app>

4.2 通用的字符集编码的过滤器–统一解决GET和POST方式的中文编码

HttpServletRequest接口通过GET和POST的方式获取客户端传递的数据时,为防止中文乱码需要进行编码的转换,为实现统一字符集编码,可以通过增强HttpServletRequest接口的getParameter 等获取参数的方法,使用装饰者模式将原始的获取数据的额方法进行装饰,而HttpServletRequest是一个接口,为方便增强其中的方法,J2EE提供了一个该接口的一个模板类HttpServletRequestWrapper;则通过继承该类可以增强原始的获取数据的方法,并在字符集的编码过滤器中进行使用,当有任何访问该站点的请求,均会通过过滤器,在过滤器中进行编码的转换。

装饰者模式的前提:增强的类和被增强类实现相同的接口,增强的类中获得到被增强的类的引用.

自定义类实现模板类并将获取数据的方法增强:

/** * GenericHttpServletRequest.java * HttpServletRequest的装饰类 统一GET和POST方式的字符编码解决中文乱码问题 */public class GenericHttpServletRequest extends HttpServletRequestWrapper {    // 获取被装饰类的引用    private HttpServletRequest request;    public GenericHttpServletRequest(HttpServletRequest request) {        super(request);        this.request = request;    }    /**     * 增强getParameter方法     */    @Override    public String getParameter(String name) {        // 获取请求的方式        String method = request.getMethod();        // 如果是GET请求        if ("get".equalsIgnoreCase(method)) {            // 通过被增强类的request对象获得数据            String parameter = request.getParameter(name);            // 将数据进行重新编码            try {                return new String(parameter.getBytes("ISO-8859-1"), "UTF-8");            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }        // POST方式请求        } else if ("post".equalsIgnoreCase(method)) {            try {                request.setCharacterEncoding("UTF-8");                return super.getParameter(name);            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }        }        // 如果是其他方式的请求,直接调用被增强类的原始的方法        return super.getParameter(name);    }    /**     * 增强getParameterMap方法     */    @Override    public Map<String, String[]> getParameterMap() {        // 获取请求的方式        String method = request.getMethod();        // POST方式,设置request缓冲区的编码即可        if ("post".equalsIgnoreCase(method)) {            try {                request.setCharacterEncoding("UTF-8");                return super.getParameterMap();            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }        } else if ("get".equalsIgnoreCase(method)) {            // 先通过被增强类的原始的方法获取到数据            Map<String, String[]> parameterMap = request.getParameterMap();            // 遍历Map集合,将其中存储的数据进行编码转换            for (String str : parameterMap.keySet()) {                 String[] strings = parameterMap.get(str);                if(strings != null) {                    for (int i = 0; i < strings.length; i++) {                        try {                            strings[i] = new String(strings[i].getBytes("ISO-8859-1"), "UTF-8");                        } catch (UnsupportedEncodingException e) {                            e.printStackTrace();                        }                    }                }            }            return parameterMap;        }        return super.getParameterMap();    }    /**     * 增强getParameterValues方法     */    @Override    public String[] getParameterValues(String name) {        // 先获取原始的数据        String[] parameterValues = request.getParameterValues(name);        if(parameterValues != null) {            for (int i = 0; i < parameterValues.length; i++) {                try {                    parameterValues[i] = new String(parameterValues[i].getBytes("ISO-8859-1"), "UTF-8");                } catch (UnsupportedEncodingException e) {                    e.printStackTrace();                }            }        }        return parameterValues;    }}

自定义过滤器,拦截所有的请求,并增强其中的HttpServletRequest对象:

package com.itheima.filter;/** * 自定义过滤器   GenericEncodingFilter.java */public class GenericEncodingFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {}    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        // 将ServletRequest对象转换为HttpServletRequest        HttpServletRequest hrequest = (HttpServletRequest) request;        // 对HttpServletRequest进行装饰        GenericHttpServletRequest genericHttpServletRequest = new GenericHttpServletRequest(hrequest);        // 放行时传入增强后的HttpServletRequest        chain.doFilter(genericHttpServletRequest, response);    }    @Override    public void destroy() {}}

在配置文件中配置自定义的过滤器,拦截所有的请求:

<!--web.xml配置文件--><!--配置过滤器--><filter>    <!--过滤器名称-->    <filter-name>GenericEncodingFilter</filter-name>    <!--过滤器类的完全限定名-->    <filter-class>com.itheima.filter.GenericEncodingFilter</filter-class></filter><!--配置过滤器映射--><filter-mapping>    <!--过滤器名称-->    <filter-name>GenericEncodingFilter</filter-name>    <!--过滤器过滤规则,拦截所有的请求-->    <url-pattern> /* </url-pattern></filter-mapping>