前端代码:
<html> <head> <base href="<%=basePath %>"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Insert title here</title> </head> <body> <form method="post" action="<%=basePath%>user/login2"> <label for="name">用户名</label> <input id="name" type="text" name="username"> <br> <label for="pass">密码</label> <input id="pass" type="text" name="password"> <button type="submit">提交</button> </form> </body> </html>
后端代码:
@PostMapping("/login2") public String loginLogic2(@RequestBody User user) { Subject subject = SecurityUtils.getSubject(); // UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); // 登录失败会抛出异常,则交由异常解析器处理 //subject.login(token); System.out.println(user); return "main"; }
分析:
出现问题的元婴是 @RequestBody 允许json的请求通过 而前端默认的请求类型为
application/x-www-form-urlencoded ,所以出现媒体类型不一致,
解决方案:
1: @RequestBody(required=false)
2: 去掉1中注解 由MVC自动进行装配,可以不是json数据
后述: 实际上在全部ajax应用的时候允许使用@RequestBody,但是传统问题上可以设置其不是必须的参数.