One. What is it

1. An overview of the

Servlet is the technology used by Sun Company to develop dynamic Web. The interface provided by Sun Company in API is called servlet. In Java, it can also be said that the Java program realizing the servlet interface is called servlet (essentially Java program).Copy the code

Two. Why

Because web servers (Tomcat, Weblogic, IIS, Apache)** do not have the ability to process dynamic resource requests **(that is, the request needs to be calculated), can only handle static resource requests (if the browser requests an HTML page, the Web server checks whether the requested HTML page exists, it does return. ) If you want a Web server to handle requests for dynamic resources, you need to use a CGI component-container approach. Servlets are concrete implementations of web servers handling dynamic resources.Copy the code

Three. How to use it

1. Developing a servlet program requires two steps:

<1>. Write a class that implements the servlet interface

<2>. Deploy the developed Java classes to the Web server

2. Code implementation

<1> Create the Maven project

I. Create a normal Maven project as a parent project (build directly without using modules)

II. Import dependencies of servlet and JSP

III. Create a Web project (module build Maven) as a sub-project

IV. Modify web. XML to the latest version to complete the structure of Maven

<2>. Write a servlet program

I. Write a generic class that implements the Servlet interface (directly inheriting HTTPServlet)

public class ServletDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); // Response stream write.print("hello"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp) } }Copy the code

Register servlets and write servlet mappings in ii.web.xml

Why mapping: Written classes are Java programs, and browser access needs to connect to a Web server, so we need to register our servlet in the Web service and give the browser a path to access itCopy the code
<! -- Register a servlet--> <servlet> < servletname >ServletDemo</ servletname > <servlet-class>com.itcast.servlet.HelloServlet</servlet-class> </servlet> <! -- Servlet request path --> < servletmapping > < servletname >ServletDemo</ servletname > <url-pattern>/itcast</url-pattern> </servlet-mapping>Copy the code

III. The configuration of tomcat

Note that the release path of the project is configuredCopy the code

IV. Start the test

http://localhost:8080/alex  
Copy the code

4. The servlet principle

Servlets are invoked by a Web server that receives a browser request...Copy the code

1. Servlt has two default implementation classes:

Sun provides two default implementation classes for the Servlet interface, HTTPServlet GenericServletCopy the code

<1>. Inheritance:

  HTTPServlet extend GenericServlet
  GenericServlet extend servlet
Copy the code

<2>.

<3>. Analysis of rewriting doGet and doPost methods

I. Top-level interface servlet

II.GenericServlet

III.HTTPServlet

2. Principle and process

<1>. The browser makes a request to the Web container (Tomcat)

The first time you access the sent request, target's class file is generated and the written servlet is generatedCopy the code

<2>. Tomcat produces two objects: request and response

<3>. The request and response object calls the Service method in the servlet to handle the request and response

<4>. The two implementation classes I overwrite actually handle requests and responses

<5>. The Web container (tomcat) reads the response

<6>. Tomcat returns the response to the client (browser)

3. Schematic diagram of principle and process

5. Mapping web. XML in servlet

1. Configure resolution

Register a servlet in <1>.xml

<! -- Register a servlet--> <servlet> < servletname >ServletDemo</ servletname > <servlet-class>com.itcast.servlet.HelloServlet</servlet-class> </servlet>Copy the code

<2> Mapping path

I A servlet specifies a mapping path

<! -- Servlet request path --> < servletmapping > < servletname >ServletDemo</ servletname > <url-pattern>/itcast</url-pattern> </servlet-mapping>Copy the code

II. A servlet specifies multiple mapping paths

<servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/itcast</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/itheima</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/it</url-pattern>
</servlet-mapping>
Copy the code

III. A servlet specifies the generic mapping path

<! -- Default request path --> <servlet-mapping> <servlet-name>ServletDemo</servlet-name> <url-pattern>/itcast/*</url-pattern> </servlet-mapping>Copy the code

IV. Default request path (do not use it)

<! /* This will cause the request not to enter the index on the home page. Higher priority --> <servlet-mapping> <servlet-name>ServletDemo</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>Copy the code

V. Customize suffix and prefix request mapping

<! -- Default request path --> <servlet-mapping> <servlet-name>ServletDemo</servlet-name> <url-pattern>*.itcast</url-pattern> </servlet-mapping>Copy the code

<3> Mapping priority problem

2. Application scenarios

< 1 > 404 pages

I. ervlet write

Ii.xml to register servlets and write mapper mapping paths

Six servlet3.0.

Annotation development to simplify the complexity of web.xml configuration servletsCopy the code

1. Write a servlet and inherit httpServlet

2. Use annotations instead of XML configuration

// @WebServlet(name = "QuickServlet",urlPatterns = "/quickServlet") // @WebServlet(urlPatterns = "/quickServlet") // @webServlet (value = "/quickServlet") @webservlet ("/quickServlet") // There is only one attribute in the annotation, the attribute name can be omitted when named value... public class QuickServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("QuickServlet.... 3.0 "); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); }}Copy the code

3. Configure tomcat and test it

7. The ServletContext object

1. What is it:

The Web Container (Tomcat), when started, creates a ServletContext object for each Web application that represents the current Web application. Servlets need to go through a middleman to communicate with each other. IO is more cumbersome, so a ServletContext can be used as a middleman (the data is stored in the ServletContext, where all servlets can get the saved data) to enable session sharingCopy the code



2. What to do:

<1> share data :(replaced by session)

The data I save in one servlet is available in the other;Copy the code

I. Write servlets to access data

II. Write mapping mappings

<2> Get initialization parameters

See <1> for servlets that share dataCopy the code

<3> Request forwarding (url unchanged) (replaced by request)

<4> Read resource files (used extensively in projects) (replaced by classloading, reflection)

Note: For maven, Java and Resources in the main directory are collectively referred to as classpath, and properties files are packaged into target classes regardless of whether they are stored in Java or resources. Solutions that cannot be exported using resources in MavenCopy the code

I. View common methods of the Properties class

II. Write the properties file and view the class path

III. Write a servlet

IV. Write a Mapping mapping

V. testing

Eight. HttpServletResponse object

1. What is

HttpServletResponse Extend The ServletResponse Web server accepts an HTTP request from a client for which, Create an HttpServletResponse and an HttpServletRequest object representing the request and response, respectively; To get the parameters requested by the client, look for HttpServletRequest. To give the client some information about the response, use HttpServletResponseCopy the code

2. Why

Learning servlets is about learning request and response objectsCopy the code

3. How does it work

<1> Simple classification of common methods:

I. Send data to the browser

II. The method responsible for sending the response header to the browser

III. Set the status code of the response

<2> Common applications (the following applications are in the response directory)

I. Output messages to the browser

II. Download files

This requirement is in the Java foundation, the first three steps are strings, the last steps are IO streams, and the following is implemented in JavaWebCopy the code
I. ervlet write
① Get the path and file name of the downloaded file ② set the browser to support what we want to download ③ Get the input stream of the downloaded file ④ Create a buffer ⑤ Get the OutpUTStream object ⑥ Write the FileOutputStream to the buffer buffer ⑦ Use OutpUTStream to output buffer data to the clientCopy the code

Ii. Servlet registers and writes mapping paths

Iii. To deploy tomcat

Iv. Test the downloaded file

III. Verification code implementation

I. Front and rear end separation using different techniques:
Js and other technologies can be used in the front end of the Java image class to generate a pictureCopy the code
Ii. The following is implemented with back-end technology
(1) the servlet to writeCopy the code

② Register servlet and write mapping mapping pathCopy the code

IV. Implement redirection (URL change) (emphasis)

Principle of i.
When a servlet wants to find another servlet, it tells the middleman first, and then the middleman tells the servlet where to find the other servletCopy the code
Ii. The scene
1>. Write a servletCopy the code

2>. Register the servlet and write the mapping mapping pathCopy the code

3>. Test accessCopy the code

Login Demo exercise 1>. Main page and access success page preparationCopy the code



2 >. Write a servletCopy the code

3>. Deploy Tomcat and test accessCopy the code

Nine. It

1. What is it:

Represents a request from a client. The user accesses the server through HTTP. All information in the HTTP request is encapsulated in an HttpServletRequest objectCopy the code

2, How to use:

<1> Common methods

<2> Common applications

I. Obtain parameters passed by the front-end

II. Request Forwarding (Login Demo Exercise)

I. Homepage and login success page preparation

Ii. Write servlet

Iii. Register servlet and write mapping

Iv. To deploy tomcat

V. Test access