Spring MVC Features - Tuong-Nguyen/Spring GitHub Wiki
- DI method
- Factory
- @RequestMapping
- Autowiring Controller Services
- URI template
- Method arguments, ex:
HttpSession,HttpServletRequest
- Single object
Parameter's names mapping to Model's properties name
- Composite objects, ex: One product belongs to a category
- Binding lists, ex: One person has a list of contacts (One-many relationship)
- Option 1: build list items of attribute in controller method
List<String> checks = new LinkedList<>(Array.asList(new String[]{
"Lead Time", "Special Rate", "Requires Approval"
}));
model.addAttribute("checkOptions", checks);-
Option 2: Use annotation
@ModelAttribute
@ModelAttribute("checkOptions")
public List<String> getChecks(){
return new LinkedList<>(Array.asList(new String[]{
"Lead Time", "Special Rate", "Requires Approval"
}));
}Use this option, we need to define model attribute only. When a request sent, all model attributes are populated for the model.
Allow we decide which model's attributes will be copied to HttpSession before render the view
@Controller
@SessionAttributes("myModelAttribute")
public class MyController {
//...
@ModelAttribute("myModelAttribute")
public MyModel getMyModel(){
//...
}
}The session attribute is removed only when sessionStatus.setComplete() was called
@RequestMapping(method = RequestMethod.POST)
public void doSomething(@ModelAttribute("myModel") MyModel model, SessionStatus sessionStatus){
//...
sessionStatus.setComplete();
}- @ResponseBody: method returned value will be written to the http response automatically.
- @RequestBody: incoming request body will be converted to the parameter object.
- HttpMessageConverter is used to convert request body string to parameter object. The string can be a serialized JSON object.
@RequestMapping("/request")
@ResponseBody
public String request(@RequestBody Resource resource) {
System.out.println(resource);
// Send out an email for request
return "The request has been sent for approval";
}<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:form method="post" modelAttribute="userForm" action="${userActionUrl}">
<form:input path="name" type="text" /> <!-- bind to user.name-->
<form:errors path="name" />
</form:form>Handling exceptions in specific handler classes or methods
@ExceptionHandler(Exception.class)
public String handleError(HttpServletRequest req) {
return "controller_error";
}- Create a class that implements
HandlerExceptionResolver
View name resolution is configurable through:
- File extension
- Accept header content type
- Bean names
- A properties file
- Custom
ViewResolverimplementation