Spring – @GetMapping and @PostMapping

Learn to create Spring MVC spring controllers with @Controller annotation and map requests with request mapping annotations, for example, @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping and @PatchMapping.

Table of Contents

1. Request Mapping Annotations
2. @GetMapping Annotation
3. @PostMapping Annotation
4. Shared class level attributes
5. @PostMapping vs @RequestMapping
6. Summary

1. Request Mapping Annotations

Originally, Spring had only @RequestMapping annotation for mapping the request URI and HHTP method type. Spring 4.3 introduced five new more specific annotations for each HTTP request type.

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

In the given example, both annotation usages do the same thing.

// 1
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)

// 2
@GetMapping("/users/{id}")

2. Spring @GetMapping Example

  • @GetMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
  • @GetMapping annotated methods handle the HTTP GET requests matched with given URI expression.
@RestController
public class UserController {

	@Autowired
	UserService userService;

	@GetMapping("users")
	public ResponseEntity<List<User>> getAll() {
		return new ResponseEntity<>(userService.getAll(), HttpStatus.OK);
	}

	@GetMapping("users/{id}")
	public ResponseEntity<User> getById(@PathVariable long id) {
		Optional<User> user = userService.getById(id);
		if (user.isPresent()) {
			return new ResponseEntity<>(user.get(), HttpStatus.OK);
		} else {
			throw new RecordNotFoundException();
		}
	}
}

3. Spring @PostMapping Example

  • @PostMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).
  • @PostMapping annotated methods handle the HTTP POST requests matched with given URI expression.
@PostMapping(path = "users", 
		consumes = MediaType.APPLICATION_JSON_VALUE, 
		produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> create(@RequestBody User newUser) {
	User user = userService.save(newUser);
	if (user == null) {
		throw new ServerException();
	} else {
		return new ResponseEntity<>(user, HttpStatus.CREATED);
	}
}
The consumes and produces attributes also support negation expressions. For example, "!text/plain" means any media type other than "text/plain".

4. Shared class level attributes

We can declare a shared produces attribute at the class level. When used at the class level, a method-level produces attribute will override the class level declaration.

package com.howtodoinjava.web;

@Controller
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public class HomeController 
{
	@PostMapping(path = "/members")
	public void addMember_V1(@RequestBody Member member) {
		//code
	}

	@PostMapping(path = "/members", produces = MediaType.APPLICATION_XML_VALUE)
	public void addMember_V2(@RequestBody Member member) {
		//code
	}
}

In above example, addMember_V1() method produces content in default media type i.e. application/json. Second method addMember_V2() overrides produces attribute and will generate content in application/xml type.

5. Difference between @PostMapping and @RequestMapping

  1. As noted above @PostMapping annotation is one specialized version of @RequestMapping annotation which handle HTTP POST requests.
  2. @PostMapping acts as a shortcut for @RequestMapping(method = RequestMethod.POST).
    @Target({ java.lang.annotation.ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @RequestMapping(method = { RequestMethod.POST })
    public @interface PostMapping 
    {
        //code
    }
    
  3. Passing URL information is same in both annotations.

Let’s see the difference between PostMapping and @RequestMapping annotations with simple code.

@RequestMapping(value = "/employees", method = RequestMethod.POST)	//1

@PostMapping("/employees")	//2

6. Summary

Spring MVC has made writing request handlers classes and methods very easy. Just add few annotations like @GetMapping and @PostMapping and put the class where component scanning can find them and configure them in web application context.

It is also very easy to create attributes at the class level so that all handler methods inherit them by default, and can override them when needed.

Same way, you can use other request mapping annotations e.g. @PutMapping, @DeleteMapping and @PatchMapping.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Spring – @GetMapping and @PostMapping”

  1. I’m using @PostMapping like this:
    @PostMapping(value = “/echo”)
    public String postEcho(@RequestBody String entity) {
    //TODO: process POST request
    return entity;
    }

    and use a form to post data like this:

    but it respond me Only one connection receive subscriber allowed.

    why it run like this?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.