SpringMVC basics -- @ ModelAttribute and @ SessionAttribute, springmvcattribute
I. @ ModelAttribute Annotation
Annotation of @ ModelAttribute for a method. annotation of @ ModelAttribute is called before each target method is called. Essentially, model data can be manipulated before the target method is called.
1. Store data to the model in the method marked by @ ModelAttribute
Note: In the @ ModelAttribute annotation method, the type of the input parameter can be the same as that allowed in the target method, for example, the request parameter marked by @ RequestParam.
There are two methods:
Target method:
@RequestMapping("/updateStudent")public String update(Student student) { System.out.println("student: " + student); return "success";}
(1) Add parameters of the Model or Map type to the input parameter (not recommended)
@ModelAttributepublic void getStudent(@RequestParam(value = "id", required = false) String idStr, Map<String, Object> map) { try { Integer id = Integer.parseInt(idStr); System.out.println("student id: " + id); map.put("student", new Student(1, "lisi", 23)); } catch(NumberFormatException ignored) { }}
Before calling the target method, "student" will be placed in the Model. The reason why this is not recommended is that a data with the key as void and null value will be added to the model.
(2) return values through the value attribute annotated by @ ModelAttribute and the method labeled by @ ModelAttribute (recommended)
@ModelAttribute("student")public Student getStudent(@RequestParam(value = "id", required = false) String idStr, Map<String, Object> map) { Student student = null; try { Integer id = Integer.parseInt(idStr); System.out.println("student id: " + id); student = new Student(1, "lisi", 23); } catch(NumberFormatException ignored) { } return student;}
Data in the model before calling the target method:
Model has only one key-value pair. This method is more elegant.
Conclusion: Before SpringMVC calls the target method, it uses the value Attribute value of the @ ModelAttribute annotation as the key, and the return value as the value, which is saved to the model.
Source code analysis:
Org. springframework. web. bind. annotation. support. HandlerMethodInvoker # invokeHandlerMethod
1 public final Object invokeHandlerMethod (Method handlerMethod, Object handler, 2 NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {3 4 Method handlerMethodToInvoke = BridgeMethodResolver. findBridgedMethod (handlerMethod); 5 try {6 boolean debug = logger. isDebugEnabled (); 7 for (String attrName: this. methodResolver. getActualSessionAttributeNames () {8 Object attrValu E = this. sessionAttributeStore. retrieveAttribute (webRequest, attrName); 9 if (attrValue! = Null) {10 implicitModel. addAttribute (attrName, attrValue); 11} 12} 13 // start to call the Method 14 for (Method attributeMethod: this. methodResolver. getModelAttributeMethods () {15 Method attributeMethodToInvoke = BridgeMethodResolver. findBridgedMethod (attributeMethod); 16 Object [] args = resolveHandlerArguments (attributeMethodToInvoke, handler, webRequest, implicitModel); 17 if (debug) {18 log Ger. debug ("Invoking model attribute method:" + attributeMethodToInvoke); 19} 20 String attrName = AnnotationUtils. findAnnotation (attributeMethod, ModelAttribute. class). value (); 21 if (! "". Equals (attrName) & implicitModel. containsAttribute (attrName) {22 continue; 23} 24 ReflectionUtils. makeAccessible (attributeMethodToInvoke); 25 Object attrValue = attributeMethodToInvoke. invoke (handler, args); 26 if ("". equals (attrName) {27 Class <?> ResolvedType = GenericTypeResolver. resolveReturnType (outputs, handler. getClass (); 28 attrName = Conventions. Outputs (attributeMethodToInvoke, resolvedType, attrValue); 29} 30 if (! ImplicitModel. containsAttribute (attrName) {31 implicitModel. addAttribute (attrName, attrValue); 32} 33} 34 Object [] args = resolveHandlerArguments (handlerMethodToInvoke, handler, webRequest, implicitModel); 35 if (debug) {36 logger. debug ("Invoking request handler method:" + handlerMethodToInvoke); 37} 38 ReflectionUtils. makeAccessible (handlerMethodToInvoke); 39 // call the target method 40 return handlerMethodToInvoke. invoke (handler, args); 41} 42 catch (IllegalStateException ex) {43 // Internal assertion failed (e.g. invalid signature): 44 // throw exception with full handler method context... 45 throw new HandlerMethodInvocationException (handlerMethodToInvoke, ex); 46} 47 catch (InvocationTargetException ex) {48 // User-defined @ ModelAttribute/@ InitBinder/@ RequestMapping method threw an exception... 49 ReflectionUtils. rethrowException (ex. getTargetException (); 50 return null; 51} 52}
The for loop at line 14 processes the @ ModleAttribute annotation method, and calls the target method at line 40-call the @ ModelAttribute annotation method before calling the target method.
The request parameters have been parsed in the 16 rows. In the method marked by @ ModelAttribute, the input parameter types can be the same as the input parameter types allowed in the target method.
20 rows, 25 rows, 31 rows-the second method. It is also clear that if the model contains the same key, it will not be replaced.
2. read data from the model in the target method
@ModelAttribute("student")public Student getStudent() { return new Student(1, "lisi", 23);}@ModelAttribute("student2")public Student getStudent2() { return new Student(2, "wangwu", 33);}
(1) do not use the @ ModelAttribute annotation at the entry of the target method
@RequestMapping("/updateStudent")public String update(Student student2) { System.out.println("student: " + student2); return "success";}
Console output:
Student: Student {id = 23, studentName = 'lisi', age = 23}
(2) Use the @ ModelAttribute annotation at the entry of the target method
@RequestMapping("/updateStudent")public String update(@ModelAttribute("student2") Student student2) { System.out.println("student: " + student2); return "success";}
Console output:
Student: Student {id = 23, studentName = 'wangwu', age = 33}
(3) Source Code Analysis
Org. springframework. web. bind. annotation. support. HandlerMethodInvoker # resolveHandlerArguments
The number of rows in this method is too large. We only focus on the following points:
Row 289: if the target method input parameter is marked with @ ModelAttribute, obtain its value attribute.
else if (ModelAttribute.class.isInstance(paramAnn)) { ModelAttribute attr = (ModelAttribute) paramAnn; attrName = attr.value(); annotationsFound++;}
Row 3:
else if (attrName != null) { WebDataBinder binder = resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler); boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1])); if (binder.getTarget() != null) { doBind(binder, webRequest, validate, validationHints, !assignBindingResult); } args[i] = binder.getTarget(); if (assignBindingResult) { args[i + 1] = binder.getBindingResult(); i++; } implicitModel.putAll(binder.getBindingResult().getModel());}
Whether the @ ModelAttribute annotation is specified for the input parameter of the target method, It will be executed here.
Look at the red place: it is resolved here.
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { // Bind request parameter onto object... String name = attrName; if ("".equals(name)) { name = Conventions.getVariableNameForParameter(methodParam); } Class<?> paramType = methodParam.getParameterType(); Object bindObject; if (implicitModel.containsKey(name)) { bindObject = implicitModel.get(name); } else if (this.methodResolver.isSessionAttribute(name, paramType)) { bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); if (bindObject == null) { raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); } } else { bindObject = BeanUtils.instantiateClass(paramType); } WebDataBinder binder = createBinder(webRequest, bindObject, name); initBinder(handler, name, binder, webRequest); return binder;}
Note:
String name = attrName;
If ("". equals (name )){
Name = Conventions. getVariableNameForParameter (methodParam );
}
If not specified, a default value is obtained through Conventions. getVariableNameForParameter (methodParam.
If (implicitModel. containsKey (name )){
BindObject = implicitModel. get (name );
}
Obtain from the model, and finally bind it.
(4) Conclusion: @ ModelAttribute used for entry to the target method can only be used to specify attrName, that is, to obtain the data key from the Model.
<1> the object parameter name of the target method has no relationship with the return value of the method indicated by @ ModelAttribute, but only with the type.
<2> If the @ ModelAttribute annotation is not used for the entry of the target method:
You do not need to use the @ ModelAttribute annotation to specify the value attribute value of the @ ModelAttribute annotation method. If there are multiple, use the default value.
<3> when @ ModelAttribute annotation is required for the entry of the target method:
There are multiple @ ModelAttribute annotation methods. The returned value is A of the same type and the value Attribute value of @ ModelAttribute is different. In the target method, the object A must be used as the input parameter, however, you need to use the specified
. At this time, you need to use @ ModelAttribute in the input parameter of the target method to specify which to use through the value attribute.
Ii. @ SessionAttribute
1. Official Instructions
2. I will not repeat SessionAttribute here because I have a very good post summary.
Http://blog.sina.com.cn/s/blog_6d3c1ec601018cx1.html
3. My own understanding:
@ SessionAttribute refers to the springmvc session. When adding a value to it, it will also add a value to the http session. Sprinmvc is cleared when sessionStatus. setComplete ();
The http session content of the corresponding key is cleared at the same time, but the content added through the request. getSession. setAttribute () method will not be cleared.
In other cases, springmvc session and http session are used in the same way.