Java programmers written interview Collection Chapter 5 Java Web: 5.1 Servlet and JSP (1-8 questions)

5.1.1 page request workflow is like

A Web application are generally composed of two parts client and server-side routines. Among them, the client mainly refers to the user and the browser, users can find the resources needed by the browser, but these resources are located on the server. Browser software is a tool, it has two main functions: one is completed and server-side interaction; the second is complete HTML (Hyper-Text Markup Language, HTML, used to tell the browser how to present content to the user) of resolution, enabling users need to view resource information to show up in an intuitive form. Client server to receive incoming requests and processes the request, find the resources requested by the client, and finally find the resources back to the client, these resources include HTML pages, images, audio, video, the contents of PDF documents.

1) users to request the resources required to enter through a browser link.

2) the browser accepts the user's request, and the request is assembled into the specified format to the transmission server to perform specific interactions between the client and the server through HTTP. Wherein the data stream request is mainly contained in HTTP (HyperText Transfer Protocol, Hypertext Transfer Protocol, a protocol to establish the TCP / IP on the basis of, mainly used for communication between the client and server side) The method of the request (GET or POST ), Web address (URL, uniform resource Lo-cator , uniform resource locator) request and parameters for information requests.

3) the server receives a request sent by the client, and find the resources needed by the user.

4) Find the resource server requested by the user, to the resources back to the client.

5) After the server returns the response message assembled by the message into a specific format to the client, this process is done via HTTP. The response data stream mainly comprises a status code (representing a request success or failure), Content-type (e.g. text, picture, HTML, etc.), the response content of the message (content images or HTML format).

6) HTML browser to parse the response and the results presented to the user.


5.1.2 HTTP GET in what is the difference and the POST method

The method of HTTP requests there are many types, such as GET, POST, HEAD, TRACE, OPTIONS , etc., but GET and POST are the two most commonly used methods. Which, GET is the simplest kind of request method, its main function is to get the user required resources from the server, and as a response back to the client, these resources can be anything HTML pages, images, documents, and in one of but need to note that the role of the gET method is mainly used to obtain information about the server-side resource, just like a database query operations, it would not affect their own state resources , such as delete, modify or add resources are not Allowed. The POST method provides more powerful functions than the GET method, which in addition to taking resources from the server, but also can upload data to the server.

Although the GET method is mainly used to get data from the server, you can also upload data to the server, but generally do not recommend using GET method to upload data to the server, but is recommended to use the POST method to achieve this function. Specifically, there are the following two reasons:

1) When using GET method to upload data to the server, add data to the general behind the URL, and both use "?", Connecting with "&" between the various variables. Since there is a limit on the length of the URL, so the use of this method can upload data amount is very small, usually around 1024Byte. POST method while data transfer is carried out by attachment HTTP request, larger amount of data transferred, the default is generally unrestricted.

2) As the GET method to upload data is added in the URL, so the uploaded data is completely "exposed" out, inherent security risks, especially when users need to submit sensitive information to the server. The POST method to submit content to the server in the URL is not displayed in plain text, it is invisible to the user, so the security is better.


5.1.3 What is a Servlet

HTML can only be used to store static content, but usually, static pages difficult to meet the needs of practical applications, in view of this, the concept of dynamic pages are introduced. The so-called dynamic pages, means the ability to display different content depending on the time, different user pages, such as a common forums, message boards, e-commerce sites are implemented by a dynamic page. So how can generate dynamic pages? One method is to use the Common Gateway Interface (Common Gateway Interface, CGI). CGI is a program written in Perl script that can be used to generate dynamic pages , and the other way is the use of Servlet technology .

What is the Servlet it? Servlet is the use of server-side program written in the Java language that runs on the Web server Servlet container, whose main function is to provide Web services model request / response, can generate dynamic Web content , which is not available in HTML function.

Compared with other technologies that generate dynamic pages, Servlet has many advantages, specifically, mainly in the following aspects:

1) better portability. Since the Java language and strong cross-platform portability features, making Servlet also has good portability, that is, without having to modify the code can be deployed on a variety of different types of Web servers.

2) implementation of high efficiency. Because CGI created for each request a process to deal with, and Servlet creates a thread for each request to perform, and to create a thread than to create less expensive to process, compared with CGI, Servlet have shorter during the interaction response time, high response efficiency.

3) easy to use. Servlet provides many useful interface to be used to read or set the HTTP message header, and the processing Cookie trace session status.

4) scalability. Because Servlet is written in Java, so it has all the advantages of the Java language. Java language is a robust, object-oriented programming language, it is easy to expand, Servlet naturally possess the advantage.

As can be seen from the above program structure of the Servlet, the Servlet, there is no main () method, even the so-called entry methods are not, then it is in the end is how to implement it? In fact, it is performed under the control of the container, the container often used for the Tomcat. When the Web server gets a request for a Servlet, which will pass the request to the server corresponding to the processing container, the container in response to the requesting client by the method (the doGet () or the doPost ()) call to the Servlet.

Specifically, Servlet client request has the following steps:

1) a user by clicking on a link to initiate a request to the Servlet.

2) Web server after receiving the request, the request will be processed to the respective container, when the container is found that the request to initiate the Servlet container case creates two objects: HttpServletResponse and HttpServletRequest.

3) Servlet container may find the corresponding message according to the URL in the request message, and then creates a separate thread for the request, while the two objects 2) created in step is transferred to the newly created thread in the form of parameters.

4) Servlet container call service () method is accomplished in response to user requests, service () method calls doPost () or doGet () method to perform specific tasks in response, while the generated dynamic page back to the container.

5) the container assembly into HTTP format response message back to the client. In this case, the thread running over, delete the two objects 2) created in step.

Figure 5-2 shows the above-described process.

Container will be processed to create a new thread for each request, and it will create HttpServletRe-sponse and HttpServletRequest two objects for each request. After processing thread will quit.

5.1.4 doPost () method doGet () method how to select

As can be seen from the Web HTTP request processing flow of the container, the final request to the Servlet will be processed by the Servlet to process the request calls the service () method, service () method invokes the doPost The different request types are () method (for processing POST request) or doGet () method (for processing GET requests) to handle the user request, to achieve responsiveness to customers. If the request is GET, calls the doGet () method; if the request is POST, calls the doPost () method. Servlet interface and in the GenericServlet (a generic, not specific to any Servlet protocol, it implements Servlet interface) is not doGet () method and doPost () method, and these methods HttpServlet defined, but are returned error information, when defining a Servlet, must implement doGet () method or doPost () method. doGet and doPost accept requests (the HttpServletRequest) and response (HttpServletResponse).

Specifically, when the HTTP request method attribute for the get, call doGet () method; when the method attribute is post, then call doPost () method.


5.1.5 What is Servlet life cycle

由于 Servlet 运行在容器中,没有 main()方法,因此,整个生命周期都是由容器来控制的。简单而言,Servlet 的生命周期只有两个状态:未创建状态与初始化状态。这两种状态的转换主要是由 3 个重要的方法来进行控制:init()、service()和 destroy()。其中,init()方法是 Servlet 生命的起点,用于创建或打开任何与 Servlet 相关的资源以及执行初始化工作。service()方法是 Servlet 中真正处理客户端传过来的请求的方法,它根据 HTTP 请求方法(GET、POST 等)将请求分发到 doGet()、doPost()等方法。destroy()方法释放任何在 init()方法中打开的与 Servlet 相关的资源。

具体而言,Servlet 的生命周期可以分为加载、创建、初始化、处理客户请求和卸载 5 个阶段。

1)加载。容器通过类加载器使用 Servlet 类对应的文件来加载 Servlet。

2)创建。通过调用 Servlet 的构造函数来创建一个 Servlet 实例。

3)初始化。通过调用 Servlet 的 init()方法来完成初始化工作,这个方法是在 Servlet 已被创建但向客户端提供服务之前调用的,需要注意的是,init()方法只会被调用一次。

4)处理客户请求。Servlet 一旦被创建后,它就可以为客户端提供服务了。每当有新的客户请求到来时,容器都会创建一个新的线程来处理该请求,接着会调用 Servlet 的 service()方法来完成客户端的请求,当然,service()方法会根据请求的 method 属性值的不同调用决定是调用 doGet()方法还是调用 doPost()方法来完成具体的响应。

5)卸载。容器在卸载 Servlet 之前需要调用 destroy()方法,让 Servlet 自己释放其占用的系统资源,一旦 destroy 方法被调用,容器就不会再向这个 Servlet 发送任何请求消息了。如果容器需要这个 Servlet,那么就必须重新创建并初始化一个实例。需要注意的是,destroy()方法只会被调用一次。


5.1.6 JSP 有哪些优点

JSP 的引入在一定程度上解决了 Servlet 存在的缺点。其实现理念是让每个 Servlet 只负责其对应的业务逻辑的处理,让 JSP 来负责用户的 HTML 显示,因此实现了业务逻辑与视图实现的分离,从而极大地提高了系统的可扩展性。

5.1.7 JSP 与 Servlet 有何异同

JSP 与 Servlet 的相同点为:JSP 可以被看作一个特殊的 Servlet,它只不过是对 Servlet 的扩展,只要是 JSP 可以完成的工作,使用 Servlet 都可以完成,例如生成动态页面。由于 JSP 页面最终要被转换成 Servlet 来运行,因此处理请求实际上是编译后的 Servlet。

JSP 与 Servlet 的不同点为:①Servlet 的实现方式是在 Java 中嵌入 HTML 代码,编写和修改 HTML 非常不方便,所以它比较适合做流程控制、业务处理;而 JSP 的实现方式为在 HTML 中嵌入 Java 代码,比较适合页面的显示,例如,在 Struts 框架中,Servlet 位于 MVC 设计模式的控制层,而 JSP 位于视图层。②Servlet 中没有内置对象,JSP 中的内置对象都是必须通过 HttpServletRequest 对象、HttpServletResponse 对象以及 HttpServlet 对象得到。


5.1.8 如何使用 JSP 与 Servlet 实现 MVC 模型

MVC 是 Model(模型)、View(视图)和 Controller(控制器)3 个单词的首字母组合。MVC 是一种目前广泛流行的应用模型,其目的是实现 Web 系统的职能分工。图 5-4 为 MVC 模型关系图,其中模型层实现系统中的业务逻辑,通常可以用 JavaBean 或 EJB 来实现;视图层则用于与用户的交互,通常用 JSP 来实现;控制层则是模型与视图之间沟通的桥梁,它可以把用户的请求分派并选择恰当的视图来显示它们,同时它也可以解释用户的输入并将其映射为模型层能够执行的操作。

MVC 强制性地分离 Web 应用的输入、处理和输出,使得 MVC 应用程序被分成 3 个核心部件:模型、视图和控制器。它们各自处理自己的任务。

(1)模型(业务逻辑层)

模型表示企业数据和业务逻辑,它是应用程序的主体部分。业务流程的处理过程对其他层来说是黑箱操作,模型接收视图请求数据,并返回最终的处理结果。业务模型的设计可以说是 MVC 最主要的核心。目前流行的 EJB 模型就是一个典型的应用例子,它从应用技术实现的角度对模型做了进一步的划分,以便充分利用现有的组件,但它不能作为应用设计模型的框架。它仅仅告诉设计人员按这种模型设计就可以利用某些技术组件,从而减少了技术上的困难,可以使设计人员专注于业务模型的设计。

MVC 把应用的模型按一定的规则抽象出来。抽象的层次很重要,这也是判断设计人员是否优秀的主要依据。抽象与具体不能隔得太远,也不能太近。MVC 并没有提供模型的设计方法,而只告诉设计人员应该如何组织管理这些模型,以便于模型的重构和提高重用性。

业务模型还有一个很重要的模型那就是数据模型。数据模型主要指实体对象的数据持续化,比如将一张订单保存到数据库,从数据库获取订单,将这个模型单独列出,所有相关数据库的操作只限制在该模型中。

(2)视图(表示层)

视图是用户看到的并与之交互的界面。对早期的 Web 应用来说,视图就是由 HTML 元素组成的界面,在新式的 Web 应用中,HTML 依旧在视图中扮演着重要的角色,但一些新的技术已层出不穷,它们包括 Adobe Flash 以及诸如 XHTML、XML/XSL 等一些标识语言和 Web 服务等。

随着 Web 应用开发技术的发展,用户要求的日益提高,如何处理应用程序的界面已经变得越来越有挑战性。MVC 架构一个大的好处是它能为 Web 应用处理很多不同的视图。在视图中其实没有真正的业务处理发生,不管这些数据是联机存储的还是一个雇员列表,作为视图来讲,它只是作为一种输出数据并允许用户操纵的方式。

视图功能强大,主要表现在以下两个方面:

1)根据客户类型显示信息。

2)显示商业逻辑(模型)的结构,而不关心信息如何获得何时获得。

(3)控制器

控制器接收用户的输入并调用模型和视图去完成用户的需求。所以当用户单击 Web 页面中的超链接和发送 HTML 表单时,控制器(例如 Servlet)本身不输出任何东西,也不执行任何处理,它只是接收请求并决定调用哪个模型构件去处理请求,然后确定用哪个视图来显示模型处理返回的数据。

MVC 的处理过程是这样的:对于每一个用户输入的请求,先被控制器接收,并决定由哪个模型来进行处理,然后模型通过业务逻辑层处理用户的请求并返回数据,最后控制器用相应的视图格式化模型返回的数据,并通过显示页面呈现给用户。

MVC 这种特殊的设计结构,给应用开发带来了很多便利,通过使用 MVC 架构,大大提高了 Web 应用的开发效率,具体来说,MVC 设计结构主要有以下几个方面的优点:

1)低耦合性。由于视图层和业务层分离,这样就使得修改视图层代码时不需要重新编译模型和控制器的代码,同样,一个应用的业务流程或者业务规则的改变只需要改动 MVC 的模型层即可。因为模型与控制器和视图相分离,所以很容易改变应用程序的数据层和业务规则。

2)高重用性和可适用性。由于技术的不断进步,现在访问应用程序可以有越来越多的方式。MVC 模式允许使用各种不同样式的视图来访问同一个服务器端的代码。它包括任何 Web(HTTP)浏览器或者无线浏览器(WAP),例如,用户可以通过计算机或手机来订购某样产品,虽然订购的方式不一样,但处理订购产品的方式是一样的。由于模型返回的数据没有进行格式化,因此同样的构件能被不同的界面使用,例如,很多数据可能用 HTML 来表示,但是也有可能用 WAP 来表示,而这些表示所需要的命令仅是改变视图层的实现方式,而控制层和模型层无需做任何改变。

3)较低的生命周期成本。MVC 使得开发和维护用户接口的技术难度降低。

4)部署快速。使用 MVC 模式可以大大缩减开发时间,这使得后台开发人员集中精力于业务逻辑上,使界面开发人员(包括 HTML 和 JSP 开发人员)集中精力于表现形式上。

5)可维护性。分离视图层和业务逻辑层也使得 Web 应用更易于维护和修改。

6)有利于软件工程化管理。由于采用了分层思想,每一层不同的应用具有某些相同的特征,有利于通过工程化、工具化管理程序代码。

用 JSP 与 Servlet 实现的 MVC 模型如图 5-5 所示。

在这个 MVC 模型中,视图模块采用 JSP 来实现,主要负责数据的展现。视图可以从控制器上获取模型的状态,当然不是直接从控制器上获取,而是控制器把模型的数据放到一个视图可以访问的地方,通过间接方式来访问模型的数据。控制器采用 Servlet 来实现,客户端的所有请求都发送给 Servlet,它接收请求,并根据请求消息把它们分发给对应的 JSP 页面来响应,同时根据需求生成 JavaBean 实例供 JSP 来使用。模型采用 JavaBean 来实现,这个模块实现了实际的业务逻辑。

发布了101 篇原创文章 · 获赞 20 · 访问量 6万+

Guess you like

Origin blog.csdn.net/qq_40993412/article/details/104066398