SpringBoot jsonの受け取りと返却
jsonの受け取りと返却を試した
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>User Setting</title> <script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script> <script> $(function() { $('#submit').on('click',function(){ var json = { 'name':$('#name').val(), 'password':$('#password').val() }; // リストの場合[{json1},{json2}]... $.ajax({ url:'/json', type:'POST', contentType: 'application/json', data:JSON.stringify(json), dataType:'json' }) .done((data, textStatus, jqXHR) => { alert(JSON.stringify(data)); }) .fail((jqXHR, textStatus, errorThrown) => { alert(jqXHR.status); }) .always((data) => { }); }); }); </script> </head> <body> <form method="post" action="/body"> <label for="name">名前:</label> <input type="text" name="name" id="name"><br> <label for="password">パスワード:</label> <input type="text" name="password" id="password"> <input type="button" id="submit" value="送信" /> </form> </body> </html>
jsonのデータ格納先
public class User implements Serializable { private static final long serialVersionUID = 1L; private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
コントローラ
@RequestMapping(value= {"/json"}, method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public User index(@RequestBody User user) { return user; } // リストの場合 @RequestMapping(value= {"/json"}, method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List<User> index(@RequestBody List<User> users) { return users; }