我正在尝试创建一个登录表单,其中包含2个参数(电子邮件和密码)。在我的控制器中,我通过@RequestParam
检索这些参数。我还指定了此控制器的方法为POST
中的@RequestMappig
。问题是我收到400并显示以下消息:
Required String parameter 'email' is not present
我尝试从HttpServletRequest
获取参数,但实际上却不见了,但是我不知道为什么吗?有人可以帮我吗?
这是我的html:
<div id="form">
<form action="/authentication" method="post">
<input type="email" value="Email" id="email" onfocus=labelsOnFocus(this) onblur=labelOnDefocus(this) onchange=emailErrorOnTyping(this)>
<p id = "emailError">Email not valide</p>
<input type="password" value="Password" id="password" onfocus=labelsOnFocus(this) onblur=labelOnDefocus(this) onchange=passwordErrorOnTyping(this)>
<p id="passwordError">Password to short</p>
<div class="buttons">
<input type="submit" value="Login" class="submit">
<input type="button" value="Register" class="submit" onclick=register()>
</div>
</form>
这是我的控制器:
public String authentication(@RequestParam("email") String email,@RequestParam("password") String password, Model model){
Map<String,String> map = new HashMap<>();
map.put("email",email);
.....
答案 0 :(得分:1)
当您将表单与method="post"
一起使用时,数据以帖子正文而不是请求参数的形式发送。
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
答案 1 :(得分:0)
@RequestParam
注释用于Web请求参数,而不用于POST正文。尝试使用@RequestBody
参数。
另外,请考虑在HTML和控制器方法中使用@ModelAttribute
将表单主体绑定到POJO(see Baeldung's MVC Form tutorial)。
最后,使用Spring Boot,您不必自己实现/authentication
控制器。如果您@EnableWebSecurity
并正确地将AuthenticationManager
连接到UserService
,则应该获得“免费”身份验证(see Baeldung's Spring Security Tutorial)。
答案 2 :(得分:0)
这不是POST请求的工作方式。当您执行发布请求时,数据将通过RequestBody而不是RequestParam发送。您可以将代码更改为
public String authentication(@RequestBody Login login){
Map<String,String> map = new HashMap<>();
map.put("email",login.email);
.....