Accessing Spring MVC Model Object in AngularJS

Viewed 1440

I have a Spring MVC web form built using JAVA Spring MVC (Backend) and AngularJS (frontend), JSP(for view) and MySQL DB. A user is able to submit the form after filling it out and search an existing entry. An email is also sent out to the user once the entry has been submitted. The entry also gets saved on a database. In the email body, I am trying to have a link which redirects the user to the form populated with the entries corresponding to the given id..the same way as when the search button is clicked..the form gets populated with the existing form fields..

Currently I wrote a controller which returns the JSP page with the data (searchData)..using ModelAndView however.. it is not populating the form with the details of the entry. How can I achieve this functionality?

I wrote the below code for the controller

@RequestMapping(value = "/searchById", method = RequestMethod.GET)
public ModelAndView populateEntrydata(@RequestParam(value = "id") String id) {
    String url= "http://localhost:8080/myform/searchById?id=" + id;
    ModelAndView model = new ModelAndView("index"); //jsp page
    ResponseEntity<Data> searchData = search(id);

    model.addObject("searchById", searchData);
    // String, String, object
    return model;
}  

How can I access the model object in the angularJS controller so I can populate the jsp with the contents i receive from the ModelAndView?

2 Answers

The mistake that you are doing here is mixing serverside presentation (JSP) and clientside presentation (Angular) layers. When you are dealing with clientside presentation technologies like Angular (react or vue or any yet-another-javascript framework) all your server side needs to worry about is the data (usually json/xml) not the view (html).

Solution

If you made up your mind about Angular or any other SPA, then forget about JSP, create a spring boot rest webservice.

I would like to suggest a slightly different approach. When user clicks on the link in the email, it gets redirected to the form. In this proccess, dont fetch the data. Write a method in controller, which gets loaded with the page. In this method you will make call to the method in your spring controller with something like this:

$http.get(<url>).success(funtion(data){
    console.log(data);
});

The url is the url to call the method in java controller(along with the id as url parameter). You will receive the response data from java app in the data variable. From there you can use it to populate the jsp page. Hope that helps.

Related