@RequestParam in Spring MVC handling optional parameters

后端 未结 3 1912
你的背包
你的背包 2020-12-07 09:08

Is it possible for a Spring controller to handle both kind of requests?

1) http://localhost:8080/submit/id/ID123432?logout=true

2) http:/

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 09:17

    As part of Spring 4.1.1 onwards you now have full support of Java 8 Optional (original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false with Optional for your 3 params logout, name, password:

    @RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,   
     produces="text/xml")
    public String showLoginWindow(@PathVariable("id") String id,
                                  @RequestParam(value = "logout") Optional logout,
                                  @RequestParam("name") Optional username,
                                  @RequestParam("password") Optional password,
                                  @ModelAttribute("submitModel") SubmitModel model,
                                  BindingResult errors) throws LoginException {...}
    

提交回复
热议问题