当前位置:网站首页>Technology point 7: servlet program

Technology point 7: servlet program

2020-11-10 17:23:28 Guo Shao

Servlet Program

One 、Servlet technology

1、 What is? Servlet

  ① Servlet yes JavaEE One of the norms . A specification is an interface

  ② Servlet Just JavaWeb One of the three components . The three components are :Servlet Program 、Filter filter 、Listener Monitor .

  ③ Servlet It's one that runs on the server java Applet , It can Receive requests from clients , And respond the data to the client .

2、 Manual implementation Servlet Program

  ① Write a class to implement Servlet Interface :

 

 

 

  ② rewrite service() Method , Processing requests , And respond to the data :

package com.zixue.servlet;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 10:57
 */
public class HelloServlet implements Servlet {
    @Override
    public void init(ServletConfig config) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("HelloServlet Was interviewed ");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

  ③ To web.xml To configure Servlet Program access address :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    servlet Label to Tomcat Server configuration Servlet Program -->
    <servlet>
<!--        servlet-name Label to Servlet The program has an alias ( It's usually a class name )-->
        <servlet-name>HelloServlet</servlet-name>
<!--        servlet-class The label is Servlet The full class name of the program -->
        <servlet-class>com.zixue.servlet.HelloServlet</servlet-class>
    </servlet>
<!--    servlet-mapping Label to Servlet Program configuration access address -->
    <servlet-mapping>
<!--        servlet-name The tag is the configured access address to which Servlet Used by the program -->
        <servlet-name>HelloServlet</servlet-name>
<!--        url-pattern Tag configuration access address 
            / :  When the server is parsing , The path of is expressed as :http://ip:port/ Project path  ( Mapping to web Catalog )
            /helloServlet :  Express this Servlet The access address of the program is :http://ip:port/ Project path /helloServlet
-->
        <url-pattern>/helloServlet</url-pattern>
    </servlet-mapping>

</web-app>

3、url Address to Servlet Access to the program

 

 

4、Servlet Life cycle of

   ① perform Servlet Constructor method ;

  ② perform init Initialization method ;

  ③ perform service Method ;

  ④ perform destroy Destruction method .

notes :

  ① and ② It was created on the first visit Servlet When the program calls ;

  ③ Every visit calls ;

  ④ Throughout web Call when the project stops .

package com.zixue.servlet;

import com.sun.media.sound.SoftTuning;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 10:57
 */
public class HelloServlet implements Servlet {

    public HelloServlet() {
        System.out.println("1. Constructor method execution ");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("2.init Initialize method execution ");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("3.HelloServlet Was interviewed ");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("4. perform destroy Destruction method ");
    }
}

   Browser address bar first visit :

 

 

 

 

 

    Continue to visit :

 

 

    When you stop the whole thing web During the project :

 

 

 

 

 

 5、GET and POST Distribution processing of requests

   We are service Method to do the request distribution processing .service There is a parameter position of the method ServletRequest Interface , It has a sub interface HttpServletRequest, There's a way inside it getMethod(), This method can realize the distribution of requests .

 

 

    stay web Next create a form.html file , How to provide a request GET/POST:

 

 

   form.html file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Distribution of requests </title>
</head>
<body>
<form action="http://localhost:8080/06_servlet/helloServlet1" method="get">
    <input type="submit" />
</form>
</body>
</html>

   To visit Servlet Program :HelloServlet1.java

package com.zixue.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 11:26
 */
public class HelloServlet1 implements Servlet {
    @Override
    public void init(ServletConfig config) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        //1. Type conversion :ServletRequest -- httpServletRequest( It has getMethod())
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        //2. How to get the request 
        String method = httpServletRequest.getMethod();
        if ("GET".equals(method)){
            doGet();
        }else if ("POST".equals(method)){
            doPost();
        }
    }

    /**
     *  do GET Requested operation 
     */
    public void doGet(){
        System.out.println("GET request ");
        System.out.println("GET request ");
    }

    /**
     *  do POST Requested operation 
     */
    public void doPost(){
        System.out.println("POST request ");
        System.out.println("POST request ");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

   Browser address bar access form.html file :

 

 

 

 

 

    give the result as follows :

 

 

    modify form.html The request mode in the file is post:

 

 

    The effect of the second visit is as follows :

 

 

 

6、 By inheritance HttpServlet Realization Servlet Program

   Usually in the actual project development , It's all about inheritance HttpServlet Class to implement Servlet Program .

Specific implementation steps :

  ① Write a class to inherit HttpServlet class :

  ② Rewrite according to business needs doGet() or doPost() Method :

  ③ To web.xml Middle configuration Servlet Program access address ;

HelloServlet2.java:

package com.zixue.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 11:53
 */
public class HelloServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 Of doGet Method ");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 Of doPost Method ");
    }
}

web.xml:

 

 

 7、 Use IDEA establish Servlet Program  

 

 

  To configure Servlet Information about :

 

 

 web.xml Configure the access address in :

 

 

 8、Servlet Class inheritance system

 

 

 

Two 、ServletConfig class

  ServletConfig From the class name , I knew it was Servlet Program configuration information class .
  Servlet Procedure and ServletConfig Objects are created by Tomcat Responsible for creating , We are responsible for using .
  Servlet By default, the program is created the first time it is accessed ,ServletConfig Is each Servlet When the program is created , Just create a corresponding ServletConfig object .

1、ServletConfig The three functions of classes

  ① obtain Servlet Program alias servlet-name Value ;

  ② Get initialization parameters init-param Value ;

  ③ obtain ServletContext object .

web.xml Configuration in :

 

 

 Servlet The code in :

 

 

  The effect is as follows :

 

 

  Be careful :

  

 

 

  3、 ... and 、ServletContext class

1、 What is? ServletContext?

  ① ServletContext It's an interface , It said Servlet Context object ;

  ②  One web engineering , only one ServletContext Object instances ;

  ③ ServletContext Object is a domain object ;

  ④ ServletContext Is in web Create when project deployment starts . stay web Destroy when the project stops .

What is domain object ?
   Domain object , It can be like Map The same object that accesses data , A domain is called an object .
   The domain here refers to the operating range of accessing data , Whole web engineering .

 

 

 2、ServletContext The four functions of a class

  ①  obtain web.xml The context parameters configured in the context-param;

  ②  Get the current project path , Format : / Project path ;

  ③  Get the absolute path on the server hard disk after project deployment ;

  ④  image Map And access data .

web.xml Configuration in : 

 

  demonstration ServletContext The code that works :

package com.zixue.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 13:41
 */
public class Servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. obtain web.xml The context parameters configured in the 
        ServletContext context = getServletContext();
        String username = context.getInitParameter("username");
        System.out.println(" Context parameters username = " + username);
        String password = context.getInitParameter("password");
        System.out.println(" Context parameters password = " + password);

        //2. Get the current project path   Format :/ Project path 
        System.out.println(" Current engineering path :" + context.getContextPath());

        //3. Get the absolute path on the server disk after project deployment 
        System.out.println(" The path of project deployment is :" + context.getRealPath("/"));
    }
}

The effect is as follows :

 

  The current project is in the following location on the server disk :

 

 

ServletContext image Map And access data :

ContextServlet1 Code :

package com.zixue.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 13:57
 */
public class ContextServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletContext();
        System.out.println(" Before saving ,ContextServlet1 obtain key The value of is :" + context.getAttribute("key"));
        context.setAttribute("key", "value");
        System.out.println(" After preservation ,ContextServlet1 obtain key The value of is :" + context.getAttribute("key"));
    }
}

ContextServlet2 Code :

package com.zixue.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 13:59
 */
public class ContextServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletContext();
        System.out.println("ContextServlet2 From key The value is :" + context.getAttribute("key"));
    }
}

   notes :ServletContext The object is in the whole web There is only one copy of the project , Domain data cannot be obtained until it is saved . When the domain data is saved , No matter where Servlet All programs can be accessed .

 

Four 、HTTP agreement

1、 What is? HTTP agreement

What is an agreement ?
   Agreement means both parties , Or more , Make a mutual agreement , Rules that everyone needs to follow , It's called an agreement .
   So-called HTTP agreement , Is refers to , When communicating between client and server , Data sent , Rules to follow , It's called HTTP agreement .
  HTTP Data in a protocol is also called a message . 

2、 Requested HTTP Form of agreement

 

 

 

 

 

 

 

 3、 Which are GET request , Which are POST request

GET request :

  ① form In the tag method=get

  ② a label

  ③ link Tags introduced css

  ④ script Tags introduced js

  ⑤ img The tag introduces the picture

  ⑥ iframe introduce html page

  ⑦ In the browser address bar, enter the address and press enter

POST request :

  form In the tag method=post

 

4、 Responsive HTTP Form of agreement

 

 

 

 

5、 Commonly used response code description

  200  ---  The request is successful

  302  ---  request redirections

  404  ---  Browser address bar address not found

  500  ---  Server code error

 

5、 ... and 、HttpServletRequest class

1、HttpServletRequest What does a class do

   Every time you have a request to enter Tomcat The server ,Tomcat The server will send the request over HTTP The protocol information is parsed and packaged to Request In the object . Then pass it on to service Method (doGet and doPost) For us to use . We can go through HttpServletRequest object , Get all the requested information .

2、HttpServletRequest Common methods of class

 

 

RequestAPIServlet.java:

package com.zixue.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr Guo
 * @create 2020-11-10 14:51
 */
public class RequestAPIServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Get the requested resource path 
        System.out.println("URI = " + req.getRequestURI());
        //2. Get the requested uniform resource locator 
        System.out.println("URL = " + req.getRequestURL());
        //3. Get client's ip Address 
        System.out.println(" client ip The address is :" + req.getRemoteHost());
        //4. Get request header 
        System.out.println(" Request header User-Agent The value of is :" + req.getHeader("User-Agent"));
        //5. Get request parameters 
        System.out.println(" Request parameters username = " + req.getParameter("username"));
        System.out.println(" Request parameters password = " + req.getParameter("password"));
        //6. How to get the request 
        System.out.println(" The request method is :" + req.getMethod());
    }
}

Browser address bar access :

 

  The effect is as follows :

 

 3、POST The requested Chinese garbled code is solved

 

 

4、 Request forwarding  

What is request forwarding ?
   Request forwarding means , After the server receives the request , The operation of jumping from one resource to another is called request forwarding .

 

 

Servlet1 Code :

public class Servlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Request forwarding 
        //1. Get the requested parameters 
        String username = request.getParameter("username");
        System.out.println("Servlet1 Request parameters in username = " + username);

        //2. towards request Save data in domain 
        request.setAttribute("key","value");

        //3. Get the requested forwarding object 
        /*
         Request forwarding must start with a slash ,/  A slash indicates that the address is :http://ip:port/ project name / ,  Mapping to  IDEA  Code  web  Catalog 
         */
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");

        //4. Go to Servlet2
        requestDispatcher.forward(request,response);
    }
}

Servlet2 Code :

public class Servlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Get the requested parameters 
        String username = request.getParameter("username");
        System.out.println("Servlet2 Request parameters in username = " + username);

        //2. obtain request Data stored in the domain 
        System.out.println(request.getAttribute("key"));

        //3. Deal with your own business 
        System.out.println("Servlet2 My business ");
    }
}

Browser address bar access :

 

  The effect is as follows :

 

 

5、base The role of labels

stay web There is a index.html page , The contents are as follows :

 

  stay web/a/b There is a c.html page , The contents are as follows :

 

  The directory structure is as follows :

 

    Start the current project , By default, the current project will be accessed index.html page :

 

    Click hyperlink a The tag will jump to c.html page :

 

    There is no problem with the jump between them ( You can jump back and forth ). Explain the following :

     All relative paths will jump relative to the address in the browser address bar when jumping . stay index.html page , The address in the browser address bar is :http://localhost:8080/06_servlet/index.html. Mapping to the current project web Under the table of contents . Click hyperlink , The address of the hyperlink is :a/b/c.html. There's no problem with the jump at this point . stay c.html page , The address of the browser address bar is :http://localhost:8080/06_servlet/a/b/c.html. Click hyperlink , The hyperlink address is :../../index.html. Father's father just maps to web Catalog , There is no problem with the jump at this time .

 

Jump with request forwarding :

   Servlet Program ForwardC.java as follows :

 

    After the start of the project , Default access index.html page , here , We visit ForwardC This Servlet Program :http://localhost:8080/06_servlet/forwardC. It will be forwarded to c.html page :

 

   here , Click hyperlink , The hyperlink address is :../../index.html. Browser address bar address is :http://localhost:8080/06_servlet/forwardC. At this time, we can't access index.html Page .

that , How to solve this problem ?

Use base label :

 

 

6、Web Relative path and absolute path in

 

 

7、web in / Different meanings of slashes

 

 

6、 ... and 、HttpServletResponse class

1、HttpServletResponse The role of classes

  HttpServletResponse Classes and HttpServletRequest Similar to class . Every time I ask to come in ,Tomcat The server will create a Response Object passed to Servlet Program to use .HttpServletRequest This is a request for information ,HttpServletResponse Information that represents all responses , If we need to set the information returned to the client , Both can pass HttpServletResponse Object to set

2、 Description of two output streams

 

 

   Two streams can only use one at a time .
   Using byte streams , You can't use character streams anymore , vice versa , Otherwise you will report an error .

3、 How to send data back to the client

public class ResponseIOServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.write("response's content");
    }
}

The effect is as follows :

 

 4、 Response to the garbled solution

   When we try to return data with Chinese to the client :

 

 

   There will be the following garbled problems :

 

    How to solve it ?

 

    The effect is as follows :

 

 

5、 request redirections

   request redirections , It means that the client sends a request to the server , Then the server tells the client that . I'll give you some addresses . You go to the new address to visit . Request redirection ( Because the previous address may have been abandoned ).

 

 Response1 Code :

 

 Response2 Code :

 

  The effect is as follows :

 

版权声明
本文为[Guo Shao]所创,转载请带上原文链接,感谢