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

66 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.

  9. you’re truly a just right webmaster. The website loading speed is incredible.
    It kind of feels that you are doing any unique trick.
    Moreover, The contents are masterpiece. you have done a excellent
    job in this topic!

  10. Hello there, just became alert to your blog through Google,
    and found that it’s truly informative. I’m going to watch out for brussels.
    I will be grateful if you continue this in future.
    Many people will be benefited from your writing. Cheers!

  11. Hey there! I understand this is kind of off-topic but I
    had to ask. Does building a well-established blog such as yours require a lot of work?
    I’m brand new to running a blog but I do write in my diary
    daily. I’d like to start a blog so I can easily share my
    personal experience and thoughts online. Please let me know if you have any recommendations or tips for new aspiring blog owners.
    Thankyou!

  12. Hey! This is my first visit to your blog!
    We are a team of volunteers and starting a new project in a community in the same niche.
    Your blog provided us useful information to work
    on. You have done a extraordinary job!

  13. We are a group of volunteers and opening a new scheme in our community.
    Your web site provided us with useful info to work on. You’ve performed an impressive job and our whole group will
    be grateful to you.

  14. Nice post. I was checking constantly this blog and I am impressed!

    Very useful information specifically the last part 🙂 I care for such information much.
    I was seeking this certain information for a very long time.
    Thank you and good luck.

  15. Hi there this is kind of of off topic but I was wondering if blogs use
    WYSIWYG editors or if you have to manually code with
    HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance
    from someone with experience. Any help would be greatly appreciated!

  16. I was more than happy to uncover this web site. I need to to thank you for ones time
    just for this fantastic read!! I definitely loved every bit of it
    and I have you book-marked to look at new stuff in your
    web site.

  17. Hey there! I could have sworn I’ve been to this
    blog before but after browsing through some of the post I realized it’s
    new to me. Anyways, I’m definitely glad I found it and I’ll be book-marking
    and checking back frequently!

  18. Hello there, You have done an incredible job.
    I’ll certainly digg it and personally suggest to my friends.
    I am confident they’ll be benefited from this site.

  19. My developer is trying to persuade me to move
    to .net from PHP. I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on a variety of websites for about a year and
    am concerned about switching to another platform.
    I have heard good things about blogengine.net. Is there
    a way I can import all my wordpress content into it? Any kind of
    help would be greatly appreciated!

  20. I’m extremely pleased to find this great site. I wanted to thank you for your time for this fantastic read!!
    I definitely appreciated every little bit of it and i also have you book marked to check out new stuff in your web
    site.

  21. Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s very hard to get that
    “perfect balance” between user friendliness and visual appearance.
    I must say that you’ve done a great job with this.
    Also, the blog loads super fast for me on Safari.

    Excellent Blog!

  22. Hello, Neat post. There is an issue with your site in internet explorer,
    may check this? IE nonetheless is the market chief and a huge component of other people will miss your wonderful
    writing due to this problem.

  23. Great goods from you, man. I’ve understand your stuff previous to
    and you are just extremely great. I really like what you’ve acquired here, really like what you’re stating and the way in which
    you say it. You make it enjoyable and you still care for to keep it wise.
    I can not wait to read far more from you. This is actually a wonderful
    website.

  24. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an edginess over that
    you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly very often inside case
    you shield this increase.

  25. Generally I don’t read post on blogs, however I wish to say that this write-up very forced me to check out and do so!
    Your writing style has been amazed me. Thanks,
    very great article.

  26. Good post however , I was wanting to know if you could write a litte more on this subject?

    I’d be very grateful if you could elaborate a little bit further.
    Bless you!

  27. Usually I don’t read post on blogs, however I would like to say that
    this write-up very compelled me to try and do it! Your writing taste has been amazed me.
    Thanks, quite nice article.

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

  29. I’m not sure exactly why but this website is loading incredibly slow for me.
    Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  30. Currently it looks like Expression Engine is the preferred blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

  31. Thank you for some other informative website. The place else may just I am getting
    that type of information written in such a perfect means?
    I’ve a venture that I’m just now running on, and I’ve been at
    the look out for such information.

  32. I do not know whether it’s just me or if everyone else experiencing problems with your blog.
    It seems like some of the text in your content are running
    off the screen. Can someone else please provide feedback and let me know if this is happening to them
    too? This might be a problem with my web browser because I’ve had this happen before.
    Cheers

  33. What’s up everyone, it’s my first pay a visit at this web site, and piece of writing is really fruitful in favor
    of me, keep up posting these types of content.

  34. Nice post. I was checking constantly this blog and I’m impressed!
    Extremely helpful info specifically the last part 🙂 I care for such info
    much. I was looking for this particular information for
    a long time. Thank you and best of luck.

  35. We are a group of volunteers and starting a new scheme in our community.

    Your website provided us with valuable information to work on. You’ve
    performed an impressive activity and our entire community shall be grateful to you.

  36. Write more, thats all I have to say. Literally, it seems as
    though you relied on the video to make your point.

    You clearly know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you
    could be giving us something informative to read?

  37. Hi, i read your blog from time to time and i own a
    similar one and i was just curious if you get a lot of spam remarks?
    If so how do you reduce it, any plugin or anything you
    can recommend? I get so much lately it’s driving me mad so any help is
    very much appreciated.

  38. Its like you read my mind! You seem to know so much about this, like
    you wrote the book in it or something. I think that you can do with a few pics to drive the message home a
    bit, but instead of that, this is excellent blog.
    An excellent read. I will certainly be back.

  39. Please let me know if you’re looking for a writer for your weblog.
    You have some really good articles and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a
    link back to mine. Please send me an email if interested.
    Many thanks!

  40. I am no longer certain the place you are
    getting your info, but good topic. I needs to spend
    some time learning more or working out more. Thank you for wonderful info I was on the lookout for this information for my mission.

  41. Hey there! I know this is kinda off topic but I was wondering which blog platform
    are you using for this website? I’m getting tired
    of WordPress because I’ve had problems with hackers and I’m looking at options for
    another platform. I would be fantastic if you could point me in the direction of a good platform.

  42. Undeniably imagine that that you stated. Your favourite
    justification seemed to be at the internet the simplest thing
    to bear in mind of. I say to you, I definitely get annoyed
    whilst folks consider issues that they plainly do not
    understand about. You controlled to hit the nail upon the top and
    also defined out the entire thing without having side effect , other folks could take a signal.

    Will likely be again to get more. Thanks

Leave a Reply

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