Servlet learning phase II

Posted by railanc4309 on Thu, 09 Dec 2021 17:37:00 +0100

HttpServletRequest class

What is the role of the HttpServletRequest class

Every time a Request enters the Tomcat server, the Tomcat server parses and encapsulates the requested HTTP protocol information into the Request object. Then it is passed to the service methods (doGet and doPost) for us to use. We can get the information of all requests through the HttpServletRequest object.

Common methods of HttpServletRequest class


Common API sample codes:

public class RequestAPIServlet extends HttpServlet {
@Override 
protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
// 	i.getRequestURI() gets the resource path of the request 
	System.out.println("URI => " + req.getRequestURI()); 
// 	ii.getRequestURL() gets the uniform resource locator (absolute path) of the request 		
	System.out.println("URL => " + req.getRequestURL());
	// iii.getRemoteHost() get the ip address of the client 
	/*** In IDEA, when using localhost to access, the client ip address is = = > > > 127.0 0.1<br/> 
	* In IDEA, use 127.0 When accessing 0.1, the client ip address is = = > > > 127.0 0.1<br/> 
	* In IDEA, when using real ip access, the obtained client ip address is = = = > > > real client ip address < br / > 
	* */
	System.out.println("client ip address => " + req.getRemoteHost());
	// iv.getHeader() get request header
	System.out.println("Request header User-Agent ==>> " + req.getHeader("User-Agent"));
	// vii.getMethod() gets the method of the request GET or POST
	System.out.println( "Request mode ==>> " + req.getMethod() );
	}
}

How to get request parameters

Let's write a form first, which will contain our request parameters:

<body> 
<form action="http://localhost:8080/07_servlet/parameterServlet" method="get"> 
	user name:<input type="text" name="username"><br/> 
	password:<input type="password" name="password"><br/> 
	hobby:<input type="checkbox" name="hobby" value="cpp">C++ 
	<input type="checkbox" name="hobby" value="java">Java <input type="checkbox" name="hobby" value="js">JavaScript<br/> 
    <input type="submit"> 
</form> 
</body>

Then we can use the servlet program to receive these parameters:

public class ParameterServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Get request parameters
	String username = req.getParameter("username"); 
	String password = req.getParameter("password"); 
	String[] hobby = req.getParameterValues("hobby");
	System.out.println("user name:" + username);
	System.out.println("password:" + password); 	
	System.out.println("hobby:" + Arrays.asList(hobby));
	}
}	

Chinese garbled code resolution of doGet request:

// Get request parameters 
String username = req.getParameter("username"); 
//1 code with iso8859-1 first 
//2. Decode with utf-8. username = new 
String(username.getBytes("iso-8859-1"), "UTF-8");

Chinese garbled code solution for POST request

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// Set the character set of the request body to UTF-8, so as to solve the Chinese garbled code problem of the post request
	//The call is valid until the request parameter is obtained.
	req.setCharacterEncoding("UTF-8");
	System.out.println("-------------doPost------------");
	// Get request parameters
	String username = req.getParameter("username");
	String password = req.getParameter("password");
	String[] hobby = req.getParameterValues("hobby");
	System.out.println("user name:" + username); 
	System.out.println("password:" + password); 	
	System.out.println("hobby:" + Arrays.asList(hobby));
}

Forwarding of requests

What is request forwarding?
Request forwarding refers to the operation that the server jumps from one resource to another after receiving the request, which is called request forwarding.

We can do this:
First, prepare two servlet programs, servlet1 and servlet2:

package com.atguigu.servlet;

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

public class servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }
}

package com.atguigu.servlet;

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

public class servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

Don't forget to go to the web To configure the servlet program in XML, I will directly omit to start writing code here:
Write servlet1 first, because we assume that the service request will access the servlet1 program first:

package com.atguigu.servlet;

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

public class servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get request parameters
        String username = req.getParameter("username");
        System.out.println("stay servlet1(View parameters (materials) in counter 1):"+username);

        //Stamp a chapter on the material and pass it to servlet2 (counter 2) program to check
        req.setAttribute("key1","Seal of counter 1");

        //Ask for directions. How can I get to servlet2 (counter 2)
        /*
        Request forwarding must begin with a slash, / slash indicates that the address is: htp://ip:port/ Project name /, mapped to web directory of IDEA code
         */
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");

        //After knowing how to go, go to that place
        //That is, forward the request, jump to the servlet2 program, and pass the req and resp of this visit
        requestDispatcher.forward(req,resp);
    }
}

Now write the program of servlet2:

package com.atguigu.servlet;

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

public class servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get request parameters
        String username = req.getParameter("username");
        System.out.println("stay servlet2(View parameters (materials) in counter 2):"+username);

        //Check whether counter 1 is stamped
        Object key1 = req.getAttribute("key1");
        System.out.println("Does counter 1 have a seal:"+key1);

        //Handle your own business
        System.out.println("servlet2 Handle your own business");
    }
}

Access servlet1 and carry the previous request parameter:

It can be seen in the console;

To summarize, there are several characteristics of request forwarding:
1. The browser address bar has not changed

You can see that although both servlet1 and servlet2 are executed this time, the address bar still only displays servlet1

2. Although they are two servlet programs, they execute one request

Because our req and resp are both req and resp in the same request

3. They share data in the request field

The reason is the paragraph in 2 above

4. It can be forwarded to the WEB-INF directory

By default, the files in the WEB-INF directory are protected. The browser cannot directly access the data in it, and a 404 error will be reported, but it can be accessed by request forwarding

5. Can I access resources other than the project

No, for example, I can't forward it to Baidu's official website, because the servlet can only be forwarded to other resources in the project

Role of base tag

Problem introduction:
When we use the a tag in html to jump the page, we can jump and return easily. When we use servlet to jump, we can only jump and cannot return correctly. At this time, we need our base tag to work.

For example:

Relative and absolute paths in the Web

Different meanings of / slash in web

HttpServletResponse class

Role of HttpServletResponse class

The HttpServletResponse class is the same as the HttpServletRequest class.

Every time a request comes in, the Tomcat server will create a Response object and pass it to the Servlet program for use. HttpServletRequest represents the information from the request, and HttpServletResponse represents the information of all responses. If we need to set the information returned to the client, we can set it through the HttpServletResponse object.

Description of two output streams

These two output streams are used to return the servlet's return body to the client.

Only one of two streams can be used at the same time.

If the byte stream is used, the character stream can no longer be used, and vice versa, otherwise an error will be reported.

How to return data to the client

Requirement: return string data to the client.

Garbled response resolution

request redirections

Request redirection means that the client sends a request to the server, and then the server tells the client. I'll give you some addresses. You visit the new address. Call request redirection (because the previous address may have been discarded).

Topics: Java Tomcat servlet intellij-idea