首页 > 代码库 > Servlet & Filter

Servlet & Filter

Servlet

   Java Servlets是运行在web或应用服务器上的程序,在来自web浏览器及其他HTTP客户端的请求和数据库及HTTP服务器上的应用之间起中间件作用。

  使用Servlets,你可以从网页表单获取用户输入,从数据库或其他资源展示数据记录,并动态地创建网页。 (selvlet类似于cgi)

 

Servlet architecture

 技术分享

 

Servlet 和 CGI

   CGI stands for Common Gateway Interface (CGI). 例如 cgit就使用了cgi。

   cgi可移植性不如servlet. 一般每次的CGI请求都需要新生成一个程序的副本来运行。

  Servlet的优点:

  • Performance is significantly better.

  • Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.

  • Servlets are platform-independent because they are written in Java.

  • Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.

  • The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

 

Filter

  过滤用户数据是Web应用安全的基础。它是验证数据合法性的过程。通过对所有的输入数据进行过滤,可以避免恶意数据在程序中被误信或误用。大多数Web应用的漏洞都是因为没有对用户输入的数据进行恰当过滤所引起的。

  •  过滤器(filter)与拦截器(interceptor) (以struts2为例)
1、拦截器是基于java的反射机制的,而过滤器是基于函数回调。 2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器。 3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。 4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能。 5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。

  Interceptors can execute code before and after an Action is invoked. Most of the framework‘s core functionality is implemented as Interceptors. Features like double-submit guards, type conversion, object population, validation, file upload, page preparation, and more, are all implemented with the help of Interceptors. Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.

 

参考:

  https://www.oschina.net/question/565065_86561

Servlet & Filter