Servlet过滤器基础技术及实践

Servlet过滤器基础技术及实践

关于servlet中过滤器Filter的一些介绍。


1、过滤器的基本认知

  1. Servlet过滤器与Servlet很像,但是它具有拦截客户端请求,对其进行检查过滤的功能。

  2. 过滤器的位置
    在这里插入图片描述
    过滤器部署到Web服务器中,客户端发送的请求会被过滤器进行过滤处理,最后发送到目标资源进行处理以后,服务器响应的信息也会经过过滤器进行处理检查。

  3. 过滤器当然也能组成链。
    在这里插入图片描述
    在部署多个过滤器后,请求和回应信息会逐层传递。

  4. 过滤器的核心对象
    在这里插入图片描述

Filter接口中的方法:
public void init(FilterConfig filterConfig)throws ServletException:过滤器初始化方法,在过滤器初始化时调用
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException:对请求进行过滤处理
public void destroy():销毁方法,释放资源

FilterConfig接口方法:
public String getFilterName():用于获取过滤器的名字
public ServletContext getServletContext():用于获取Servlet上下文
public String getInitParameter(String name):用于获取过滤器初始化参数
public Enumeration getInitParameterNames():用于获取过滤器的所有初始化参数

FilterChain接口方法:
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException:用于将过滤后的请求传送给下一个过滤器或者目标资源。


2、过滤器的实践一

  1. 本次实践主要是实现了在过滤器DemoFilter中统计访客次数count,暂时没有使用数据库,所以将count以web.xml文件配置信息的形式保存在服务器里面。
  2. 编写demoFilter类。
package myFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class DemoFilter implements Filter
{
    private int count;//记录放客数量
    //销毁资源
    public void destroy()
    {
        //释放资源
    }
    //过滤处理方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException
    {
        //过滤处理
        count++; //访问数量自增
        HttpServletRequest request=(HttpServletRequest)req;//将ServletRequest req转换成 HttpServletRequest
        //获取ServletContext
        ServletContext context = request.getSession().getServletContext();
        context.setAttribute("count",count);//将来访数量值放入ServletContext中
        chain.doFilter(req, resp);//向下传递过滤器
    }
    //初始化
    public void init(FilterConfig config) throws ServletException
    {
        //初始化处理
        String param= config.getInitParameter("count");//初始化参数
        count= Integer.valueOf(param);//将字符转化成int
    }

}
  1. 在web.xml中配置Filter
    <!-- Filter映射配置Start-->
    <filter>
        <filter-name>DemoFilter</filter-name>
        <filter-class>myFilter.DemoFilter</filter-class>
        <init-param>
            <!--初始化参数-->
            <param-name>count</param-name>
            <param-value>0</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DemoFilter</filter-name>
        <!--过滤器URL映射,对谁进行过滤-->
        <url-pattern>/demo.jsp</url-pattern>
    </filter-mapping>
    <!-- Filter映射配置End-->
  1. 编写demo.jsp
<%--
  Created by IntelliJ IDEA.
  User: 86136
  Date: 2020/11/4
  Time: 12:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>demo</title>
</head>
<body>
<h2>
    欢迎光临,您是第【<%=application.getAttribute("count")%>】位访客!
</h2>
</body>
</html>
  1. 运行截图
    输入http://localhost:8080/myWeb/demo.jsp
    在这里插入图片描述
    再次输入http://localhost:8080/myWeb/demo.jsp
    在这里插入图片描述

3、字符编码过滤实践

  1. html,servlet,filter三者联用,实现一个表单输入联动。
  2. Web容器内部使用的编码不支持中文字符集,所以可能会出现乱码现象。
    在这里插入图片描述
    所以可以定义一个过滤器,专门用于对字符编码格式进行过滤。
  3. 创建一个CharactorFilter类,编写如下代码
package myServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

public class CharactorFilter implements Filter
{
    String encoding=null;
    public void destroy()
    {
        encoding=null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException
    {
        //判断字符编码是否是空
        if(encoding!=null)
        {
            //设置req的编码格式
            req.setCharacterEncoding(encoding);
            //设置resp的编码格式
            resp.setContentType("text/html; charset="+encoding);
        }
        //传递给下一个过滤器
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException
    {
        //从web.xml配置文件中获取初始化参数
        encoding=config.getInitParameter("encoding");
    }

}
  1. 在web.xml中配置CharactorFilter配置信息
    <filter>
        <filter-name>CharactorFilter</filter-name>
        <filter-class>myFilter.CharactorFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharactorFilter</filter-name>
        <!--对所有的servlet请求都进行字符格式编码过滤-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  1. 创建Addservlet类,用于处理添加图书信息请求。
package myServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AddServlet extends HttpServlet
{
    private static final long seriaVersionUID=1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //获取PrintWriter
        PrintWriter out= response.getWriter();
        //获取图书编号
        String id=request.getParameter("id");
        //获取名称
        String name=request.getParameter("name");
        //获取作者
        String author = request.getParameter("author");
        //获取价格
        String price = request.getParameter("price");
        //输出图书信息
        out.print("<h2>图书信息添加成功</h2><hr>");
        out.print("图书编号:"+id+"<br>");
        out.print("图书名称:"+name+"<br>");
        out.print("作者:"+author+"<br>");
        out.print("价格:"+price+"<br>");
        out.print("<a href='./sales.html'>返回</a>");
        //刷新流
        out.flush();
        //关闭流
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request,response);
    }
}

  1. 在web.xml中配置AddFilter
    <servlet>
        <servlet-name>AddServlet</servlet-name>
        <servlet-class>myServlet.AddServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>AddServlet</servlet-name>
        <url-pattern>/AddServlet</url-pattern>
    </servlet-mapping>
  1. 编写sales.html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type"content="text/html;charset=GB2312">
    <title>sale</title>
</head>
<body>
    <form action="AddServlet" method="post">
        <table align="center" width="350" border="1">
            <tr>
                <td class="2" align="center" colspan="2">
                    <h2>添加图书信息</h2>
                </td>
            </tr>
            <tr>
                <td align="right">图书编号:</td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td align="right">图书名称:</td>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <td align="right">作 者:</td>
                <td><input type="text" name="author"></td>
            </tr>
            <tr>
                <td align="right">价 格:</td>
                <td><input type="text" name="price"></td>
            </tr>
            <tr>
                <td class="2" align="center" colspan="2">
                <input type="submit" value="添 加"></td>
            </tr>
        </table>
    </form>
</body>
</html>
  1. 运行工程
    在这里插入图片描述
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

creator_gzw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值