[Java] How to get a request by HTTP communication

Introduction

We will introduce for beginners how to get the request from the front by HTTP communication using Java.

This time, when fetching a request by HTTP communication with Java, a Java program called Servlet is used.

A Servlet is a Java program that runs on a web server such as Tomcat. It plays a role in responding to requests from web browsers and processing sent data.

In this sample program, a request is made from a web browser, We will create a program that returns a simple HTML response to the browser.

1. Development environment

After that, it will be explained in the following versions and environments.

IDE:eclipse Java version: 8 Tomcat:8

2. Directory structure

The folder structure of this sample program is as follows. 20190418-000121.png

3. Create a project

First, select "Dynamic Web Project" from Create New Project and proceed to the next.

スクリーンショット 2019-04-16 23.59.56.png

Next, name the project "SampleHttpServer". Also, make sure the target runtime is "Tomcat 8". If there is no problem, click the Finish button.

スクリーンショット 2019-04-17 0.00.44.png

4. Create Servlet

First right click on the src directory and select New> Other.

スクリーンショット 2019-04-17 0.04.09.png

Then, the following browser will appear. Select "Servlet" and proceed to the next.

スクリーンショット 2019-04-17 0.04.21.png

Then, name the class "HttpServletTest". Java packages may or may not be listed. If not stated, the Servlet will be created in the default package.

After entering the class name, proceed to the next.

スクリーンショット 2019-04-17 0.07.51.png

Uncheck the superclass constructor and inherited abstract methods.

スクリーンショット 2019-04-17 0.10.38.png

Press Finish to complete the creation of the Servlet class.

5. Sample PGM

This time, we will create a simple PGM that returns "Sucess!" To the browser when the URL http: // localhost: 8080 / SampleHttpServer / HttpServletTest is executed in the browser.

First, rewrite the annotation part as follows.

name refers to the name of the Servlet and works without mentioning it, but it is often customarily written. urlPatterns is the URL (relative path) to access this Servlet.

It's OK to understand that "private static final long serialVersionUID = 1L" is like a magic trick when reading and writing data.

java


@WebServlet(name = "HttpServletTest", urlPatterns = { "/HttpServletTest" })
public class HttpServletTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
}

Next, I will write the source code that receives the request from the browser and returns the HTML response.

java


@WebServlet(name = "HttpServletTest", urlPatterns = { "/HttpServletTest" })
public class HttpServletTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

        //The part to be added this time
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Request receipt");
		//HTTP response header content type
		response.setContentType("text/html");

		//HTTP body part
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset=\"UTF-8\">");
		out.println("<title>Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Success!</h1>");
		out.println("</body>");
		out.println("</html>");
		System.out.println("Return response");
	}

First of all, the doget () method is described as above every time you make a GET request.

When returning a response, setContentType specifies the form in which the response is returned. This time, the response is returned in HTML, so "text / html" is specified.

Then, use the response.getWriter () method to get the "PrintWriter" class object for outputting characters to the client, and output the HTML text.

Also, in order to check that it was received on the server side, Sytem.out.println makes it possible to know the receipt of the request and the return of the response.

6. Run sample PGM

Right-click on the project and press Run on Server.

スクリーンショット 2019-04-17 0.17.54.png スクリーンショット 2019-04-17 0.18.14.png

When the server starts, execute the following URL in your browser, and when "Success!" Is displayed as shown below, it is OK. Also, check that the log "Request reception / Response return" is output to the console.

http://localhost:8080/SampleHttpServer/HttpServletTest

スクリーンショット 2019-04-17 0.19.29.png

at the end

I started my personal blog in 2020!

Based on the knowledge and experience gained as a freelance engineer, we plan to distribute content such as information about freelance engineers, IT technical information, industry information, and engineer life hacks.

The number of articles is still small, but it is updated weekly, so if you are interested, I would be grateful if you could take a look.

https://yacchi-engineer.com/

Recommended Posts

[Java] How to get a request by HTTP communication
[Java] How to cut out a character string character by character
How to make a Java container
[Java] How to create a folder
How to make a Java array
How to make a Java calendar Summary
[Introduction to Java] How to write a Java program
How to make a Discord bot (Java)
[Java] How to get the current directory
How to print a Java Word document
How to get the date in java
[Java] How to get to the front of a specific string using the String class
How a completely inexperienced person studied to acquire Java silver by himself
How to get the absolute path of a directory running in Java
How to track when a bucket managed by scoop changes (mainly Java)
How to get a heapdump from a Docker container
[Java] How to get and output standard input
How to display a web page in Java
How to get Class from Element in Java
How to convert a solidity contract to a Java contract class
[Java] How to get random numbers excluding specific numbers
How to get and study java SE8 Gold
[Java] How to get the redirected final URL
[Java] How to get the authority of the folder
[Java] How to get HashMap elements by loop control using extended for statement
[Java] How to get the URL of the transition source
How to create a Java environment in just 3 seconds
How to jump from Eclipse Java to a SQL file
java: How to write a generic type list [Note]
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
[Java] How to get the maximum value of HashMap
As of April 2018 How to get Java 8 on Mac
[Java] How to execute tasks on a regular basis
Summary of Java communication API (1) How to use Socket
[Java] How to erase a specific character from a character string
Summary of Java communication API (3) How to use SocketChannel
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Summary of Java communication API (2) How to use HttpUrlConnection
How to get started with creating a Rails app
[Java] How to start a new line with StringBuilder
(Java) How to implement equals () for a class with value elements added by inheritance
[Java] How to get the key and value stored in Map by iterative processing
How to request by passing an array to the query with HTTP Client of Ruby
How to lower java version
[Java] How to use Map
Java --How to make JTable
How to use java Optional
How to minimize Java images
How to write java comments
How to leave a comment
How to use java class
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
How to use Java variables
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array