Spring MVC: Ajax & JQuery

Today I want to demonstrate how to integrate AJAX into a Spring MVC application. I’m going to use JQuery on a client side for sending of requests and receiving of responses. This tutorial will be based on one of my previous tutorials about Spring MVC and REST services. In this article you will read how to make a web-application more interactive with the help of asynchronous requests.

Preparations

I need to modify the SmartphoneController class by removing methods which are not required any more. This is a first step of AJAX integration.
 

//imports are omitted@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, 			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)	@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 = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)	@ResponseBody	public Smartphone editSmartphone(@PathVariable int id, 			@RequestBody Smartphone smartphone) {		smartphone.setId(id);		return smartphoneService.update(smartphone);	}	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, 			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)	@ResponseBody	public Smartphone deleteSmartphone(@PathVariable int id) {		return smartphoneService.delete(id);	}	@RequestMapping(value="", method=RequestMethod.GET,			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)	@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;	}}

Source : http://www.javacodegeeks.com/2013/09/spring-mvc-ajax-jquery.html

Back to Top