简体   繁体   中英

Getting “null” value from bean when using @RequestParam

Here is my Controller method:

    @RequestMapping(value = "/quickstart/email")
    public String viewQuickStartEmailForm(@RequestParam("key") String key,@ModelAttribute(value = "quickbean") 
    QuickStartBean quickbean,BindingResult result,Model model) { 
        try {    
           System.out.println(key); 
           email=quickbean.getEmail();
           System.out.println(email);
           model.addAttribute("quickstartdatabean", new QuickStartBean());

        } catch (Exception e) {
            e.printStackTrace();
        }

When I do not use @RequestParam , the code works fine and quickbean gets the form values but when I use it the bean gets null values.

How can I fix it?

如果您通过密钥或不通过密钥,则可以通过添加required属性来工作,请尝试使用此@RequestParam(required = false ,value = "key")String key进行更改

Every field in your QuickStartBean will be interpreted as @RequestParam .

So if you explicit use a @RequestParam in you controller method, spring will use it and ignores the QuickStartBean . Both the bean and RequestParam are not possible.

Put the String key in a QuickStartBean . Or create a new bean like this:

public class RequestForm extends QuickStartBean {

    private String key;

    [...] // getter,setter...
}

and controller:

public String viewQuickStartEmailForm(@Valid RequestForm form, BindingResult result, Model model){
    if(result.hasErrors()) {
        // return "error";
    }
    [...]
}

尝试@RequestParam(value = "key")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM