Spring Framework 4.3 New Feature RequestMapping: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

Spring Framework 4.3 has some Web improvements. In the article, JavaSampleApproach will introduce you about New Feature RequestMapping: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping.

Related Posts:
Spring MVC – @RequestMapping with Methods, Headers, Params, @PathVariable and @RequestParam
Kotlin Spring MVC RequestMapping RESTful APIs with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping | SpringBoot Example


I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.3.RELEASE

II. Overview
1. Project Structure

spring new feature request mapping project structure

2. Step to do

– Create SpringBoot project
– Create a simple model
– Create New Feature RequestMapping
– Run and check result

III. Practices
1. Create SpringBoot project

Open SpringToolSuite, on main menu, choose File->New->Spring Boot Starter, input project information. Press Next, then Finish, a SpringBoot project is created succesfully.
Open pom.xml file, add Web dependency:


	org.springframework.boot
	spring-boot-starter-web

2. Create a simple model
package com.javasampleapproach.newfeaturerequestmapping.model;

public class Customer {
	private int custId;
	private String firstname;
	private String lastname;
	private int age;
	
	public Customer(){}
	
	public Customer(int custId, String firstname, String lastname, int age){
		this.custId = custId;
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
	}
	
	public Customer(String firstname, String lastname, int age){
		this.firstname = firstname;
		this.lastname = lastname;
		this.age = age;
	}

	public int getCustId() {
		return custId;
	}

	public void setCustId(int custId) {
		this.custId = custId;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		String info = String.format("custId = %d, firstname = %s, lastname = %s, age = %d", custId, firstname, lastname, age);
		return info;
	}
}
3. Create New Feature RequestMapping

Create @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

package com.javasampleapproach.newfeaturerequestmapping.controller;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
 
import javax.annotation.PostConstruct;
 
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.javasampleapproach.newfeaturerequestmapping.model.Customer;
 
@RestController
public class WebController {
 
    Map custStores = new HashMap();
 
    @PostConstruct
    public void initIt() throws Exception {
        Customer cust1 = new Customer(1, "Jack", "Smith", 20);
        Customer cust2 = new Customer(2, "Peter", "Johnson", 25);
 
        custStores.put(cust1.getCustId(), cust1);
        custStores.put(cust2.getCustId(), cust2);
    }
 
    @GetMapping("/get")
    public Customer getMethod(@RequestParam("custId") int custId) {
        return custStores.get(custId);
    }
 
    @PostMapping("/post")
    public Customer postMethod(@RequestBody Customer customer) {
        Random r = new Random();
        customer.setCustId(r.nextInt());
 
        // POST processing
        custStores.put(customer.getCustId(), customer);
 
        // Log out custStores after POST
        System.out.println("Customer Stores after POST:");
        custStores.forEach((id, cust) -> System.out.println(cust.toString()));
 
        return customer;
    }
 
    @PutMapping("/put/{custId}")
    public Customer putMethod(@PathVariable int custId, @RequestBody Customer customer) {
        // PUT processing
        try{
            custStores.remove(custId);
            customer.setCustId(custId);
            custStores.put(custId, customer);
        }catch(Exception e){
            System.out.println(e.getStackTrace());
            return null;
        }
 
        // Log out custStores after PUT
        System.out.println("Customer Stores after PUT");
        custStores.forEach((id, cust) -> System.out.println(cust.toString()));
 
        return customer;
    }
 
    @DeleteMapping("/delete/{custId}")
    public String deleteMethod(@PathVariable int custId) {
        try {
            // DELETE processing
            custStores.remove(custId);
        } catch (Exception e) {
            return "Error";
        }
 
        // Log out custStores after DELETE
        System.out.println("Customer Stores after DELETE");
        custStores.forEach((id, cust) -> System.out.println(cust.toString()));
 
        return "Done";
    }
 
}
4. Run and check result

Build & Run SpringBoot project then check result:

– Get RequestMapping:
new feature requestmapping spring mvc @getmapping

– POST RequestMapping:
new feature requestmapping springmvc @postmapping

– PUT RequestMapping:
new feature requestmapping springmvc @putmapping

– DELETE RequestMapping:
new feature requestmapping springmvc @deletemapping

ResfulWebServices Logs:

Customer Stores after POST:
custId = 1642586151, firstname = Mary, lastname = Taylor, age = 27
custId = 1, firstname = Jack, lastname = Smith, age = 20
custId = 2, firstname = Peter, lastname = Johnson, age = 25
Customer Stores after PUT
custId = 1642586151, firstname = Amy, lastname = Taylor, age = 24
custId = 1, firstname = Jack, lastname = Smith, age = 20
custId = 2, firstname = Peter, lastname = Johnson, age = 25
Customer Stores after DELETE
custId = 1, firstname = Jack, lastname = Smith, age = 20
custId = 2, firstname = Peter, lastname = Johnson, age = 25
IV. Sourcecode

SpringMVCNewFeatureRequestMapping

17 thoughts on “Spring Framework 4.3 New Feature RequestMapping: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping”

  1. is package scanning configuration required to tell Spring which Java source packages to initialize the beans from?

    1. Hi,

      With SpringBoot application, we have:
      @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan.

      @EnableAutoConfiguration annotation implicitly defines a base search package is the root package: com.javasampleapproach.newfeaturerequestmapping.

      Regards,

  2. A little confused here. In your code you defined:

    @GetMapping("/get")
    public Customer getMethod(@RequestParam("custId") int custId) {
       return custStores.get(custId);
    }
    

    @RequestParam("custId") is my confusion because in your demo example you’re fetching the id param via /get?id=1

    Shouldn’t that be /get?custId=1
    ???

    Great tut overall.
    Thanks!

    1. Hi Emko,

      We should change code as:

      1. For request: /get?id=1

      @GetMapping("/get")
      public Customer getMethod(@RequestParam("id") int custId) {
      

      2. Or use: /get?custId=1 with the mapping:

      @GetMapping("/get")
      public Customer getMethod(@RequestParam("custId") int custId) {
      

      Thanks for your notice

      Regards,
      JSA

  3. After I originally left a comment I appear to have
    clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I recieve 4 emails with
    the same comment. Is there a way you are able to remove me from that service?
    Thanks!

  4. Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out much.
    I hope to give something back and help others like you aided me.

  5. We’re a gaggle of volunteers and opening a new scheme in our community.
    Your web site provided us with useful info to work on. You have performed a formidable process and our entire
    neighborhood will probably be grateful to you.

  6. I like what you guys are up also. Such intelligent work and reporting! Keep up the superb works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my website :).

  7. Hi there, I discovered your blog by means of Google whilst searching for a similar subject, your website came up,
    it looks good. I have bookmarked it in my google bookmarks.

    Hi there, just became alert to your blog via Google,
    and located that it’s truly informative. I’m gonna be careful for brussels.
    I’ll appreciate should you continue this in future.
    Numerous folks will likely be benefited from your writing.
    Cheers!

  8. I would like to thnkx for the efforts you have put in writing this website. I am hoping the same high-grade blog post from you in the upcoming also. In fact your creative writing abilities has encouraged me to get my own web site now. Actually the blogging is spreading its wings fast. Your write up is a great example of it.

Leave a Reply

Your email address will not be published. Required fields are marked *