SpringMVC front-end transfers objects to the back-end (transfer)

springController:
[java] view plaincopy
@Controller  
@RequestMapping("/user")  
public UserController extends BaseController{  
    @RequestMapping("/addUser")    
    public void testBinderOuput(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response){    
        System.out.println(user);    
    }   
}  


Use object:
[java] view plaincopy
public Class User{  
    private String name;      
    private int sex;      
    private String address;  
    private int id;  
    public int getSex() {  
        return sex;  
    }  
    public void setSex(int sex) {  
        this.sex = sex;  
    }  
    public String getAddress() {  
        return address;  
    }  
    public void setAddress(String address) {  
        this.address = address;  
    }  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
}  

Request path:
localhost/user/addUser?user.name="test"
Then in the parameters received in the background, the name attribute of the user object is null. If the path is changed to localhost/user/addUser?name="test", the name attribute of the user object is test.
Here, name="test" must be used instead of user.name="test", because springMVC does not support user.name parameter transfer by default.

If an object manager also has the same attribute of name, then user.name and manager.name can be used to transfer parameters. But this requires adding a prefix binding

to the controller: the controller class after adding the binding prefix is ​​as follows:

[java] view plaincopy
@Controller  
@RequestMapping("/user")  
public UserController extends BaseController{  
      
    @InitBinder("manager")    
    public void initBinder1(WebDataBinder binder) {    
            binder.setFieldDefaultPrefix("manager.");    
    }    
    @InitBinder("user")    
    public void initBinder2(WebDataBinder binder) {    
            binder.setFieldDefaultPrefix("user.");    
    }    
    @RequestMapping("/addUser")    
    public void testBinderOuput(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response){    
        System.out.println(user.getName);    
    }   
    @RequestMapping("/addManager")    
    public void testBinderOuput(@ModelAttribute Manager manager, HttpServletRequest request, HttpServletResponse response){    
        System.out.println(manager.getName);    
    }   
}

In this way, when using the connection localhost/user/addUser?user.name="test" to request, the parameter of the name obtained in the background is not null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326546140&siteId=291194637