Illustrations & Javaweb:servlet must be known

Source: Internet
Author: User
Tags ftp file http post print object

Writer:bysocket (mud and brick pulp carpenter)

Micro-Blog: Bysocket

Watercress: Bysocket

FaceBook: Bysocket

Twitter: Bysocket

"In the blink of an eye, it was 1 months before a technical post was written. Afraid of their really unfamiliar, is the record too slow provoked. Haha, continue to high~ "

from [Java EE to understand the small things] http-related , always wanted to write some web development related. Recent project interface development is tight, and there are preparations for the new September battle. JDK IO source code on a separate paragraph, restudying see Servlet & JSP related. Review your basics and share some tips and code with everyone. Here should be a part of the source code, the development of ideas and some hand-made diagrams. Like Java, or have some experience in Java development more valuable advice.

One, the Web server

Web developers will be aware of a thing called an http server , such as JEE development-Tomcat,Jetty,. NET development-ISS and more. The HTTP server uses HTTP(Hypertext Transfer Protocol) to communicate information with the client browser. Here is the HTTP server simple interaction diagram: (from [Java EE to understand the trivial] HTTP related blog)

HTTP Server is one of the Web server , is also the most common development, naturally there are other ways to interact with the information, such as FTP file server ...

A Web server is a program that can provide documentation to the requesting browser. Its core process is

connection Process- request Process- answer process- close connection

This reminds me of a picture of the tomcat architecture :

Second, Tomcat simply say a few words

, Tomcat contains the core service modules: TheConnector connection module and the Container container. The Tomcat Server core is a servlet/jsp Container. For each HTTP request, the process is as follows

- Get Connections

- Servlet to parse requests (httpservletrequest)

-Call its service method for business processing

-Generate corresponding response (httpservletresponse)

- Close Connection

The blue line pointing to the process is the request , and the Green Line pointing to the process is the response process. That is, the above Web Server Core process: " connection process-Request process-answer process-close connection "

Third, my first servlet

What is a servlet? (Every time you keep asking yourself, what is this?) What should I do with "how"?

in the Java EE 6 documentation , the following are introduced

TheServlet is a Java applet that runs on a Web server . The servlet can obtain and respond to requests from the Web client. In general, transmission communication is carried out via HTTP, the Hypertext Transfer Protocol. ”

?
1 A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

Therefore, theServlet is an abstraction of the core work of the Web server . It does not just implement HttpServlet, it may be implemented with Ftpservlet(this I guess) and so on. Relatively a lot of web development, know is definitely httpservlet.

in the Java EE 6 documentation , the introduction of HttpServletis as follows:

"HttpServlet provides an abstract class that can be inherited to create an Http Servlet that adapts to a Web site. ”

?
1 Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.

Light say do not practice false bashi, practice a "hello,servlet/jsp world!":

?
123456789101112131415161718192021222324252627282930313233343536373839404142 import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/* * Copyright [2015] [Jeff Lee] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//** * @author Jeff Lee * @since 2015-6-25 19:46:45 *  HelloWrold案例 */@WebServlet(urlPatterns = "/helloWorld.html")public class HelloWorldServletT extends HttpServlet{        private static final long serialVersionUID = 1L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException{        // 获取输出打印对象        PrintWriter out = resp.getWriter();        out.println("Hello,Servlet/JSP World!");    }}

Right-click the Helloworldservlett.java file-run as-run on server-select Tomcat Server-finish

Wait a moment and you can see the following output on the webpage. This is the response that the client obtains from HttpServlet:

Take a Break ~ look at the ads:

The open source code is on my GitHub,-https://github.com/jeffli1993.

Third, the analysis of source code

?
1 @WebServlet(urlPatterns = "/helloWorld.html")

@WebServlet annotations are used to declare a httpservlet configuration . Wherein,urlpatters = "/helloworld.html", urlpatterns plural form, stating that at least one URL must be declared. It must exist with another value, but it cannot exist at the same time. If you want to match multiple URL paths , the following:

?
1 @WebServlet(urlPatterns = { "/helloWorld01.html", "/helloWorld02.html" }

Here is a @override that overrides the doget method of the parent class HttpServlet . Let's look at the parent class HttpServlet first. HttpServlet is an abstract class that provides the following methods:

-doget, serving HTPP GET requests

-dopost, serving HTTP POST requests

-doput, serving HTTP PUT requests

-dodelete, serving HTTP DELETE requests

...

For different requests , the subclass of HttpServlet must implement at least one method , usually one, so that the code is clearer. What does the Doget method of the father do?

?
1234567891011 protected void doGet(HttpServletRequest req, HttpServletResponse resp)        throws ServletException, IOException    {        String protocol = req.getProtocol();        String msg = lStrings.getString("http.method_get_not_supported");        if (protocol.endsWith("1.1")) {            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);        } else {            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);        }    }

Here it is simple to get the next HTTP protocol and HTTP local information, and then the protocol is 1.1, to make a 405 or 400HTTP status code response.

Back to Helloworldservlett.java here:

?
1234567 @Override protected void doget (HttpServletRequest req, HttpServletResponse resp)          throws Servletexception, IOException {      //get output Print object      printwriter out = Resp.getwriter ();      out.println ("hello,servlet/jsp world!"); }

Indicates that the Helloworldservlett accepts an Http GET request , and oom to HttpServletRequest, and executes the logical code inside and returns the response . This gets the output print object PrintWriterfrom the httpservletresponse object, and then outputs "hello,servlet/jsp world!".

It's over ! Oh, there's one more thing to add :

Print, here's a good word. It would be cumbersome to print a table, so something with a JSP appeared, a servlet's HTML avatar.

V. In-depth servlet specific process

And back to this simple get servlet code:

?
123456789101112 public class HelloWorldServletT extends HttpServlet{        private static final long serialVersionUID = 1L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException{        // 获取输出打印对象        PrintWriter out = resp.getWriter();        out.println("Hello,Servlet/JSP World!");    }}

The process is summarized as follows:

- Get the connection "/helloworld.html" from the browser (Client)

- the TOMCAT connector module passes the request to the container module

- Container module will do the following things

--Analyze HTPP request information and assemble it into httpservletrequest object

--Create a new HttpServletResponse Object

--based on the routing configuration, search for the appropriate Servletand create a thread to process the request. At this point, the thread passes the index of the Request and Response object above to the servlet

-Servlet processing logic in a new thread

-After the thread ends , return the browser a message via the httpservletresponse object's printwriter

The process diagram is as follows:

The blue line pointing to the process is the request , the Green Line pointing to the process is the response process, and the Orange Line pointing to the process is the internal process.

Some of these questions will ask:

is the servlet thread-safe?

No, a Servlet implementation class will have only one instance object , and multiple threads may access the same Servlet instance object, and thread safety issues are caused by global variables and static variables .

Therefore, the Servlet object instantiation is the first time that the servlet is requested, and if the instance object exists in memory after access, it will only disappear when the server is stopped. It does not end with the end of each thread. So the next time you access the servlet, theservlet Container will search for the appropriate servlet, and if it does not ,Container create the corresponding Servlet. And that's what we want.

Vi. Summary

Found this blog to write too much, look back. Can be written in three articles. The main points of this article are as follows

1. Simple introduction to Web server and Tomcat container

2. Development and use of the first Sevlet

3, in-depth source and API introduction to use

4. Summarize the real process of request and response

5, Welcome to click on my blog and github-blog to provide RSS subscription OH

———-http://www.bysocket.com/————-https://github.com/JeffLi1993 ———-

Illustrations & Javaweb:servlet must be known

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.