How to access Spring MVC model object in javascript file?
Asked Answered
G

9

17

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/param3

I have a spring MVC controller method as below:

public ModelAndView showPage(@PathVariable("param1") String paramOne, @PathVariable("param2") String paramTwo, @PathVariable("param3") String paramThree, HttpServletResponse response) {  
        SomeModel model = new SomeModel(paramOne, paramTwo, paramThree);
       return new ModelAndView("SomeJsp", "model", model);
    } 

SomeModel.java

public class SomeModel{
 private String paramOne;
 private String paramTwo;
 private String paramThree;
//constructor
 //setters and getters

}

SomeJsp.jsp

//In this Jsp i have a div with few elements. Div is not visible by default.
//This jsp has externalJavascript included.
//I enable div and set the data into div elements using jquery.
<script src="<c:url value="/resources/js/extjs.js" />" type="text/javascript"></script>

externalJs.js

$(document).ready(function() {

    //Here i need the model returned using ModelAndView
//I can get data from model and set into div elements.


});

In external java script file, is it possible to get the model content? If possible, how can i do that?

Thanks!

Gnat answered 19/3, 2014 at 14:19 Comment(1)
<script type="text/javascript">var myVar = "${model.paramOne}";</script>Bedspread
O
33

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>
Octahedral answered 19/3, 2014 at 14:24 Comment(5)
Aurand, Could you please provide me some code snippet for your answer? Thanks!Gnat
Aurand, now can i access paramOne in an external js included in same jsp?Gnat
paramOne is a JavaScript variable. Just access it by name.Octahedral
That first paragraph opened my eyes and made things a lot clearer. Thanks.Bedsore
I was getting errors implying it was interpreting this example as a regular expression. Once I did <script>var JsParam = "${JavaParam}"</script> (note the quotes), it worked.Nadanadab
S
20

Another solution could be using in JSP: <input type="hidden" id="jsonBom" value='${jsonBom}'/>

and getting the value in Javascript with jQuery:

var jsonBom = $('#jsonBom').val();

Safko answered 21/1, 2015 at 9:43 Comment(0)
G
11

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);
});
Guarani answered 9/9, 2014 at 3:6 Comment(0)
C
8

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);
});
Conjugal answered 21/11, 2015 at 7:27 Comment(2)
Could you please add some explanation on the magic that happens especially in the JS part?Axenic
i follow this.. i got json parse exception "Uncaught SyntaxError: Unexpected end of JSON input" when i print personJson.val() -> alert shows "{"Marquesan
L
5

Here is an example of how i made a list object available for javascript:

var listForJavascript = [];
<c:forEach items="${MyListFromJava}" var="listItem">
  var arr = [];

  arr.push("<c:out value="${listItem.param1}" />");
  arr.push("<c:out value="${listItem.param2}" />");

  listForJavascript.push(arr);
</c:forEach>
Latitudinarian answered 30/6, 2014 at 16:29 Comment(0)
P
1

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.

Palliate answered 19/3, 2014 at 14:25 Comment(1)
Max, here i cannot make ajax call, since controller is being called from external application and is directly mapped to controller method.Gnat
C
0

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);
}
Cockcrow answered 31/7, 2019 at 9:22 Comment(0)
R
0
   @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>
Reckon answered 17/5, 2020 at 3:37 Comment(0)
B
0

I have used a hidden tag and passed object to js.

<input type="hidden" id="jsonBom" value='${jsonBom}'/>

you can access value of the tag using id

Baer answered 24/8, 2022 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.