博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java servlet_Servlet教程– Java
阅读量:2531 次
发布时间:2019-05-11

本文共 28778 字,大约阅读时间需要 95 分钟。

java servlet

Welcome to Java Servlet Tutorial. In the last article, we learned about and looked into core concepts of Web Applications such as Web Server, Web Client, HTTP and HTML, Web Container and how we can use Servlets and JSPs to create web application. We also created our first Servlet and JSP web application and executed it on tomcat server.

欢迎使用Java Servlet教程。 在上一篇文章中,我们了解了并研究了Web应用程序的核心概念,例如Web服务器Web客户端HTTPHTMLWeb容器以及如何使用ServletJSP创建Web应用程序。 我们还创建了第一个Servlet和JSP Web应用程序,并在tomcat服务器上执行了它。

Servlet教程 (Servlet Tutorial)

Servlet tutorial is aimed to provide more details about java servlet, core interfaces in Java Servlet API, Servlet 3.0 annotations, life cycle of Servlet and at the end we will create a simple login servlet example application.

Servlet教程旨在提供有关Java Servlet,Java Servlet API中的核心接口,Servlet 3.0批注,Servlet的生命周期的更多详细信息,最后,我们将创建一个简单的登录Servlet示例应用程序。

  1. Servlet教程–概述 (Servlet Tutorial – Overview)

    Servlet is Java EE server driven technology to create web applications in java. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.

    All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.

    Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class.

    Servlet是Java EE服务器驱动的技术,可以用Java创建Web应用程序。 javax.servletjavax.servlet.http包提供用于编写​​我们自己的servlet的接口和类。

    所有servlet必须实现javax.servlet.Servlet接口,该接口定义了servlet生命周期方法。 在实现通用服务时,我们可以扩展Java Servlet API随附的GenericServlet类。 HttpServlet类提供用于处理HTTP特定服务的方法,例如doGet()doPost()

    大多数时候,使用HTTP协议访问Web应用程序,这就是为什么我们主要扩展HttpServlet类的原因。

  2. 通用网关接口(CGI) (Common Gateway Interface (CGI))

    Before introduction of Java Servlet API, CGI technology was used to create dynamic web applications. CGI technology has many drawbacks such as creating separate process for each request, platform dependent code (C, C++), high memory usage and slow performance.

    在引入Java Servlet API之前,曾使用CGI技术创建动态Web应用程序。 CGI技术具有许多缺点,例如为每个请求创建单独的流程,与平台有关的代码(C,C ++),较高的内存使用量和较慢的性能。

  3. CGI与Servlet (CGI vs Servlet)

    Java Servlet technology was introduced to overcome the shortcomings of CGI technology.

    • Servlets provide better performance that CGI in terms of processing time, memory utilization because servlets uses benefits of multithreading and for each request a new thread is created, that is faster than loading creating new Object for each request with CGI.
    • Servlets and platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on operating systems such as Windows, Linux, Unix, Solaris, Mac etc.
    • Servlets are robust because container takes care of life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection etc.
    • Servlets are maintainable and learning curve is small because all we need to take care is business logic for our application.

    引入Java Servlet技术来克服CGI技术的缺点。

    • Servlet在处理时间,内存利用率方面提供了比CGI更好的性能,因为Servlet利用了多线程的优势,并且为每个请求创建了一个新线程,这比为CGI为每个请求加载创建新对象要快。
    • 用Servlet开发的Web应用程序与Servlet和平台和系统无关,可以在任何标准的Web容器上运行,例如Tomcat,JBoss,Glassfish服务器以及在Windows,Linux,Unix,Solaris,Mac等操作系统上。
    • Servlet的功能强大,因为容器负责Servlet的生命周期,因此我们无需担心内存泄漏,安全性,垃圾回收等问题。
    • Servlet是可维护的,学习曲线很小,因为我们需要注意的是应用程序的业务逻辑。
  4. Servlet API层次结构 (Servlet API Hierarchy)

    javax.servlet.Servlet is the base of Servlet API. There are some other interfaces and classes that we should be aware of when working with Servlets. Also with Servlet 3.0 specs, servlet API introduced the use of annotations rather than having all the servlet configuration in the deployment descriptor. In this section, we will look into important Servlet API interfaces, classes and annotations that we will use further in developing our application. The below diagram shows servlet API hierarchy.

    1. Servlet Interface

      javax.servlet.Servlet is the base interface of Java Servlet API. Servlet interface declares the life cycle methods of servlet. All the servlet classes are required to implement this interface. The methods declared in this interface are:

      1. public abstract void init(ServletConfig paramServletConfig) throws ServletException – This is the very important method that is invoked by servlet container to initialized the servlet and ServletConfig parameters. The servlet is not ready to process client request until unless init() method is finished executing. This method is called only once in servlet lifecycle and make Servlet class different from normal java objects. We can extend this method in our servlet classes to initialize resources such as DB Connection, Socket connection etc.
      2. public abstract ServletConfig getServletConfig() – This method returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. We can use this method to get the init parameters of servlet defines in deployment descriptor (web.xml) or through annotation in Servlet 3. We will look into ServletConfig interface later on.
      3. public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException – This method is responsible for processing the client request. Whenever servlet container receives any request, it creates a new thread and execute the service() method by passing request and response as argument. Servlets usually run in multi-threaded environment, so it’s developer responsibility to keep shared resources thread-safe using .
      4. public abstract String getServletInfo() – This method returns string containing information about the servlet, such as its author, version, and copyright. The string returned should be plain text and can’t have markups.
      5. public abstract void destroy() – This method can be called only once in servlet life cycle and used to close any open resources. This is like finalize method of a java class.
    2. ServletConfig Interface

      javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

      The important methods of ServletConfig interface are:

      1. public abstract ServletContext getServletContext() – This method returns the ServletContext object for the servlet. We will look into ServletContext interface in next section.
      2. public abstract Enumeration<String> getInitParameterNames() – This method returns the Enumeration<String> of name of init parameters defined for the servlet. If there are no init parameters defined, this method returns empty enumeration.
      3. public abstract String getInitParameter(String paramString) – This method can be used to get the specific init parameter value by name. If parameter is not present with the name, it returns null.
    3. ServletContext interface

      javax.servlet.ServletContext interface provides access to web application variables to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet engines may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

      Some of the important methods of ServletContext are:

      1. public abstract ServletContext getContext(String uripath) – This method returns ServletContext object for a particular uripath or null if not available or not visible to the servlet.
      2. public abstract URL getResource(String path) throws MalformedURLException – This method return URL object allowing access to any content resource requested. We can access items whether they reside on the local file system, a remote file system, a database, or a remote network site without knowing the specific details of how to obtain the resources.
      3. public abstract InputStream getResourceAsStream(String path) – This method returns an input stream to the given resource path or null if not found.
      4. public abstract RequestDispatcher getRequestDispatcher(String urlpath) – This method is mostly used to obtain a reference to another servlet. After obtaining a RequestDispatcher, the servlet programmer forward a request to the target component or include content from it.
      5. public abstract void log(String msg) – This method is used to write given message string to the servlet log file.
      6. public abstract Object getAttribute(String name) – Return the object attribute for the given name. We can get enumeration of all the attributes using public abstract Enumeration<String> getAttributeNames() method.
      7. public abstract void setAttribute(String paramString, Object paramObject) – This method is used to set the attribute with application scope. The attribute will be accessible to all the other servlets having access to this ServletContext. We can remove an attribute using public abstract void removeAttribute(String paramString) method.
      8. String getInitParameter(String name) – This method returns the String value for the init parameter defined with name in web.xml, returns null if parameter name doesn’t exist. We can use Enumeration<String> getInitParameterNames() to get enumeration of all the init parameter names.
      9. boolean setInitParameter(String paramString1, String paramString2) – We can use this method to set init parameters to the application.

      Note: Ideally the name of this interface should be ApplicationContext because it’s for the application and not specific to any servlet. Also don’t get confused it with the servlet context passed in the URL to access the web application.

    4. ServletRequest interface

      ServletRequest interface is used to provide client request information to the servlet. Servlet container creates ServletRequest object from client request and pass it to the servlet service() method for processing.

      Some of the important methods of ServletRequest interface are:

      1. Object getAttribute(String name) – This method returns the value of named attribute as Object and null if it’s not present. We can use getAttributeNames() method to get the enumeration of attribute names for the request. This interface also provide methods for setting and removing attributes.
      2. String getParameter(String name) – This method returns the request parameter as String. We can use getParameterNames() method to get the enumeration of parameter names for the request.
      3. String getServerName() – returns the hostname of the server.
      4. int getServerPort() – returns the port number of the server on which it’s listening.

      The child interface of ServletRequest is HttpServletRequest that contains some other methods for session management, cookies and authorization of request.

    5. ServletResponse interface

      ServletResponse interface is used by servlet in sending response to the client. Servlet container creates the ServletResponse object and pass it to servlet service() method and later use the response object to generate the HTML response for client.

      Some of the important methods in HttpServletResponse are:

      1. void addCookie(Cookie cookie) – Used to add cookie to the response.
      2. void addHeader(String name, String value) – used to add a response header with the given name and value.
      3. String encodeURL(java.lang.String url) – encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
      4. String getHeader(String name) – return the value for the specified header, or null if this header has not been set.
      5. void sendRedirect(String location) – used to send a temporary redirect response to the client using the specified redirect location URL.
      6. void setStatus(int sc) – used to set the status code for the response.
    6. RequestDispatcher interface

      RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in the same context. We can also use this to include the content of another resource to the response. This interface is used for servlet communication within the same context.

      There are two methods defined in this interface:

      1. void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
      2. void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.

      We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.

    7. GenericServlet class

      GenericServlet is an that implements Servlet, ServletConfig and Serializable interface. GenericServlet provide default implementation of all the Servlet life cycle methods and ServletConfig methods and makes our life easier when we extend this class, we need to override only the methods we want and rest of them we can work with the default implementation. Most of the methods defined in this class are only for easy access to common methods defined in Servlet and ServletConfig interfaces.

      One of the important method in GenericServlet class is no-argument init() method and we should override this method in our servlet program if we have to initialize some resources before processing any request from servlet.

    8. HTTPServlet class

      HTTPServlet is an abstract class that extends GenericServlet and provides the base for creating HTTP based web applications. There are methods defined to be overridden by subclasses for different HTTP methods.

      1. doGet(), for HTTP GET requests
      2. doPost(), for HTTP POST requests
      3. doPut(), for HTTP PUT requests
      4. doDelete(), for HTTP DELETE requests

    javax.servlet.Servlet是Servlet API的基本 。 使用Servlet时,还应注意其他一些接口和类。 同样在Servlet 3.0规范中,Servlet API引入了注释的使用,而不是将所有Servlet配置都包含在部署描述符中。 在本节中,我们将研究重要的Servlet API接口,类和注释,我们将在开发应用程序时进一步使用它们。 下图显示了Servlet API层次结构。

    1. Servlet接口

      javax.servlet.ServletJava Servlet API的基本接口。 Servlet接口声明Servlet的生命周期方法。 所有Servlet类都是实现此接口所必需的。 在此接口中声明的方法是:

      1. 公共抽象void init(ServletConfig paramServletConfig)引发ServletException-这是servlet容器调用以初始化servlet和ServletConfig参数的非常重要的方法。 除非init()方法完成执行,否则servlet尚未准备好处理客户端请求。 此方法在servlet生命周期中仅被调用一次,并使Servlet类不同于普通的java对象。 我们可以在servlet类中扩展此方法以初始化资源,例如DB Connection,Socket连接等。
      2. 公共抽象ServletConfig getServletConfig() -此方法返回一个servlet配置对象,其中包含该servlet的所有初始化参数和启动配置。 我们可以使用此方法来获取部署描述符(web.xml)中或通过Servlet 3中的注释定义的servlet的初始参数。稍后我们将研究ServletConfig接口。
      3. 公共抽象无效服务(ServletRequest req,ServletResponse res)抛出ServletException,IOException-此方法负责处理客户端请求。 每当servlet容器收到任何请求时,它都会创建一个新线程并通过将请求和响应作为参数传递来执行service()方法。 Servlet通常在多线程环境中运行,因此开发人员有责任使用保持共享资源线程安全。
      4. public abstract String getServletInfo() –此方法返回包含有关servlet信息的字符串,例如其作者,版本和版权。 返回的字符串应为纯文本,不能包含标记。
      5. public abstract void destroy() –此方法在Servlet生命周期中只能调用一次,并用于关闭所有开放资源。 这就像java类的finalize方法。
    2. ServletConfig接口

      javax.servlet.ServletConfig用于将配置信息传递给Servlet。 每个servlet都有自己的ServletConfig对象,并且servlet容器负责实例化此对象。 我们可以在web.xml文件中或通过使用WebInitParam批注提供servlet初始化参数。 我们可以使用getServletConfig()方法来获取Servlet的ServletConfig对象。

      ServletConfig接口的重要方法是:

      1. 公共抽象ServletContext getServletContext() -此方法返回Servlet的ServletContext对象。 在下一节中,我们将研究ServletContext接口。
      2. 公共抽象Enumeration <String> getInitParameterNames() –此方法返回为servlet定义的初始化参数名称的Enumeration <String>。 如果没有定义初始化参数,则此方法返回空枚举。
      3. 公共抽象字符串getInitParameter(String paramString) -此方法可用于按名称获取特定的初始化参数值。 如果参数不带名称,则返回null。
    3. ServletContext接口

      javax.servlet.ServletContext接口提供对servlet的Web应用程序变量的访问。 ServletContext是唯一的对象,可用于Web应用程序中的所有Servlet。 当我们希望某些初始化参数可用于Web应用程序中的多个或所有servlet时,我们可以使用ServletContext对象,并使用<context-param>元素在web.xml中定义参数。 我们可以通过ServletConfig的getServletContext()方法获取ServletContext对象。 Servlet引擎还可以提供一组Servlet特有的上下文对象,该上下文对象与主机的URL路径名称空间的特定部分相关联。

      ServletContext的一些重要方法是:

      1. 公共抽象ServletContext getContext(String uripath) -此方法为特定的uripath返回ServletContext对象;如果该属性不可用或对servlet不可见,则返回null。
      2. 公共抽象URL getResource(String path)引发MalformedURLException-此方法返回URL对象,允许访问所请求的任何内容资源。 我们可以访问项目,无论它们驻留在本地文件系统,远程文件系统,数据库还是远程网络站点上,而无需了解如何获取资源的具体细节。
      3. 公共抽象InputStream getResourceAsStream(String path) –此方法将输入流返回到给定的资源路径;如果找不到,则返回null。
      4. 公共抽象RequestDispatcher getRequestDispatcher(String urlpath) –此方法主要用于获取对另一个servlet的引用。 获得RequestDispatcher之后,该Servlet程序员将请求转发到目标组件或包含其中的内容。
      5. public abstract void log(String msg) -此方法用于将给定的消息字符串写入servlet日志文件。
      6. 公共抽象对象getAttribute(String name) –返回给定名称的对象属性。 我们可以使用公共抽象Enumeration <String> getAttributeNames()方法获取所有属性的枚举
      7. public abstract void setAttribute(String paramString,Object paramObject) –此方法用于设置应用程序范围内的属性。 所有其他有权访问此ServletContext的servlet均可访问该属性。 我们可以使用公共抽象void removeAttribute(String paramString)方法删除属性。
      8. String getInitParameter(String name) –此方法返回用web.xml中的name定义的init参数的String值,如果参数名不存在,则返回null。 我们可以使用Enumeration <String> getInitParameterNames()来获取所有初始化参数名称的枚举。
      9. boolean setInitParameter(String paramString1,String paramString2) –我们可以使用此方法为应用程序设置初始化参数。

      注意 :理想情况下,此接口的名称应为ApplicationContext,因为它用于应用程序,而不特定于任何servlet。 也不要将其与URL中传递的servlet上下文混淆,以访问Web应用程序。

    4. ServletRequest接口

      ServletRequest接口用于向Servlet提供客户端请求信息。 Servlet容器根据客户端请求创建ServletRequest对象,并将其传递给servlet service()方法进行处理。

      ServletRequest接口的一些重要方法是:

      1. Object getAttribute(String name) –此方法将命名属性的值作为Object返回,如果不存在,则返回null。 我们可以使用getAttributeNames()方法获取请求的属性名称的枚举。 该接口还提供了用于设置和删除属性的方法。
      2. String getParameter(String name) –此方法以String形式返回请求参数。 我们可以使用getParameterNames()方法获取请求的参数名称的枚举。
      3. 字符串getServerName() –返回服务器的主机名。
      4. int getServerPort() –返回正在侦听的服务器的端口号。

      ServletRequest的子接口是HttpServletRequest ,它包含其他一些用于会话管理,cookie和请求授权的方法。

    5. ServletResponse接口

      Servlet使用ServletResponse接口将响应发送到客户端。 Servlet容器创建ServletResponse对象,并将其传递给servlet service()方法,然后使用响应对象为客户端生成HTML响应。

      HttpServletResponse中的一些重要方法是:

      1. void addCookie(Cookie cookie) –用于将cookie添加到响应中。
      2. void addHeader(String name,String value) –用于添加具有给定名称和值的响应头。
      3. String encodeURL(java.lang.String url) –通过在其中包含会话ID对指定的URL进行编码,或者,如果不需要编码,则返回不变的URL。
      4. String getHeader(String name) –返回指定标头的值,如果尚未设置此标头,则返回null。
      5. void sendRedirect(String location) –用于使用指定的重定向位置URL向客户端发送临时重定向响应。
      6. setStatus(int sc) —用于设置响应的状态码。
    6. RequestDispatcher接口

      RequestDispatcher接口用于将请求转发到另一个资源,该资源可以是同一上下文中HTML,JSP或另一个servlet。 我们还可以使用它来将另一个资源的内容包括到响应中。 此接口用于同一上下文中的servlet通信。

      此接口中定义了两种方法:

      1. void forward(ServletRequest请求,ServletResponse响应) –将请求从Servlet转发到服务器上的另一个资源(Servlet,JSP文件或HTML文件)。
      2. void include(ServletRequest request,ServletResponse response) –在响应中包含资源的内容(Servlet,JSP页面,HTML文件)。

      我们可以使用ServletContext的getRequestDispatcher(String path)方法在Servlet中获取RequestDispatcher。 该路径必须以/开头,并被解释为相对于当前上下文根。

    7. GenericServlet类

      GenericServlet是实现Servlet,ServletConfig和Serializable接口的 。 GenericServlet提供所有Servlet生命周期方法和ServletConfig方法的默认实现,并且在扩展此类时使我们的生活更轻松,我们只需要覆盖所需的方法,其余方法可以使用默认实现。 此类中定义的大多数方法仅用于轻松访问Servlet和ServletConfig接口中定义的通用方法。

      GenericServlet类中的重要方法之一是无参数init()方法,如果在处理来自Servlet的任何请求之前必须初始化一些资源,则应在Servlet程序中重写此方法。

    8. HTTPServlet类

      HTTPServlet是扩展GenericServlet的抽象类,并提供了创建基于HTTP的Web应用程序的基础。 对于不同的HTTP方法,有一些方法定义为被子类覆盖。

      1. doGet(),用于HTTP GET请求
      2. doPost(),用于HTTP POST请求
      3. doPut(),用于HTTP PUT请求
      4. doDelete(),用于HTTP DELETE请求
  5. Servlet属性 (Servlet Attributes)

    Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.

    ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.

    Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

    Servlet属性用于Servlet间的通信,我们可以在Web应用程序中设置,获取和删除属性。 servlet属性有三个范围- 请求范围会话范围应用程序范围

    ServletRequestHttpSessionServletContext接口分别提供了从请求,会话和应用程序范围获取/设置/删除属性的方法。

    Servlet属性与web.xml中为ServletConfig或ServletContext定义的初始化参数不同。

  6. Servlet 3中的注释 (Annotations in Servlet 3)

    Prior to Servlet 3, all the servlet mapping and its init parameters were used to defined in web.xml, this was not convenient and more error-prone when the number of servlets is huge in an application.

    Servlet 3 introduced use of to define a servlet, filter and listener servlets and init parameters.

    Some of the important Servlet annotations are:

    1. WebServlet – We can use this annotation with Servlet classes to define init parameters, loadOnStartup value, description and url patterns etc. At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both. The class on which this annotation is declared MUST extend HttpServlet.
    2. WebInitParam – This annotation is used to define init parameters for servlet or filter, it contains name, value pair and we can provide description also. This annotation can be used within a WebFilter or WebServlet annotation.
    3. WebFilter – This annotation is used to declare a servlet filter. This annotation is processed by the container during deployment, the Filter class in which it is found will be created as per the configuration and applied to the URL patterns, Servlets and DispatcherTypes. The annotated class MUST implement javax.servlet.Filter interface.
    4. WebListener – The annotation used to declare a listener for various types of event, in a given web application context.

    Note: We will look into Servlet Filters and Listeners in future articles, in this article our focus is to learn about base interfaces and classes of Servlet API.

    在Servlet 3之前,所有servlet映射及其init参数都已在web.xml中定义,当应用程序中的servlet数量巨大时,这样做不方便且更容易出错。

    Servlet 3引入了使用来定义servlet,过滤器和侦听器servlet以及init参数的方法。

    一些重要的Servlet注释是:

    1. WebServlet –我们可以将此注释与Servlet类一起使用,以定义初始化参数,loadOnStartup值,描述和url模式等。必须在注释的value或urlPattern属性中至少声明一个URL模式,但不能同时声明两者。 声明此注释的类必须扩展HttpServlet。
    2. WebInitParam –此注释用于定义servlet或过滤器的初始化参数,它包含名称,值对,我们还可以提供描述。 可以在WebFilter或WebServlet批注中使用此批注。
    3. WebFilter –此注释用于声明servlet过滤器。 容器在部署期间会处理此批注,将根据配置创建在其中找到它的Filter类,并将其应用于URL模式,Servlet和DispatcherTypes。 带注释的类必须实现javax.servlet.Filter接口。
    4. WebListener –在给定的Web应用程序上下文中,用于声明各种事件的侦听器的注释。

    注意:在以后的文章中,我们将研究Servlet过滤器和侦听器,在本文中,我们的重点是学习Servlet API的基本接口和类。

  7. Java Servlet登录示例 (Java Servlet Login Example)

    Now we are ready to create our login servlet example, in this example, I will use simple HTML, JSP, and servlet that will authenticate the user credentials. We will also see the use of ServletContext init parameters, attributes, ServletConfig init parameters and RequestDispatcher include() and response sendRedirect() usage.

    Our Final Dynamic Web Project will look like below image. I am using Eclipse and Tomcat for the application, the process to create dynamic web project is provided in tutorial.

    Here is our login HTML page, we will put it in the welcome files list in the web.xml so that when we launch the application it will open the login page.

    If the login will be successful, the user will be presented with new JSP page with login successful message. JSP page code is like below.

    <%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%>
    Login Success Page

    Hi Pankaj, Login successful.

    Login Page

    Here is the web.xml deployment descriptor file where we have defined servlet context init parameters and welcome page.

    Here is our final Servlet class for authenticating the user credentials, notice the use of annotations for Servlet configuration and ServletConfig init parameters.

    package com.journaldev.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet Tutorial - Servlet Example */@WebServlet(		description = "Login Servlet", 		urlPatterns = { "/LoginServlet" }, 		initParams = { 				@WebInitParam(name = "user", value = "Pankaj"), 				@WebInitParam(name = "password", value = "journaldev")		})public class LoginServlet extends HttpServlet {	private static final long serialVersionUID = 1L;           	public void init() throws ServletException {		//we can create DB connection resource here and set it to Servlet context		if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&				getServletContext().getInitParameter("dbUser").equals("mysql_user") &&				getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))		getServletContext().setAttribute("DB_Success", "True");		else throw new ServletException("DB Connection error");	}		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//get request parameters for userID and password		String user = request.getParameter("user");		String pwd = request.getParameter("pwd");				//get servlet config init params		String userID = getServletConfig().getInitParameter("user");		String password = getServletConfig().getInitParameter("password");		//logging example		log("User="+user+"::password="+pwd);				if(userID.equals(user) && password.equals(pwd)){			response.sendRedirect("LoginSuccess.jsp");		}else{			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");			PrintWriter out= response.getWriter();			out.println("Either user name or password is wrong.");			rd.include(request, response);					}			}}

    Below screenshots shows the different pages of our Servlet Example project, based on the user password combinations for successful login and failed logins.

    现在我们准备创建我们的登录servlet示例,在这个示例中,我将使用简单HTML,JSP和servlet来验证用户凭据。 我们还将看到ServletContext初始化参数,属性,ServletConfig初始化参数以及RequestDispatcher include()和response sendRedirect()用法的使用。

    我们的最终动态Web项目将如下图所示。 我正在为应用程序使用Eclipse和Tomcat, 教程中提供了创建动态Web项目的过程。

    这是我们的登录HTML页面,我们将其放在web.xml的欢迎文件列表中,以便在启动应用程序时它将打开登录页面。

    如果登录成功,将向用户显示新的JSP页面以及登录成功消息。 JSP页面代码如下所示。

    <%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%>
    Login Success Page

    Hi Pankaj, Login successful.

    Login Page

    这是web.xml部署描述符文件,我们在其中定义了servlet上下文初始化参数和欢迎页面。

    这是我们用于验证用户凭据的最终Servlet类,请注意对Servlet配置和ServletConfig初始化参数使用了注释。

    package com.journaldev.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet Tutorial - Servlet Example */@WebServlet(		description = "Login Servlet", 		urlPatterns = { "/LoginServlet" }, 		initParams = { 				@WebInitParam(name = "user", value = "Pankaj"), 				@WebInitParam(name = "password", value = "journaldev")		})public class LoginServlet extends HttpServlet {	private static final long serialVersionUID = 1L;           	public void init() throws ServletException {		//we can create DB connection resource here and set it to Servlet context		if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&				getServletContext().getInitParameter("dbUser").equals("mysql_user") &&				getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))		getServletContext().setAttribute("DB_Success", "True");		else throw new ServletException("DB Connection error");	}		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//get request parameters for userID and password		String user = request.getParameter("user");		String pwd = request.getParameter("pwd");				//get servlet config init params		String userID = getServletConfig().getInitParameter("user");		String password = getServletConfig().getInitParameter("password");		//logging example		log("User="+user+"::password="+pwd);				if(userID.equals(user) && password.equals(pwd)){			response.sendRedirect("LoginSuccess.jsp");		}else{			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");			PrintWriter out= response.getWriter();			out.println("Either user name or password is wrong.");			rd.include(request, response);					}			}}

    下面的屏幕快照根据成功登录和失败登录的用户密码组合,显示了Servlet示例项目的不同页面。

That’s all for Servlet Tutorial for beginners, in next tutorial we will look into Session Management, Servlet Filters and Listeners.

对于初学者的Servlet教程而言,这就是全部。在下一个教程中,我们将研究会话管理,Servlet过滤器和侦听器。

Update: Check out next article in series, .

更新:请查阅系列文章的下一篇

翻译自:

java servlet

转载地址:http://awlzd.baihongyu.com/

你可能感兴趣的文章
android驱动在win10系统上安装的心酸历程
查看>>
优雅的程序员
查看>>
oracle之三 自动任务调度
查看>>
Android dex分包方案
查看>>
ThreadLocal为什么要用WeakReference
查看>>
删除本地文件
查看>>
FOC实现概述
查看>>
base64编码的图片字节流存入html页面中的显示
查看>>
这个大学时代的博客不在维护了,请移步到我的新博客
查看>>
GUI学习之二十一——QSlider、QScroll、QDial学习总结
查看>>
nginx反向代理docker registry报”blob upload unknown"解决办法
查看>>
gethostbyname与sockaddr_in的完美组合
查看>>
kibana的query string syntax 笔记
查看>>
旋转变换(一)旋转矩阵
查看>>
thinkphp3.2.3 bug集锦
查看>>
[BZOJ 4010] 菜肴制作
查看>>
C# 创建 读取 更新 XML文件
查看>>
KD树
查看>>
VsVim - Shortcut Key (快捷键)
查看>>
C++练习 | 模板与泛式编程练习(1)
查看>>