Servlet-编写过滤器

SERVLET过滤器 全球因特网用户使用不同类型的Web浏览器访问应用服务器上存储的Web应用程序。每个浏览器根据对应的Web浏览器窗口中的设置显示应用程序中的信息。Web应用程序可能会有一些客户机的Web浏览器不支持的HTML标记或功能。这种情况下,应用程序在客户机的Web浏览器中可能运行,可能不运行,还可能生成不需要的输出。为了避免这种问题,在调用servlet之前需要识别浏览器的类型和向Web应用程序发送请求的客户机和其他特定的信息。 阅读详情


Servlet过滤器是Java类,出于以下目的,可以在Servlet编程中使用它们:

  • 在客户端访问后端之前拦截客户端的请求。
  • 在服务器将响应发送回客户端之前对其进行操作。

规格建议使用多种类型的过滤器:

  • 身份验证过滤器。
  • 数据压缩过滤器。
  • 加密过滤器。
  • 触发资源访问事件的过滤器。
  • 图像转换过滤器。
  • 日志和审核过滤器。
  • MIME-TYPE链式过滤器。
  • 标记化过滤器。
  • 转换XML内容的XSL/T过滤器。

过滤器部署在部署描述符文件web.xml中,然后映射到应用程序的部署描述符中的servlet名称或URL模式。

Web容器启动Web应用程序时,它将为您在部署描述符中声明的每个过滤器创建一个实例。过滤器按照在部署描述符中声明的顺序执行。

Servlet过滤器方法

过滤器只是实现javax.servlet.Filter接口的Java类。javax.servlet.Filter接口定义了三种方法:

序号方法与说明
1public void doFilter (ServletRequest, ServletResponse, FilterChain):每当客户端对链末端的资源请求时,容器每次request/response对通过链时,容器都会调用此方法。
2public void init(FilterConfig filterConfig):Web容器调用此方法,以向过滤器指示它已投入使用。
3public void destroy():Web容器调用此方法,以向过滤器指示该方法已停止使用。

Servlet过滤器-示例

以下是Servlet过滤器示例,该示例将显示客户端IP地址和当前日期时间。该示例将使您对Servlet过滤器有基本的了解,但是您可以使用相同的概念编写更复杂的过滤器应用程序:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class
public class LogFilter implements Filter  {
   public void  init(FilterConfig config) throws ServletException {
      
      // Get init parameter 
      String testParam = config.getInitParameter("test-param"); 

      //Print the init parameter 
      System.out.println("Test Param: " + testParam); 
   }
   
   public void  doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws java.io.IOException, ServletException {

      // Get the IP address of client machine.
      String ipAddress = request.getRemoteAddr();

      // Log the IP address and current timestamp.
      System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());

      // Pass request back down the filter chain
      chain.doFilter(request,response);
   }

   public void destroy( ) {
      /* Called before the Filter instance is removed from service by the web container*/
   }
}

以常规方式编译LogFilter.java并将类文件放入<Tomcat安装目录>/webapps/ROOT/WEB-INF/classes中。

Web.xml中的Servlet过滤器映射

定义过滤器,然后将其映射到URL或Servlet,与定义Servlet然后将其映射到URL模式几乎相同。在部署描述符文件web.xml中为过滤器标签创建以下条目:

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

上面的过滤器将应用于所有servlet,因为我们在配置中指定了/*。如果只想对几个servlet应用过滤器,则可以指定一个特定的servlet路径。

现在尝试以通常的方式调用任何servlet,您将在Web服务器日志中看到生成的日志。您可以使用Log4J记录器在单独的文件上方记录日志。

使用多个过滤器

您的Web应用程序可能会针对特定目的定义几个不同的过滤器。考虑一下,您定义了两个过滤器AuthenFilter和LogFilter。其余过程将按上述说明进行,只是您需要按如下所述创建其他映射

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter>
   <filter-name>AuthenFilter</filter-name>
   <filter-class>AuthenFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

筛选申请单

web.xml中过滤器映射元素的顺序确定了Web容器将过滤器应用于servlet的顺序。要颠倒过滤器的顺序,您只需要颠倒web.xml文件中的过滤器映射元素。

例如,上面的示例将首先应用LogFilter,然后将AuthenFilter应用于任何servlet,但是下面的示例将颠倒顺序:

<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

上一篇:Servlet-Http状态代码
下一篇:Servlet-异常

彻底卸载Ubuntu双系统,并完美回收100G空间给D盘 本文记录了安全卸载Ubuntu双系统并回收磁盘空间的全过程。作者首先通过Windows命令行彻底清除Ubuntu启动项,避免GRUB引导报错;随后在磁盘管理中删除Linux分区,将100G未分配空间合并至相邻的D盘。针对C盘空间不足问题,作者采用Dism++清理系统文件,并将用户文档、聊天记录等迁移至扩容后的D盘。最终实现了引导纯净、空间合理分配的目标,特别强调分区扩展必须遵循"相邻原则",建议通过间接迁移而非直接扩容来优化系统盘空间管理。 阅读详情

相关推荐

TPS563201DDCR电路翻车实录:从原理图到PCB,我踩过的5个坑及补救方法

本文详细记录了使用TPS563201DDCR电源芯片设计电路时遇到的5个常见问题及解决方案,包括EN引脚配置、BST电容选型、反馈网络设计、PCB布局优化以及散热处理。通过实际案例和数据分析,帮助工程师避免类似错误,提升电源模块的可靠性和效率。

weixin_42532938的博客 529

Servlet 编写过滤器

前言 Servlet 过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响应中的信息。 可以将一个或多个 Servlet 过滤器附加到一个 Servlet 或一组 Servlet。Servlet 过滤器也可以附加到 JavaServer Pages (JSP) 文件和 HTML 页面。调用 Servlet 前调用所有附加的 Servlet 过滤器。 Servlet 过滤器是可用于 Servl...

Yfw的博客 794

卷积码和Turbo码

通信原理相关博文目录:目录我们常在移动通信中遇到的卷积码就是一种非分组码,卷积码和信号处理中的卷积运算有关系吗?是不是就是信号处理中的卷积运算,先看看编码器的编码原理再说:下面是一个比较实用的卷积码编码器:它有三个移位寄存器D0,D1,D2和三个模2加法器,以及一个旋转开关组成,编码前,先将各级移位寄存器清零:现在假设输入的信息码元是1101:当输入的第一个码元为1时,三个模2加法器计算的结果都为...

Reborn Lee 2万+

servlet过滤器简约版

servlet过滤器: 过滤器: 介绍: ​ Filter 即为过滤,⽤于在 Servlet 之外对 Request 或者 Response 进⾏修改。它主要⽤于对⽤户请求进⾏预处理,也可以对 HttpServletResponse 进⾏后处理。使⽤ Filter 的完整流程: Filter 对⽤户请求进⾏预处理,接着将请求交给 Servlet 进⾏处理并⽣成响应,最后 Filter 再 对服务器响应进⾏后处理。在⼀个 web 应⽤中,可以开发编写多个 Filter,这些 Filter 组合 起来称之为

qq_43517448的博客 174

Ubuntu22环境下Xinference与RAGFLOW集成:构建高效rerank模型服务【实战指南】

本文详细介绍了在Ubuntu22.04系统上,通过部署Xinference模型推理服务来加载bge-reranker-base等rerank模型,并将其与RAGFLOW框架集成的完整实战指南。该方案实现了模型服务的解耦与灵活管理,有效提升RAG系统的检索精度与答案相关性,并提供了从环境配置、服务启动、网络连接到性能调优及常见问题排查的全流程解决方案。

pluto的博客 500

技术前沿:半导体前道检测和量测设备修复技术

半导体前道检测设备是目前除光刻机外,国产渗透率较低的环节之一,近年来我国初步实现国产突破。前道检测相对后道检测环节壁垒更高,国内多家涉及后道测试,涉及前道检测和中道检测相对较少。

VOMMA的博客 4543

Servlet—实现过滤器

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34106122的博客 279

反应动力学仿真软件:Kintecus_(4).用户界面及操作指南

在 Kintecus 中,反应方程的定义非常灵活。您可以定义简单的一阶反应、复杂的多步反应以及不同类型的反应机制。

kkchenjj的博客 1182

JAVA WEB过滤器

WEB的三大组件之一 过滤器实际上就是对WEB资源进行拦截,做一些处理后再交给下一个过滤器或者SERVLET处理。 通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理 应用场景: 自动登录 统一设置编码格式 访问权限控制 敏感字符过滤等 1、统一设置编码格式 在Servlet中我们一般都会对request和response中的字符集编码进行配置,如果Servlet过多字符集编码发生变化时修改起码会很麻烦,这些通用的字符集编码配置等工作我们可以放到Filter

我3的博客 477

手把手教你学Simulink——基于Simulink的前馈解耦SVPWM整流器仿真

本文详细介绍了基于Simulink的前馈解耦SVPWM整流器仿真方法。针对三相PWM整流器存在的dq轴交叉耦合问题,提出前馈解耦控制方案,通过在电流环中引入耦合电压补偿项,显著提升系统性能。文章包含完整的系统架构、核心算法、Simulink建模步骤及参数设置,仿真结果显示:电流跟踪误差<2%、动态响应时间<0.05s、THD<3%、功率因数>0.999。同时提供了可直接复用的MATLAB代码和工程优化建议,为电力电子工程师实现高精度AC/DC转换提供了实用解决方案。

MHD0815的博客 108

3、数据导入与清洗:Excel、SQL、SPSS、Stata和SAS数据处理

本文详细介绍了如何从Excel文件、SQL数据库以及SPSS、Stata和SAS等统计软件中导入和清洗数据。针对不同数据来源的特点,提供了具体的处理方法,包括跳过无用行、重命名列、处理缺失值、转换数据类型、保留元数据等关键步骤。同时,通过实际应用案例展示了如何整合多源数据,并总结了数据导入和清洗的最佳实践,帮助读者高效完成数据预处理工作,为后续的数据分析打下坚实基础。

134

如何创建 Java Servlet 过滤器

Java servlet 过滤器是 Java Web 应用程序的基本组件,因为过滤器允许程序员拦截请求并转换响应以用于各种目的。即使您不创建任何过滤器,servlet 容器(如 Tomcat)和 Web 框架(如 Spring)也会在后台使用过滤器。 在本教程中,您将找到详细的分步指南来为您的项目创建 Java servlet 过滤器。 基本上,创建过滤器有 3 个步骤: - 编写实现Filter接口并覆盖过滤器生命周期方法的Java类。 - 指定过滤器的初始化参数(可选)。 - 指定

allway2的博客 1945

AI人工智能代理工作流 AI Agent WorkFlow:在股票市场预测中的应用

AI人工智能代理工作流 AI Agent WorkFlow:在股票市场预测中的应用 作者:禅与计算机程序设计艺术 / Zen and the Art of Computer Programming 关键词: AI Agent, W

AI天才研究院 859

Servlet过滤器

一,什么是Servlet过滤器? 1,过滤器 过滤器是在数据交互之间过滤数据的中间组件,独立于任何平台或者 Servlet 容器。 2,Servlet过滤器 Servlet过滤器是在Java Servlet规范2.3中定义的. 在WEB中,Servlet过滤器是服务器端WEB容器中的一个WEB组件,它们拦截请求和响应,并监视、修改或以某种方式处理正在交互的数据。  Servlet 过滤器可

自强 6294

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Servlet过滤器,过滤器并不是servlet

 Servlet过滤器是一种小型的、可插入的Web组件,其提供了对Web应用程序的前期处理和后期处理的逻辑控制,可以拦截请求和响应,以便查看、提取或以某种方式操作正在客户端和服务器之间进行交换的数据。Servlet过滤器具有动态、灵活、透明、模块化、可移植、可重用等性质,是一种自包含的,模块化的组件,可以在使用时将其添加到请求/响应链中,也可以被删除而不影响到应用程序的其他Web组件。Servle

傻傻@ 1277

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

【JavaWeb】Servlet与过滤器

javaweb中的Servlet与过滤器

低调做人,低调编码,神码都是浮云 1474

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Servlet 过滤器

Servlet 过滤器是 Java Web 应用程序中非常重要的组件,它可以对请求和响应进行拦截和处理。本文将详细介绍 Servlet 过滤器的概念、工作原理、使用场景及实现方式。

m0_73941339的博客 680
上一篇: Servlet-Http状态代码
下一篇: CentOS服务器使用经验总结
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值