简体   繁体   中英

How to dynamically populate javascript file directly from spring boot java controller in json format?

In my main.js file I want to have data from spring boot controller in some specific json format. eg.

var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"},
                    {"userId": "seconduser", "displayName": "seconduser"}];

Now in my controller "/users" i'm returning list of all users. I want that at the time of application loading the value of contactsJSON gets populated dynamically in required json format (I only need username to create JSON).

main.js

var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"
                    },
                   {"userId": "seconduser", "displayName": "seconduser"
                   },
                   {"userId": "thirduser", "displayName": "thirduser"
                   }
                  ];

UserController.java

 @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String viewUsers(Model model) {

       List<User> list = userService.getAllUsers();

       model.addAttribute("userList", list);

       return "welcome";
    }

List contains  private Long id;
    private String username;
    private String password;
    private String passwordConfirm;

I want to dynamically provide value of contactsJSON in my javascript file. How can I do this ?

First, a Thymeleaf recommendation

I highly recommend Thymeleaf over JSP templates. For one thing, it makes inline object-to-JSON expressions very easy. For example...

<script th:inline="javascript">
const contactsJSON = [[${userList}]];
</script>

See https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#advanced-inlined-evaluation-and-javascript-serialization


If you don't want to switch, I would recommend adding an AJAX call to fetch your user data. On the Java side, it might look like this

@GetRequest(path = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getAllUsers() {
    return userService.getAllUsers();
}

Spring will automatically serialize the response as JSON.

Then in your welcome.jsp

<script>
// load the current URL (ie /users) but requesting JSON
fetch('', {
  headers: {
    Accept: 'application/json'
  }
}).then(res => res.json()).then(contactsJSON => {
  // you can now use contactsJSON here
})
</script>

You can either return a response as String or you can use ResponseEntity Object provided by Spring as below. By this way, you can also return Http status code which is more helpful in the web service call.

@RestController
@RequestMapping("/api")
public class MyRestController
    {

        @RequestMapping(value = "/users", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Object> viewUsers(Model model) {
        {
             //Get data from service layer into entityList.
            List<User> list = userService.getAllUsers();
            List<JSONObject> entities = new ArrayList<JSONObject>();
            for (Entity n : list) { // You can  iterate over the list and add in json format below is the example  for same 
                //JSONObject entity = new JSONObject();
                //entity.put("aa", "bb");
                //entities.add(entity);
            }
            return new ResponseEntity<Object>(entities, HttpStatus.OK);
        }
    }

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