Java web Learning notes-Servlet, web Learning notes-servlet

Source: Internet
Author: User

Java web Learning notes-Servlet, web Learning notes-servlet
Servlet basics 1. Servlet Overview

The predecessor of JSP is Servlet. Servlet is a small program running on the server. A Servlet is a Java class that can be accessed through the "request-response" programming model in the server memory.

2. Tomcat container level

Tomcat containers are classified into four levels. Servlet containers manage the Context container. One Context corresponds to one Web project.

3. Manually write the first Servlet

Writing a Servlet program requires three steps: Inheriting HttpServlet --> rewriting doGet () or doPost () method --> registering Servlet in web. xml.

HttpServlet inheritance

Rewrite the doGet or doPost method depends on the Request Method.

1. Compile a class that inherits from HttpRequest and override doGet (or doPost method) to create a servlet. MyServlet. java in the src directory of the project.

1 package servlet; 2 3 import java. io. IOException; 4 import java. io. printWriter; 5 6 import javax. servlet. servletException; 7 import javax. servlet. http. httpServlet; 8 import javax. servlet. http. httpServletRequest; 9 import javax. servlet. http. httpServletResponse; 10 11/** inherited from HttpServlet */12 public class HelloServlet extends HttpServlet {13 14/** override doGet Method */15 @ Override16 protected void doGet (HttpS ErvletRequest request, HttpServletResponse response) 17 throws ServletException, IOException {18 System. out. println ("process get requests... "); 19 PrintWriter out = response. getWriter (); 20 out. println ("<B> HelloServlet </B>"); 21} 22 23/** rewrite the doPost Method */24 @ Override25 protected void doPost (HttpServletRequest request, HttpServletResponse response) 26 throws ServletException, IOException {27 System. out. println ("processing post requests... "); 28 PrintWriter out = response. getWriter (); 29 out. println (" <B> HelloServlet </B> "); 30} 31 32}

2. register the newly created Servlet in WEB-INF/web. xml:

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <web-app version = "2.5" 3 xmlns = "http://java.sun.com/xml/ns/javaee" 4 xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" 5 xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <display-name> </display-name> 8 <welcome-file-list> 9 <welcome-file> index. jsp </welcome-file> 10 </welcome-file-list> 11 12 <! -- Start Servlet registration --> 13 <servlet> 14 <servlet-name> HelloServlet </servlet-name> 15 <servlet-class> servlet. helloServlet </servlet-class> 16 </servlet> 17 <servlet-mapping> 18 <servlet-name> HelloServlet </servlet-name> 19 <url-pattern>/servlet/ helloServlet </url-pattern> 20 </servlet-mapping> 21 <! -- Servlet Registration ended --> 22 23 </web-app>

Specifically, servlet-name indicates the Servlet name, servlet-class indicates the definition of the class to be written (package name. class name), and url-pattern indicates the Servlet Path.

Use a custom Servlet in index. jsp to process get and post requests.

1 <% @ page language = "java" import = "java. util. *" contentType = "text/html; charset = UTF-8" %> 2 <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 3 

Release the project and run the following results:

4. Use MyEclipse to compile Servlet

1. src --> new Servlet.

2. Override the doGet () or doPost () methods.

3. Deploy and run.

When a Servlet is created using MyEclipse, It is inherited from HttpServlet by default. By default, the override init (), destory (), doGet (), and doPost () methods are checked, and the Servlet is automatically registered with web. xml.

We can find that the Servlet created using MyEclipse has automatically generated an html template for our output. We only need to make a few changes.

5. Servlet Execution Process and lifecycle

The user clicks the hyperlink to send a request to the Servlet --> the server is on the web. in xml, servlet-mapping looks for the URL address corresponding to the Servlet --> finds the corresponding Servlet name --> finds the processing class related to the Servlet according to the Servlet name --> Based on the requested determine whether to call the doGet or doPost method.

    The lifecycle of a Servlet is roughly divided into three phases:

  

1. The client sends a request to the server.

2. The server starts to accept the request. First, judge whether the requested servlet instance exists. If not, first load a servlet class and create an instance.

If yes, call the service method of the servlet directly, and then determine whether to call the doGet method or the doPost method.

3. After the servlet creates an instance, it calls the init Method for initialization. Then call the servce method to determine whether to call the doGet or doPost method.

4. Check whether the server is shut down. If yes, call the destroy method.

 

The following example shows the Servlet lifecycle:

The first is a Servlet: TestServlet1

1 package servlet; 2 3 import java. io. IOException; 4 import java. io. printWriter; 5 6 import javax. servlet. servletException; 7 import javax. servlet. http. httpServlet; 8 import javax. servlet. http. httpServletRequest; 9 import javax. servlet. http. httpServletResponse; 10 11 public class TestServlet1 extends HttpServlet {12 13 public TestServlet1 () {14 System. out. println ("TestServlet1 constructor is executed! "); 15} 16 17 public void destroy () {18 System. out. println (" TestServlet1 destruction method is executed! "); 19} 20 21 public void doGet (HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException {23 24 System. out. println (" TestServlet1 doGet method is executed! "); 25 response. setContentType (" text/html; charset = UTF-8 "); 26 PrintWriter out = response. getWriter (); 27 out. println (" <! Doctype html public \ "-// W3C // dtd html 4.01 Transitional // EN \"> "); 28 out. println ("<HTML>"); 29 out. println ("<HEAD> <TITLE> A Servlet </TITLE> </HEAD>"); 30 out. println ("<BODY>"); 31 out. println ("

Home page index. jsp

1 <% @ page language = "java" import = "java. util. * "contentType =" text/html; charset = UTF-8 "%> 2 <% 3 String path = request. getContextPath (); 4 String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; 5%> 6 7 <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 8 

When the server is started for the first time when we access index. jsp, the constructor method, the initialization method, and the doGet () method are executed.

When we request this page again, only the doGet () method is executed:

The destroy method is executed when the server is shut down.

6. Three cases of Tomcat loading Servlet

The Servlet container loads the Servlet at the following time points:

1. Some servlets are automatically loaded when the Servlet container starts. To achieve this, you only need to add the following code between <Servlet> </servlet> in the web. xml file:

<load-on-startup>1</load-on-startup>

The smaller the number, the higher the priority.

For example, in web. xml, set TestServlet2 to 1, TestServlet1 to 2, and start and stop Tomcat:

If the priority is high, start or close the service first.

2. The client sends a request to a Servlet for the first time. [For more information, see the Servlet lifecycle example]

3. After the Servlet class is modified, the Tomcat container will reload the Servlet.

After the Servlet is loaded, the Servlet container will create a Servlet instance and call the Servlet init () method for initialization. The init () method is called only once in the real life cycle of the Servlet.

7. Relationship between Servlet and JSP built-in objects

8. Servlet to obtain form data

    

9. Servlet route jump 10. Phase case use MVC Architecture to implement the project

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.