Enterprise Java

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
TB
TB
11 years ago

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

Fruzenshtein
11 years ago
Reply to  TB
Abhishek
10 years ago

Great Post. I have one question on it. What is the best practice , I am in process of developing an application which can either be consumed by browser or mobile phones, so I have decided to used REST API of Spring which is good enough for Mobile Application as they will be calling REST API and will be getting the JSON Data and use there own logic to show in the data. My problem is that the browser client which I have developing will also going to use same REST API (Using Spring) and getting the JSON Back, now… Read more »

Back to top button