Java8设计模式最佳实战-设计模式概述(第六天学习记录)

文章介绍了如何在Java中创建和配置Servlet过滤器,包括使用责任链模式、定义filterName和urlPatterns,以及通过web.xml文件管理过滤器执行顺序。LogAccessFilter和LogBrowserFilter示例展示了获取客户端信息并记录日志的过程。
摘要由CSDN通过智能技术生成

Date dateEndRequest = new Date();

//Logging the informations of IP and access time.

logger.info("IP: " + ip + " Access time : "

  • Long.toString(dateEndRequest.getTime()
  • dateInitRequest.getTime())
  • " ms");

}

public void init(javax.servlet.FilterConfig config) throws

javax.servlet.ServletException {

}

}

As we can see in the code, to create one servlet filter, we need to create a class that

正如我们在代码中看到的,要创建一个servlet过滤器,我们需要创建一个类

extends javax.servlet.Filter and puts the @WebFilter annotation with filterName

继承javax.servlet.Filter并将@WebFilter注释与filterName放在一起

and urlPatterns parameters, which define the filter name and the URLs to filter, before

和urlPatterns参数,它们定义了过滤器名称和要过滤的url

the definition of class. The following is a snippet of code that demonstrates how to do that

class的定义。下面是一段代码,演示了如何做到这一点

@WebFilter(filterName = “LogAccess”, urlPatterns = “/*”)

public class LogAccessFilter implements javax.servlet.Filter{

}

Note that the servlet filter uses the chain of responsibility pattern to walk throughout the

注意,servlet过滤器使用责任链模式遍历整个

filters (objects that are servlet filter). The following is a snippet of code that uses a chain of

过滤器(servlet过滤器对象)。以下是使用

responsibility pattern:

责任模式:

chain.doFilter(req, resp);

In the preceding line of code, we established the filter name as LogAccess through

在前面的代码行中,我们将过滤器名称设置为LogAccess through

the filterName parameter. This will filter all requests, because

filterName参数。这将过滤所有请求,因为

the urlPatterns parameter has the “/_” value. If we filter according to servlet name, we

urlPatterns参数具有“/_”值。如果我们根据servlet名称进行过滤,那么

need to use the following annotation:

需要使用以下注释:

//Servlet1 and Servlet2 are the servlets to filter.

@WebFilter(filterName = “LogAccess”, servletNames =

{“servlet1”,“servlet2”})

The doFilter method is responsible for pre-processing and post-processing and

doFilter方法负责前处理和后处理以及

establishes when to follow the request to the next filter or servlet (main logic). To follow the

确定何时跟踪请求到下一个过滤器或servlet(主逻辑)。跟随

request to the next filter or servlet, the following code needs be executed:

请求下一个筛选器或servlet时,需要执行以下代码:

//Following to next filter or servlet.

chain.doFilter(req, resp);

When the preceding code is executed, the current filter executes only the next line when the

当执行前面的代码时,当前筛选器只执行下一行

other filters and servlets finish their processing.

其他过滤器和servlet完成它们的处理。

Implementing LogBrowserFilter

The implementation of LogBrowserFilter is as follows:

package com.gary.book.chapter01;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import javax.servlet.*;

import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

@WebFilter(filterName = “LogBrowser”, urlPatterns = “/*”)

public class LogBrowserFilter implements Filter {

private static Logger logger = LogManager.getLogger(LogBrowser.class);

public void destroy() {

}

public void doFilter(ServletRequest req, ServletResponse resp,

FilterChain chain) throws ServletException, IOException {

//Get userAgent that contain browse informations.

String userAgent = ((HttpServletRequest) req).getHeader(“UserAgent”);

//Get IP of Client that sent a resquest.

String ip = ((HttpServletRequest) req).getRemoteAddr();

//Logging the informations of IP and Browser.

logger.info("IP: " + ip + " Browser info: " + userAgent);

//Following to the next filter. If none next filter exist, follow to main logic.

chain.doFilter(req, resp);

}

public void init(FilterConfig config) throws ServletException {

}

}

In the preceding filter, we get the client IP and browser information and log them. The

在前面的过滤器中,我们获取客户端IP和浏览器信息并记录它们。这个

LogBrowserFilter operation is similar to that of LogAccessFilter.

LogBrowserFilter的操作与LogAccessFilter的操作类似。

To define the order of filter execution, we need to configure the web.xml and add the filter

要定义过滤器执行的顺序,我们需要配置web.xml文件再加上过滤器

mapping information. Here, we can see web.xml with its configuration:

映射信息。在这里,我们可以看到web.xml文件其配置:

<web-app version=“3.1”

xmlns=“http://xmlns.jcp.org/xml/ns/javaee”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

LogBrowser

com.rhuan.filter.LogBrowserFilter

LogAccess

com.rhuan.filter.LogAccessFilter

The configurations defined in web.xml override the annotation configurations. Thus, if we

中定义的配置web.xml文件重写注释配置。因此,如果我们

put the urlPattern configuration on web.xml, then the configuration considered

启用urlPattern配置web.xml文件,然后考虑配置

is web.xml’s configuration. We don’t put the filter mapping information on web.xml

是web.xml文件的配置。我们不把过滤器映射信息放在web.xml文件

because this is already on the annotation configuration in the code.

因为这已经在代码中的注释配置上了。

The web.xml configuration defines the order—LogBrowserFilter will be called first,

这个web.xml文件配置定义将首先调用LogBrowserFilter的顺序,

followed by LogAccessFilter, and then the main logic (servlet).

接着是LogAccessFilter,然后是主逻辑(servlet)。

Deciding filter mapping

定义滤波器映射

Defining the mapping method is crucial to implementing the intercepting filter pattern.

定义映射方法是实现拦截过滤模式的关键。

This is because a bad method for mapping can impact the project directly and cause

这是因为不好的映射方法会直接影响项目并导致

rework. We have two filter mapping types—UrlPattern and servlet name.

返工。我们有两种过滤器映射类型UrlPattern和servlet name。

The use of UrlPatterns is indicated when we want to filter the HTTP Requests to nonspecific resources or files, but we also want to filter various unknown resources. Here are

当我们想过滤对非特定资源或文件的HTTP请求时,使用UrlPatterns是有指示的,但是我们也希望过滤各种未知资源。给你

some examples of this:

这方面的一些例子:

_.jsp: This filters all requests to JSP pages. If one JSP page is added to the

_.jsp:它过滤对jsp页面的所有请求。如果一个JSP页面被添加到

server, then the filter will filter the new JSP page without making any

服务器,则过滤器将过滤新的JSP页面,而不进行任何

modifications.

修改。

/_: This filters all requests to all resources or files on the server. If one resource or

/_:这将筛选对服务器上所有资源或文件的所有请求。如果一个资源或

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
-1714807044920)]

[外链图片转存中…(img-TaRftqnv-1714807044921)]

[外链图片转存中…(img-rPyKYJVD-1714807044921)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值