Servelt fire

1. Common methods of HttpServlet (1)

                    (2) Servlet life cycle

2.HttpServletRequest

                     (1) Common methods 

                     (2) Various forms of front-end and back-end transmission             

Our three most commonly used classes: HttpServlet, HttpServletRequest, HttpServletResponse

1. HttpServlet

@WebServlet("/hello")
public class Hello_servlet2 extends HttpServlet {
    public void init()
    {
        System.out.println("初始化");
    }
    public void destroy()
    {
        System.out.println("destroy");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        System.out.println("hello");
        resp.getWriter().write("helloWorld");
    }
}

When we enter 127.0.0.1:8080/hello_servlet2/hello in the address bar, then tomcat will call HttpServlet, instantiate HttpServlet, and then call the init() method to initialize.

When we refresh the page and resend such a request, the init() method will not be called again, and the init() method will only be executed once

The service method will call this method every time it receives a request, and then call different methods according to the request type.

 Destory method: It will be called when the server terminates. Can the destory here be executed? If the stop button of smart tomcat is directly used, this operation is essentially to actively stop through port 8005 of tomcat, and destroy() can be triggered. If It is to kill the process directly, and it may be too late to execute destroy() at this time.

Servlet life cycle

1. When we send an http request, tomcat will instantiate HttpServlet and call the init() method, which is only executed once

2. Then call the service() method and forward it to different methods for processing according to the request type, such as doGet() method, doPost() method, etc.

3. Finally, when the server terminates, the destroy() method is called to perform a cleanup operation. This method is called only once, and then the JVM recycles resources.

Two. HttpServletRequest class

The object of the class HttpServletRequest represents the Http request. This object is automatically constructed by Tomcat. Tomcat will implement the listening port, parse the request, and construct the request.

Let's take a look at the methods provided by the HttpServletRequest class

@WebServlet("/show")
public class Showservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(req.getProtocol());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());
        stringBuilder.append("<br>");
        
        //获取首行当中所有的键对值
        Enumeration<String>headernames=req.getHeaderNames();
        while (headernames.hasMoreElements()) {
            String headerName = headernames.nextElement();
            stringBuilder.append(headerName + ": " + req.getHeader(headerName));
            stringBuilder.append("<br>");
        }
        resp.getWriter().write(stringBuilder.toString());
    }
}

When we send a request like this 

This is the request message when capturing the packet

 Let's take a look at what we finally return to the browser

Next, let's focus on the three forms of the front-end transmission to the back-end

The first form: GET, through query string 

The second form: post, and then through the form form

The third form: post. Through the form of json

Let's look at the first one first:

@WebServlet("/paramter")
public class getParamter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aa=req.getParameter("aa");
        String bb=req.getParameter("bb");
        resp.setContentType("text/html");
        resp.getWriter().write("aa="+aa+" "+"bb="+bb);
    }



}

Here we can get the key-value pairs in the query string through the getParameter() method, and we can also get the key-value pairs in the body constructed by the form form

The second type: form form

 

 

 

@WebServlet("/pat")
public class pare extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aa=req.getParameter("aa");
        String bb=req.getParameter("bb");
        resp.setContentType("text/html");
        resp.getWriter().write("aa="+aa+" "+"bb="+bb);
    }
}

Let's take a look at the relationship between them

 

The third type: json format

We use postman to send a post request

Backend code:

@WebServlet("/json")
public class jsonServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int length= req.getContentLength();
        byte[]arr=new byte[length];
        InputStream inputStream=req.getInputStream();
        inputStream.read(arr);
        String result=new String(arr,0,length);
        System.out.println(result);
         resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(result);

    }
}

 

Observing the back-end code here, we can know that data is currently transmitted through json, but the server reads out the entire body, and does not process it in the way of key-value pairs (the value cannot be obtained according to the key), and the form form can be based on The key is used to obtain the value. In order to process it in the form of key-value pairs, we use a third-party library, jackson, spring mvc, which supports data in json format. The built-in jackson library is used to parse the json format. We introduce third-party libraries through maven, and add this dependency to pom.xml

 

class Geshi{
    public int aa;
    public int bb;
}


@WebServlet("/json")
public class pare extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //json涉及到的核心对象
        ObjectMapper objectMapper=new ObjectMapper();
        //readValue把json格式的字符串转换成java对象
        Geshi result=objectMapper.readValue(req.getInputStream(),Geshi.class);
        System.out.println(result.aa+","+result.bb);


    }
}

 

 

Guess you like

Origin blog.csdn.net/m0_70386582/article/details/129817944