Creating an echo controller in Java with Spring boot

problem

You wish to create an endpoint in your web application that when it is hit, it echoes back the data you’re sending. A basic example would be to add a parameter message and then it prints it back.

SOLUTION

Let’s create a Spring Boot project. In this case IntelliJ IDEA is used and the spring initializer to speed things up.

New Java project

Second step

Last step.

After the project is successfully created, the following class is provided by Spring Boot so we can run the application as a simple Java program.

EchoApplication.java
				
					package com.programmerabroad.www;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EchoApplication {

    public static void main(String[] args) {
        SpringApplication.run(EchoApplication.class, args);
    }

}

				
			
Creating the echo controller

Create a new package controller and inside add a new Java class named EchoController.java with the following code:

EchoApplication.java
				
					package com.programmerabroad.www.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EchoController {

    @GetMapping("/echo")
    public String echoBack(@RequestParam("message") String message){
        return message;
    }
}

				
			
running

In IntelliJ the project can run by clicking run on the main class above (EchoApplication.java).

Alternatively, in the terminal – at the root of the project, it can be executed by the command:

				
					mvn spring-boot:run

				
			
output

Just visit the endpoint: http://localhost:8080/echo?message=testing

Whatever the message (GET parameter) has, it will be echoed back to the browser as seen in the screenshots below.

echo testing
In the terminal, using curl
				
					curl http://localhost:8080/echo\?message\=hello
				
			

conclusion

In this post we saw quickly how to add a RestController with a GetMapping in Spring Boot that accepts a simple request parameter and echoes it back to the client.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x