Implementing the Add Contact View
Implementing the add contact view is much like the edit view. Because we will reuse the edit.jspx page,
we only need to add the methods in the ContactController class and the view definition.
Listing 17-36 shows the code snippet for the two new methods for the add contact function in the
ContactController class.
Listing 17-36. The Add Contact Methods
package com.apress.prospring3.ch17.web.controller;
// Import statements omitted
@RequestMapping("/contacts")
@Controller
public class ContactController {
// Other code omitted
@RequestMapping(params = "form", method = RequestMethod.POST)
public String create(Contact contact, BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale) {
logger.info("Creating contact");
if (bindingResult.hasErrors()) {
uiModel.addAttribute("message", new Message("error",
messageSource.getMessage("contact_save_fail", new Object[]{}, locale)));
uiModel.addAttribute("contact", contact);
return "contacts/create";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success",
messageSource.getMessage("contact_save_success", new Object[]{}, locale)));
logger.info("Contact id: " + contact.getId());
contactService.save(contact);
return "redirect:/contacts/" + UrlUtil.encodeUrlPathSegment(contact.getId().toString(),
httpServletRequest);
}
@RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel) {
Contact contact = new Contact();
uiModel.addAttribute("contact", contact);
return "contacts/create";
}
}
Next, add the view mapping to the view definition file (/views/contacts/views.xml). Listing 17-37
shows the code snippet.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home