There was an unexpected error(type=Bad Request,status=400).Required String parameter'username' isnot

异常信息:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Jan 28 23:32:38 CST 2020

There was an unexpected error (type=Bad Request, status=400).

Required String parameter 'username' is not present

错误代码:

   @PostMapping("/login")
    public String login(Model model , @RequestParam("username") String username,
                       @RequestParam("password") String password,
                       @RequestParam(value = "rememberme", defaultValue = "false")
                       boolean rememberme,HttpServletResponse response) {
        Map map = userService.login(username, password);
            if (map.containsKey("msg")) {
            model.addAttribute("msg",map.get("msg"));
            return "reglogin";
        } else {
            if (map.containsKey("ticket")) {
                Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
                cookie.setPath("/");
                if (rememberme) {
                    cookie.setMaxAge(3600 * 24 * 5);
                }
                response.addCookie(cookie);
            }
            return "home";
        }

出错原因:

如果我们在方法中定义了@RequestParam变量,如果访问的URL中不带有相应的参数,就会抛出异常。而上面的代码里用的是post请求,所以出现了异常 。 不过Spring会尝试帮我们进行绑定,然而没有成功。但有的时候,参数确实不一定永远都存在,这是我们可以通过定义required属性:

@RequestParam(name="username",required=false)
//在参数不存在的情况下,可能希望变量有一个默认值
@RequestParam(name="username",required=false,defaultValue="0")

改正后的代码:

 @PostMapping("/login")
    public String login(Model model , @RequestParam(value = "username" , required = false) String username,
                       @RequestParam(value = "password" , required = false) String password,
                       @RequestParam(value = "rememberme", defaultValue = "false") boolean rememberme,
                       HttpServletResponse response) {
        Map map = userService.login(username, password);
            if (map.containsKey("msg")) {
            model.addAttribute("msg",map.get("msg"));
            return "reglogin";
        } else {
            if (map.containsKey("ticket")) {
                Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
                cookie.setPath("/");
                if (rememberme) {
                    cookie.setMaxAge(3600 * 24 * 5);
                }
                response.addCookie(cookie);
            }
            return "home";
        }

 

你可能感兴趣的:(There was an unexpected error(type=Bad Request,status=400).Required String parameter'username' isnot)