How to access Spring MVC model object in javascript file?

前端 未结 8 1077
南方客
南方客 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:13

    JavaScript is run on the client side. Your model does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

    If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.

    Update:

    A simple example

    <%-- SomeJsp.jsp --%>
    <script>var paramOne =<c:out value="${paramOne}"/></script>
    
    0 讨论(0)
  • 2020-12-28 19:18

    in controller:

    JSONObject jsonobject=new JSONObject();
    jsonobject.put("error","Invalid username");
    response.getWriter().write(jsonobject.toString());
    

    in javascript:

    f(data!=success){
    
    
    
     var errorMessage=jQuery.parseJson(data);
      alert(errorMessage.error);
    }
    
    0 讨论(0)
  • 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:

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>1.7.1</version>
    </dependency>
    

    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

    <html>
        <head>
            <title>Person Example</title>
            <script src="jquery-1.11.3.min.js"></script>
            <script type="text/javascript" src="personScript.js"></script>
        </head>
        <body>
            <h1>Person/h1>
            <input type="hidden" id="person" value="${person}">     
        </body>
    </html>
    

    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);
    });
    
    0 讨论(0)
  • 2020-12-28 19:29

    I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

    <script>
      var model=[];
      model.paramOne="${model.paramOne}";
      model.paramTwo="${model.paramTwo}";
      model.paramThree="${model.paramThree}";
    </script>
    

    Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

    $(document).ready(function() {
       alert(model.paramOne);
    });
    
    0 讨论(0)
  • 2020-12-28 19:29

    You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).

    I suggest you to use ajax and @ResponseBody.

    0 讨论(0)
  • 2020-12-28 19:31
       @RequestMapping("/op")
       public ModelAndView method(Map<String, Object> model) {
           model.put("att", "helloooo");
           return new ModelAndView("dom/op");
       }
    

    In your .js

    <script>
        var valVar = [[${att}]];
    </script>
    
    0 讨论(0)
提交回复
热议问题