简体   繁体   中英

Spring boot application Error 400 Bad request on POST

I am trying to create a login form that posts 2 parameters (an email and a password). In my controller I am retrieving those parameters through @RequestParam . I've also specified that the method of this controller is POST in @RequestMappig . The problem is that I am getting 400 with the following message:

Required String parameter 'email' is not present

I've tried getting the params from HttpServletRequest and they are actually missing, but I have no clue why? Can anyone help me out please?

Here is my 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>

And here is my controller:

public String authentication(@RequestParam("email") String email,@RequestParam("password") String password, Model model){

    Map<String,String> map = new HashMap<>();
    map.put("email",email);
.....

When you use form with method="post" , data send in post body, not in request params. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data

The @RequestParam annotation is for web request parameters not for the body of a POST. Try the @RequestBody parameter.

Also, consider using the @ModelAttribute in your HTML and controller method to bind the form body to a POJO ( see Baeldung's MVC Form tutorial ).

Lastly, with Spring Boot you should not have to implement the /authentication controller yourself. If you @EnableWebSecurity and correctly wire up an AuthenticationManager with your UserService you should get authentication "for free" ( see Baeldung's Spring Security Tutorial ).

This is not the way POST request works. When you do a post request then the data is sent in RequestBody, not in RequestParam. You can change your code as

public String authentication(@RequestBody Login login){

Map<String,String> map = new HashMap<>();
map.put("email",login.email);

.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM