How to Access a Model Attribute With JavaScript Variable

How do you access a model attribute with javascript variable

there is no way you can access model atributes hence they are on server side and they where lost when rendering jsp into HTML

How to access model attribute in Javascript

First of all, there's no way to convert a Java object to a Javascript object directly since they have nothing to do with each other. One is server-side language and the other is client-side language.


So to accomplish this goal, you have to do some convertion. I think you have two options:

  1. Convert ResponseDTO object to JSON string and pass it to jsp and you may get the javascript object directly.
  2. Pass ResponseDTO object to JSP and populate the javascript object as what you are trying now.

For option #1, you should use a library to generate JSON string by the Java object. You can use this one JSON-lib.
e.g:

JSONObject jsonObject = JSONObject.fromObject( responseDTO );  
/*
jsonStr is something like below, "errors" represents the List<ObjectError>
I don't know what's in ObjectError, errorName is just an example property.
{
"dataRequestName":"request1",
"actionPassed":true,
"errors":[{"errorName":"error"},{"errorName":"unknown error"}]
}
*/
String jsonStr = jsonObject.toString();
model.addAttribute("dataJson", jsonStr);

/*In JSP, get the corresponding javascript object
by eval the json string directly.*/
<script>
var data = eval('('+'${dataJson}'+')');
</script>

For option #2,

//Pass java object as you do now
model.addAttribute("data",responseDTO);

//In JSP, include jstl taglib to help accessing List.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<script>
var errorArr = [], errorObj;
<c:forEach var="error" items="${data.errors}">
errorObj = { errorName: '${error.errorName}' };
errorArr.push(errorObj);
</c:forEach>

//Populate the corresponding javascript object.
var data = {
dataRequestName: '${data.dataRequestName}',
actionPassed: ${data.actionPassed},
errors: errorArr
};
</script>

As you can see, option #2 is complicated and only useful if the Java object is simple while option #1 is much easier and maintainable.

How do you access a model attribute (liste) in Jquery

As an option, you could use a converter from Java object to JSON. Such as Jackson.

Then your code can be following:

ObjectMapper mapper = new ObjectMapper();
String jsonInString = mapper.writeValueAsString(listRdv);
model.addAttribute("listRvd", jsonInString);

Then in your thymeleaf template, you can assign this JSON object as a javascript variable.

Although It is not the best practice you can try this out.

Use Spring Model attribute to set js variable

You can use Model object and use addAttribute method for every object you need to have in ajax success function. In every Spring method you can add Model object, for example:

@RequestMapping(value="value", method = RequestMethod.POST)
public @ResponseBody String yourMethod(@RequestParam(value="yourParam") String yourParam,
Model model){
String a = "Your String";
int b = 456;

model.addAttribute("myString", a);
model.addAttribute("myInt", b);

return "";
}

The success function must be declared with one parameter, that is the response. Inside this parameter you will find the parameters you added in model object (myString and myInt):

success: function(response){   
// response.myString will be "Your String"
// response.myInt will be 456
}

Accessing java variable from javascript in spring mvc

In the JSP page you can set the values as javascript variables by adding a script tag in the <head> with the assignment inside as a json object for example:

<script>
var myServerSideVars = {
"aServerSideVarName" : "<here you set the value with el/jslt/scriptlet>",
"anotherServerSideVarName" : "<here you set the value with el/jslt/scriptlet>"
};
</script>

EDIT I

Example using EL (Expression Language) but the same could be done with scriptlets if you are using that (<% %>):

Lets say in your Servlet you put a Car instance in the request before forwarding to the JSP page.

The car:

public class Car{
protected String brand;
protected String year;

//getters and setters for the two properties.
}

In the Servlet you put it into the request:

Car car = new Car();
car.setBrand("BMW");
car.setYear("2017");
request.setAttribute("carInRequest", car);

In the JSP you set it to a Json Object accessible from javascript. Before closing the body tag I put a simple example of how the var can be accessed from javascript. I haven't run it so it may have some typo or error to correct:

<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<html>
<head><title>System.out.println</title>
<script>
var aCar= {
"brand" : "${requestScope.carInRequest.brand}",
"year" : "${requestScope.carInRequest.year}"
};
</script>
</head>

<body>
<h2>Brand: <span id="brandPlaceHolder"></span></h2>
<h2>Year: <span id="yearPlaceHolder"></span></h2>

</body>
<script>
var brandSpan = document.findElementById("brandPlaceHolder");
brandSpan.html = aCar.brand;
var yearSpan = document.findElementById("yearPlaceHolder");
brandSpan.html = aCar.year;
</script>
</html>

How do you access a model attribute in jquery?

<script type="text/javascript">
var modelAttributeValue = '${modelAttribute}';
</script>

This will resolve the model attribute added by model.addAttribute("modelAttribute", value)



Related Topics



Leave a reply



Submit