SpringMVC learning-----@InitBinder annotation

1. Annotation
It can be seen from the literal meaning that the function of this is to initialize the Binder, and the method annotated by this can initialize the WebDataBinder. webDataBinder is for form to method data binding!
@InitBinder only annotates methods in @Controller to register a binder initialization method for this controller, and the method is only valid for this controller.
2. Code Demonstration

1. Set up data binding

There are many ways in WebDataBinder to make specific settings for data binding: for example, we set the name property to an unbound property (or set the binding value setAllowedFields):

Add a method to the Controller:

     @InitBinder
        public void initBinder(WebDataBinder binder) {
            binder.setDisallowedFields("name");
        }

Then run:

Add to:

Looking at the name value behind it, the binding is not successful!

(The specific function video gives an example to illustrate one of its functions: for example, there are multiple selection buttons in the form, which corresponds to a collection attribute in JaveBean, but the selection is id, and the collection saves the exact class, here we cannot Let SpringMVC bind automatically, we need to bind manually, so turn off its automatic binding, otherwise it will report an error!)

2. Register an existing editor
WebDataBinder is used to bind the request parameters to the specified property editor. Since the value passed to the controller in the foreground is of String type, when the value is set in the Model, if the property of the set is an object, Spring will go to Find the corresponding editor to convert, and then set it in! Spring itself provides a large number of implementation classes (all editor s under org.springframwork.beans.propertyEditors as shown in the figure below), such as CustomDateEditor, CustomBooleanEditor, CustomNumberEditor, etc., which are basically sufficient. When using SpringMVC at ordinary times, you will encounter Date type parameters in javabean s, and the string representing the date in the form is converted into a date type. SpringMVC does not support this type of conversion by default. We just need to set the time format manually and register the editor on webDateBinder!

implementation code

Now add a birth property, setter and getter of type Date to the student class, and add a constructor with all properties of birth. (code omitted)

list.jsp (all student information pages) plus a column showing birthdays: ${stu.birth}

input.jsp (add information interface):

    <br>
    birth(format=yyyy-mm-dd):<form:input path="birth"/>
    <br>

Then drop the previous @InitBinder code in the controller:

        @InitBinder
        public void initBinder(WebDataBinder binder) {
            //binder.setDisallowedFields("name");
            CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true);
            binder.registerCustomEditor(Date.class, editor);
        }

        Editor constructor
         
        public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) 

    Register editor functions

    public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor)

then run

Added successfully

3. Register a custom editor

To use a custom editor is to add a custom editor on the basis of the second one. The custom editor class needs to inherit

org.springframework.beans.propertyeditors.PropertiesEditor;

And rewrite its setAsText and getAsText two methods on the line!

For example, the following DoubleEditor:

    public class DoubleEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null || text.equals("")) {
                text = "0";
            }
            setValue(Double.parseDouble(text));
        }
     
        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

Reference: http://blog.51cto.com/simplelife/1919597

Then register it in the InitBinder method.

3. Setting the prefix of the property can realize parameter binding

Enter the code as shown:

jsp: 

    <form action="/testBean" method="post">
        name: <input type="text" name="u.name"> <br>
        age: <input type="text" name="u.age"> <br>
        name: <input type="text" name="s.name"> <br>
        age: <input type="text" name="s.age"> <br>
        <input type="submit">
    </form>

controller:

      @InitBinder("user")
        public void init1(WebDataBinder binder) {
            binder.setFieldDefaultPrefix("u.");
        }
     
        @InitBinder("stu")
        public void init2(WebDataBinder binder) {
            binder.setFieldDefaultPrefix("s.");
        }
     
        @RequestMapping("/testBean")
        public ModelAndView testBean(User user, @ModelAttribute("stu") Student stu) {
            System.out.println(stu);
            System.out.println(user);
            String viewName = "success";
            ModelAndView modelAndView = new ModelAndView(viewName);
            modelAndView.addObject("user", user);
            modelAndView.addObject("student", stu);
            return modelAndView;
     
        }

@InitBinder("user") The parameters in parentheses are the first letter of the class in lowercase (the default naming rule), and can also be qualified with @ModelAttribute("stu").

Original: https://blog.csdn.net/qq_38016931/article/details/82080940

Tags: Spring MVC Annotation

Posted by microthick on Wed, 18 May 2022 13:04:15 +0300