Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring MVC: REST application with CNVR vol. 2

In the previous post I have made a fast overview of the setting up environment for Spring MVC REST project with CNVR. In this part I can focus directly on a controller and on demonstration of a REST service. As usually I’m going to make a short introduction and after that I will go through the controller methods and explain all essential moments.

Since further I will talk about the REST service, I need to say some sentences about the basic REST concepts. You probably heard before about sites which provide API to use their functionality. This becomes possible with the help of REST or SOAP, but in this article I will talk about the REST.

E.g. you want to develop an application for a university library which will work with students and books. You can implement all controllers using REST. This decision will make your application opened for a collaboration with other applications which can use the application’s API. For the more information about REST features you need to visit special sites.

Spring MVC REST controller

The Smartphone application is oriented on HTTP clients such as browsers and on JSON clients. JSON format can be consumed by various types of clients, but it’s doesn’t matter now.

Let’s consider the entire controller code:

@Controller
@RequestMapping(value="/smartphones")
public class SmartphoneController {

	@Autowired
	private SmartphoneService smartphoneService;

	@RequestMapping(value="/create", method=RequestMethod.GET)
	public ModelAndView createSmartphonePage() {
		ModelAndView mav = new ModelAndView("phones/new-phone");
		mav.addObject("sPhone", new Smartphone());
		return mav;
	}

	@RequestMapping(value="/create", method=RequestMethod.POST)
	public ModelAndView createSmartphone(@ModelAttribute Smartphone smartphone,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		createSmartphone(smartphone);
		attributes.addFlashAttribute("msg", "New Smartphone "+smartphone+" was successfully created.");
		return mav;
	}

	@RequestMapping(value="/create", method=RequestMethod.POST, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
		return smartphoneService.create(smartphone);
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
	public ModelAndView editSmartphonePage(@PathVariable int id) {
		ModelAndView mav = new ModelAndView("phones/edit-phone");
		Smartphone smartphone = smartphoneService.get(id);
		mav.addObject("sPhone", smartphone);
		return mav;
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone editSmartphone(@PathVariable int id, 
			@RequestBody Smartphone smartphone) {
		smartphone.setId(id);
		return smartphoneService.update(smartphone);
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT)
	public ModelAndView editSmartphone(@PathVariable int id,
			@ModelAttribute Smartphone smartphone,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		editSmartphone(id, smartphone);
		attributes.addFlashAttribute("msg", "The Smartphone "+smartphone+" was successfully updated.");
		return mav;
	}

	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone deleteSmartphone(@PathVariable int id) {
		return smartphoneService.delete(id);
	}

	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public ModelAndView deleteSmartphone(@PathVariable int id,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		Smartphone deletedSphone = deleteSmartphone(id);
		attributes.addFlashAttribute("msg", "The Smartphone "+deletedSphone+" was successfully deleted.");
		return mav;
	}

	@RequestMapping(value="", method=RequestMethod.GET,
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public List< Smartphone > allPhones() {
		return smartphoneService.getAll();
	}

	@RequestMapping(value="", method=RequestMethod.GET)
	public ModelAndView allPhonesPage() {
		ModelAndView mav = new ModelAndView("phones/all-phones");
		List< Smartphone > smartphones = new ArrayList< Smartphone >();
		smartphones.addAll(allPhones());
		mav.addObject("smartphones", smartphones);
		return mav;
	}

}

The Smartphone controller is really verbose and has a lot of methods. In the start of the controller you can see autowired smartphoneService. In its turn the smartphoneService has five methods:

  • public Smartphone create(Smartphone sp);
  • public Smartphone get(Integer id);
  • public List< Smartphone > getAll();
  • public Smartphone update(Smartphone sp) throws SmartphoneNotFoundException;
  • public Smartphone delete(Integer id) throws SmartphoneNotFoundException;

Each method in the controller corresponds to the certain metod of the service. So let’s examine this correspondence in the following sections.

REST: CREATE

The following code snippet is responsible for the creation of a new smartphone entity:

...
	@RequestMapping(value="/create", method=RequestMethod.POST)
	public ModelAndView createSmartphone(@ModelAttribute Smartphone smartphone,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		createSmartphone(smartphone);
		attributes.addFlashAttribute("msg", "New Smartphone "+smartphone+" was successfully created.");
		return mav;
	}

	@RequestMapping(value="/create", method=RequestMethod.POST, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
		return smartphoneService.create(smartphone);
	}
...

The first method is a simple Spring MVC controller. I have explained multiple times in my previous posts how to work with Spring MVC controllers. But you can notice that the method is unusual, because it contains invocation of the second one method. The second method is a REST method whith standart REST annotations: @ResponseBody and @RequestBody.

When you submit a form with a data about a new smartphone to “../smartphones/create.html” for a processing, content negotiating view resolver determines that you need to receive a html page. In case when you call URL “../smartphones/create.json” you will get back JSON document. Because I specified in the WebAppConfig that CNVR need to make its decision based on URL sufix.

You can ask: So what is the reason of CNVR usage if we still need to create several methods for the same operation? Let’s suppose that the smartphone application has to support 2 extra content types: XML and PDF. In this case CNVR will make our life easier and we won’t develop extra methods, just add appropriate view resolvers in the WebAppConfig. The situation will become ideal if we start use AJAX in the application. That’s mean we can eliminate methods which return ModelAndView objects.

REST: GET ALL RECORDS

In the previous paragraph I have made a detailed overview of the CNVR principles in practice. So now I will just post concrete code snippets which correspond to the appropriate operation.

...
	@RequestMapping(value="", method=RequestMethod.GET,
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public List< Smartphone > allPhones() {
		return smartphoneService.getAll();
	}

	@RequestMapping(value="", method=RequestMethod.GET)
	public ModelAndView allPhonesPage() {
		ModelAndView mav = new ModelAndView("phones/all-phones");
		List< Smartphone > smartphones = new ArrayList< Smartphone >();
		smartphones.addAll(allPhones());
		mav.addObject("smartphones", smartphones);
		return mav;
	}
...

These methods are responsible for a retrieving of the smartphone list.

REST: UPDATE

Here are methods which perform update of the existing smartphone.

...
	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone editSmartphone(@PathVariable int id, 
			@RequestBody Smartphone smartphone) {
		smartphone.setId(id);
		return smartphoneService.update(smartphone);
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT)
	public ModelAndView editSmartphone(@PathVariable int id,
			@ModelAttribute Smartphone smartphone,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		editSmartphone(id, smartphone);
		attributes.addFlashAttribute("msg", "The Smartphone "+smartphone+" was successfully updated.");
		return mav;
	}
...

REST: DELETE

Here are methods which perform deletion of the existing smartphone.

...
	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, 
			produces = "application/json", consumes = "application/json")
	@ResponseBody
	public Smartphone deleteSmartphone(@PathVariable int id) {
		return smartphoneService.delete(id);
	}

	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public ModelAndView deleteSmartphone(@PathVariable int id,
			final RedirectAttributes attributes) {
		ModelAndView mav = new ModelAndView("redirect:/index.html");
		Smartphone deletedSphone = deleteSmartphone(id);
		attributes.addFlashAttribute("msg", "The Smartphone "+deletedSphone+" was successfully deleted.");
		return mav;
	}
...

Summary

I hope this part was clear for you. Definitely you need to have some basic knowledge of Spring and REST in order to fully understand this article. Don’t ignore links which I put in the article for the more information. In the third part I’m going to demonstrate how this application works.
 

Reference: Spring MVC: REST application with CNVR vol. 2 from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

2 Responses to "Spring MVC: REST application with CNVR vol. 2"

  1. TB says:

    You should read up on REST. It it not acceptable to use /create or /edit/{id}, creating methods in REST is the opposite of doing REST. You should post to / for a create and edit by posting (or putting) to /{id}.
    Can even be found on wikipedia: http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_APIs

Leave a Reply


two × = 18



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.