How does @RequestParam in Spring handle Guava's Optional?

后端 未结 3 1958
暗喜
暗喜 2021-02-05 02:36
@RequestMapping(value = \"/contact.html\", method = RequestMethod.POST)
public final ModelAndView contact(
        @RequestParam(value = \"name\", required = false) Opti         


        
3条回答
  •  天命终不由人
    2021-02-05 03:19

    I recommend to use the Java 8 version: java.util.Optional. Look at the Oracle documentation in http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html. Also put a name to the variable, specially if your using Spring 3 or higher:.

    import java.util.Optional;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class LoginController
    {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public ModelAndView getLoginPage(@RequestParam(name = "error", required = false) Optional errorMsg)
        {
            //error.ifPresent(LOGGER::debug); //Java 8 with Optional
            return new ModelAndView("login", "error", errorMsg);
        }
    
    }
    

    java.util.Optional is very useful for managing optional parametrers, like errors in Spring.

提交回复
热议问题