[java] How to access Spring MVC model object in javascript file?

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!

This question is related to java javascript jquery spring spring-mvc

The answer is


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);
}

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);
});

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>

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();


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);
});

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>

   @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>

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)