Java Web Learning Servlet series 18 HttpServletRequest object get request message line related methods

Keywords: Java Tomcat Eclipse

In the previous section, I introduced the HttpServletResponse object and common methods. This section started to learn the HttpServletRequest object and related methods. Like the previous section, I couldn't learn the methods of operating the request message line, request message header and request body. This article is to learn about the methods of requesting message lines.

1. Request message line related methods

In the request message line, you need to master the following methods

getMethod()
getRequestURL()
getRequestURI()
getContextPath()
getQueryString()

Among them, the middle three are the key methods.

 

2. Code example

package com.anthony.servlet;

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


public class ServletDemo4 extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//Get request message line related methods
		//GET http request type, common are GET and POST
		System.out.println(req.getMethod());  // This is GET.
		//Get request full URL address
		System.out.println(req.getRequestURL());
		//Get request URI
		System.out.println(req.getRequestURI());
		//Get application root
		System.out.println(req.getContextPath());
		//Get request parameter content
		System.out.println(req.getQueryString());
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	
}

3. Test run results

After deployment to tomcat, request the test results, and the Eclipse log console outputs the following

GET
http://localhost:8080/Servlet01/demo4
/Servlet01/demo4
/Servlet01
null

This result, compared with the five methods in the doGet() method above, is very easy to understand. Why does a null appear here? That is, we request the address without parameters http://localhost:8080/Servlet01/demo4 replace with http://localhost:8080/Servlet01/demo4?username=anthony

Test again

GET
http://localhost:8080/Servlet01/demo4
/Servlet01/demo4
/Servlet01
username=anthony

Get the parameter part of the request line.

Posted by vito336 on Sun, 10 Nov 2019 09:29:49 -0800