本文共 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客户端 , HTTP和HTML , Web容器以及如何使用Servlet和JSP创建Web应用程序。 我们还创建了第一个Servlet和JSP Web应用程序,并在tomcat服务器上执行了它。
Servlet教程旨在提供有关Java Servlet,Java Servlet API中的核心接口,Servlet 3.0批注,Servlet的生命周期的更多详细信息,最后,我们将创建一个简单的登录Servlet示例应用程序。
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.servlet
和javax.servlet.http
包提供用于编写我们自己的servlet的接口和类。
所有servlet必须实现javax.servlet.Servlet
接口,该接口定义了servlet生命周期方法。 在实现通用服务时,我们可以扩展Java Servlet API随附的GenericServlet
类。 HttpServlet
类提供用于处理HTTP特定服务的方法,例如doGet()
和doPost()
。
大多数时候,使用HTTP协议访问Web应用程序,这就是为什么我们主要扩展HttpServlet类的原因。
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 ++),较高的内存使用量和较慢的性能。
Java Servlet technology was introduced to overcome the shortcomings of CGI technology.
引入Java Servlet技术来克服CGI技术的缺点。
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.
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:
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 .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:
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:
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.
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:
getAttributeNames()
method to get the enumeration of attribute names for the request. This interface also provide methods for setting and removing attributes.getParameterNames()
method to get the enumeration of parameter names for the request.The child interface of ServletRequest
is HttpServletRequest
that contains some other methods for session management, cookies and authorization of request.
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:
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:
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.
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.
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.
javax.servlet.Servlet
是Servlet API的基本 。 使用Servlet时,还应注意其他一些接口和类。 同样在Servlet 3.0规范中,Servlet API引入了注释的使用,而不是将所有Servlet配置都包含在部署描述符中。 在本节中,我们将研究重要的Servlet API接口,类和注释,我们将在开发应用程序时进一步使用它们。 下图显示了Servlet API层次结构。
javax.servlet.Servlet
是Java Servlet API的基本接口。 Servlet接口声明Servlet的生命周期方法。 所有Servlet类都是实现此接口所必需的。 在此接口中声明的方法是:
service()
方法。 Servlet通常在多线程环境中运行,因此开发人员有责任使用保持共享资源线程安全。 javax.servlet.ServletConfig
用于将配置信息传递给Servlet。 每个servlet都有自己的ServletConfig对象,并且servlet容器负责实例化此对象。 我们可以在web.xml文件中或通过使用WebInitParam
批注提供servlet初始化参数。 我们可以使用getServletConfig()方法来获取Servlet的ServletConfig对象。
ServletConfig接口的重要方法是:
javax.servlet.ServletContext
接口提供对servlet的Web应用程序变量的访问。 ServletContext是唯一的对象,可用于Web应用程序中的所有Servlet。 当我们希望某些初始化参数可用于Web应用程序中的多个或所有servlet时,我们可以使用ServletContext对象,并使用<context-param>元素在web.xml中定义参数。 我们可以通过ServletConfig的getServletContext()方法获取ServletContext对象。 Servlet引擎还可以提供一组Servlet特有的上下文对象,该上下文对象与主机的URL路径名称空间的特定部分相关联。
ServletContext的一些重要方法是:
注意 :理想情况下,此接口的名称应为ApplicationContext,因为它用于应用程序,而不特定于任何servlet。 也不要将其与URL中传递的servlet上下文混淆,以访问Web应用程序。
ServletRequest接口用于向Servlet提供客户端请求信息。 Servlet容器根据客户端请求创建ServletRequest对象,并将其传递给servlet service()方法进行处理。
ServletRequest接口的一些重要方法是:
getAttributeNames()
方法获取请求的属性名称的枚举。 该接口还提供了用于设置和删除属性的方法。 getParameterNames()
方法获取请求的参数名称的枚举。 ServletRequest
的子接口是HttpServletRequest
,它包含其他一些用于会话管理,cookie和请求授权的方法。
Servlet使用ServletResponse接口将响应发送到客户端。 Servlet容器创建ServletResponse对象,并将其传递给servlet service()方法,然后使用响应对象为客户端生成HTML响应。
HttpServletResponse中的一些重要方法是:
RequestDispatcher接口用于将请求转发到另一个资源,该资源可以是同一上下文中HTML,JSP或另一个servlet。 我们还可以使用它来将另一个资源的内容包括到响应中。 此接口用于同一上下文中的servlet通信。
此接口中定义了两种方法:
我们可以使用ServletContext的getRequestDispatcher(String path)方法在Servlet中获取RequestDispatcher。 该路径必须以/开头,并被解释为相对于当前上下文根。
GenericServlet是实现Servlet,ServletConfig和Serializable接口的 。 GenericServlet提供所有Servlet生命周期方法和ServletConfig方法的默认实现,并且在扩展此类时使我们的生活更轻松,我们只需要覆盖所需的方法,其余方法可以使用默认实现。 此类中定义的大多数方法仅用于轻松访问Servlet和ServletConfig接口中定义的通用方法。
GenericServlet类中的重要方法之一是无参数init()方法,如果在处理来自Servlet的任何请求之前必须初始化一些资源,则应在Servlet程序中重写此方法。
HTTPServlet是扩展GenericServlet的抽象类,并提供了创建基于HTTP的Web应用程序的基础。 对于不同的HTTP方法,有一些方法定义为被子类覆盖。
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属性有三个范围- 请求范围 , 会话范围和应用程序范围 。
ServletRequest , HttpSession和ServletContext接口分别提供了从请求,会话和应用程序范围获取/设置/删除属性的方法。
Servlet属性与web.xml中为ServletConfig或ServletContext定义的初始化参数不同。
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:
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注释是:
注意:在以后的文章中,我们将研究Servlet过滤器和侦听器,在本文中,我们的重点是学习Servlet API的基本接口和类。
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/