artificerpi

Servlet & Filter

Servlet

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

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

 

通用Servlet

  一般来说,通用Servlet由javax.servlet.GenericServlet实作Servlet界面。程序设计人员可以通过使用或继承这个类来实现通用Servlet应用。

HttpServlet

  javax.servlet.http.HttpServlet实现了专门用于响应HTTP请求的Servlet,提供了响应对应HTTP标准请求的doGet()、doPost()等方法。

 

Dependency

  maven: https://mvnrepository.com/artifact/javax.servlet/servlet-api 

 

Servlet architecture

 

 Life cicle:

 The servlet is initialized by calling the init () method.

 The servlet calls service() method to process a client's request.

 The servlet is terminated by calling the destroy() method.

 Finally, servlet is garbage collected by the garbage collector of the JVM.

   对每一个客户端的请求,Servlet引擎载入Servlet,调用它的init()方法,完成Servlet的初始化。然后,Servlet对象通过为每一个请求单独调用service()方法来处理所有随后来自客户端的请求,最后,调用Servlet的destroy()方法把Servlet删除掉。

 

Code Example:

pom.xml  javax-api

1 <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
2 <dependency>
3     <groupId>javax.servlet</groupId>
4     <artifactId>servlet-api</artifactId>
5     <version>2.5</version>
6 </dependency>
View Code

HelloWorld.java

 1 // Import required java libraries
 2 import java.io.*;
 3 import javax.servlet.*;
 4 import javax.servlet.http.*;
 5 
 6 // Extend HttpServlet class
 7 public class HelloWorld extends HttpServlet {
 8  
 9   private String message;
10 
11   public void init() throws ServletException
12   {
13       // Do required initialization
14       message = "Hello World";
15   }
16 
17   public void doGet(HttpServletRequest request,
18                     HttpServletResponse response)
19             throws ServletException, IOException
20   {
21       // Set response content type
22       response.setContentType("text/html");
23 
24       // Actual logic goes here.
25       PrintWriter out = response.getWriter();
26       out.println("<h1>" + message + "</h1>");
27   }
28   
29   public void destroy()
30   {
31       // do nothing.
32   }
33 }
View Code

web.xml

1 <servlet>
2    <servlet-name>HelloWorld</servlet-name>
3    <servlet-class>HelloWorld</servlet-class>
4 </servlet>
5 
6 <servlet-mapping>
7    <servlet-name>HelloWorld</servlet-name>
8    <url-pattern>/HelloWorld</url-pattern>
9 </servlet-mapping>
View Code

Another example from github.

 

使用gradle

/*
 * This build file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * user guide available at https://docs.gradle.org/3.5/userguide/java_library_plugin.html
 */
 
 configurations {
    provided
    compile.extendsFrom provided
}
 

// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenCentral()
}

dependencies {
	provided group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

    // This dependency is exported to consumers, that is to say found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:21.0'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
}

  

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.

   参考代码 loginDemo 使用filter和interceptor实现权限认证。

 

参考:

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

  http://www.tutorialspoint.com/servlets/

  https://stackoverflow.com/questions/7213541/what-is-java-servlet

posted @ 2016-10-03 17:33  artificerpi  阅读(356)  评论(0编辑  收藏  举报

Copyright ©2017 artificerpi