Spring @GetMapping
last modified October 18, 2023
In this article we show how to use @GetMapping annotation to map HTTP GET requests onto specific handler methods.
Spring is a popular Java application framework for creating enterprise applications.
@GetMapping
@GetMapping
annotation maps HTTP GET requests onto specific handler
methods. It is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.GET)
.
Spring @GetMapping example
The following application uses @GetMapping
to map two request
paths onto handler methods. In this example, we use annotations to
set up a Spring web application.
pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───config │ │ │ MyWebInitializer.java │ │ │ WebConfig.java │ │ └───controller │ │ MyController.java │ └───resources │ logback.xml └───test └───java └───com └───zetcode └───controller MyControllerTest.java
This is the project structure.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>getmapping</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <spring-version>5.3.23</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.49.v20220914</version> </plugin> </plugins> </build> </project>
In the pom.xml
file we have the following dependencies:
logback-classic
, javax.servlet-api
,
junit
, spring-webmvc
, and spring-test
.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root> </configuration>
The logback.xml
is a configuration file for the Logback logging
library.
package com.zetcode.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @Configuration public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
MyWebInitializer
registers the Spring
DispatcherServlet
, which is a front controller for a Spring web
application.
@Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; }
The getServletConfigClasses
returns a web configuration class.
package com.zetcode.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.zetcode"}) public class WebConfig { }
The WebConfig
enables Spring MVC annotations with
@EnableWebMvc
and configures component scanning for the
com.zetcode
package.
package com.zetcode.controller; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping(value="/", produces = MediaType.TEXT_PLAIN_VALUE) public String index() { return "This is Home page"; } @GetMapping(value="/hello", produces = MediaType.TEXT_PLAIN_VALUE) public String sayHello() { return "Hello there!"; } }
MyController
provides mappings between request paths and handler
methods.
@RestController public class MyController {
@RestController
is used for creating restful controllers, which do
not use a view technology. The methods typically return XML, JSON, or plain
text.
@GetMapping(value="/", produces = MediaType.TEXT_PLAIN_VALUE) public String index() { return "This is Home page"; }
The @GetMapping
maps a /
root path from a GET request
to the index
method. It returns a plain text.
package com.zetcode.controller; import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class MyControllerTest { private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new MyController()).build(); } @Test public void testHomePage() throws Exception { this.mockMvc.perform(get("/")).andExpect(status().isOk()) .andExpect(content().string("This is Home page")); } @Test public void testHelloPage() throws Exception { this.mockMvc.perform(get("/hello")).andExpect(status().isOk()) .andExpect(content().string("Hello there!")); } }
MyControllerTest
tests the two pages.
$ curl localhost:8080 This is Home page $ curl localhost:8080/hello Hello there!
We run the application and create two GET requests with curl
tool.
In this article we have presented the @GetMapping
annotation.
Author
List all Spring tutorials.