How to access Spring MVC model object in javascript file?

前端 未结 8 1157
南方客
南方客 2020-12-28 19:05

I am using spring 3 MVC and i have below classes.

External system would call my application using below URL:

http://somehost/root/param1/param2/param         


        
8条回答
  •  不知归路
    2020-12-28 19:24

    This way works and with this structure you can create your own framework and do it with less boilerplate.

    Sorry if some error is present, I'm writing this handly with my cellphone

    Maven dependency:

    
        com.google.code.gson
        gson
        1.7.1
    
    

    Java:

    Person.java (Person Object Class)

    Class Person {
    
        private String name;
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    PersonController.java (Person Controller)

    @RestController
    public class PersonController implements Controller {
    
        @RequestMapping("/person")
        public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
            Person person = new Person();
            person.setName("Person's name");
            Gson gson = new Gson();
    
            ModelAndView modelAndView = new ModelAndView("person");
            modelAndView.addObject("person", gson.toJson(person));
    
            return modelAndView;
        }
    }
    

    View:

    person.jsp

    
        
            Person Example
            
            
        
        
            

    Person/h1>

    Javascript:

    personScript.js

    function parseJSON(data) {
        return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); 
    }
    
    $(document).ready(function() {
        var personJson = $('#person');
        person = parseJSON(personJson.val());
        alert(person.name);
    });
    

提交回复
热议问题