How to get variable HTML form values (POST) in Spr

2020-04-21 06:47发布

问题:

i'm fairly new to Java and the Spring Framework and this might be easy to solve but I cant find any solutions to this problem and other solutions don't fit my problem.

I want to implement a dynamic form, where the user inserts multiple Email addresses to send invitations. This form can dynamically be extended by JS. Every click adds another input field to my form. So now I have a variable amount of values I want to send to my Spring Backend. I was thinking that I have to use @ResponseBody and a Map to store the POST values in it and then iterate over it and (for example) copy them into an ArrayList or directly use my EmailService to send out an Email.

The problem is, Spring gives me an error:

Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

This is my HTML

<form method="post" id="send-invite-mail" th:action="@{/sendmail/sendInvitations}">
  <div id="formfields">
    <div class="form-group">
      <input type="email" class="form-control" id="email1" name="email1" placeholder="Enter Email-Address ..."/>
    </div>
  </div>
  <!-- more form-groups are added here by JS -->
  <button type="submit" id="submitInvitation" class="btn btn-primary">Invite</button>
</form>

And this is what I use in the backend to get my values

@PostMapping("/sendmail/sendInvitations")
public void getInvitationList (@RequestBody Map<String, String> formData){
   List<String> adressList = new ArrayList<String>();
   for (Map.Entry<String, String> entry : formData.entrySet()) {
      adressList.add(entry.getValue());
   }
}

Right now I have no idea if I'm doing this correct or not. Appreciate any help.

回答1:

HTML forms with method='post' send data as form-url-encoded. So, In this case, Spring can not understand it as a RequestBody. Because, POST data with @RequestBody expects an content type as application/json. So, if you want to really send data as json, you have to remove the @RequestBody annotation.

Finally, you can specify content-type with consumes and use one of the following ways:

1. @RequestParam instead of @RequestBody:

@RequestMapping(value = "/sendmail/sendInvitations",
        method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody returnType methodName(@RequestParam Map<String, String> name) {
    ...
}

2. Remove @RequestBody and use your POJO class:

@RequestMapping(value = "/sendmail/sendInvitations",
        method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody returnType methodName(YourPOJO pojo) {
    ...
}

I hope this helps you.