我正在尝试从Spring Boot应用程序上的表单获取用户输入。我该怎么办?
我实现了一个登录控制器,该控制器使用@RequestParam
批注来请求数据进行验证,但得到的结果是不存在参数。
// LoginController.java
@PostMapping(path = "/login")
public String userLogin(@RequestParam("email") String email,
@RequestParam("password") String password) {
// validate username and password
User user = userRepository.findUserByEmail(email);
System.out.println(user.getEmail()+" "+user.getPassword());
if(!(user.getEmail()==email) || !(user.getPassword()==password)){
logger.info("Invalid user details or not register");
return "login failed";
}
try{
loginService.login(email, password);
logger.info("User successfully login");
return "redirect:dashboard/profile";
}catch (Exception ex){
logger.info("",ex);
}
return "Successfully logged in ..";
}
Login.html
<form th:action="@{/login}" method="post" class="form-horizontal" role="form">
<form:hidden path/>
<div class="form-group">
<div class="mb-3">
<input type="email" class="form-control" name="email" id="email" placeholder="example@gmail.com" required="required">
</div>
</div>
<div class="form-group">
<div class="mb-3">
<input type="password" class="form-control" name="password" id="password" placeholder="" required="required">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<label>
<input type="checkbox"> Remember me
</label>
<button type="submit" class="btn btn-success">Login</button>
</div>
</div>
</form>
我希望用户可以先登录并获得电子邮件和密码
2019-07-27 20:30:54.393 WARN 2900 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.bind.MissingServletRequestParameterException: 必需的字符串参数'email'不存在]
答案 0 :(得分:0)
您必须从前端发送参数名称:
Plan_start_Date
答案 1 :(得分:0)
由于API设计错误和URL中的RequestParam不匹配而导致的问题。
将您的API更改为此:
@PostMapping(path = "/login") public String userLogin(@RequestBody Map<String, Object> user) {
String username=user.get("user").toString();
String password=user.get("password").toString();
}
您的请求正文JSON应该像这样。
{
"user":"USER",
"password":"pass5&234rf"
}
这是来自客户端的POST请求的JSON有效负载(正文)。