How to get spring value of mvc controller model key inside javascript?

I am using spring mvc controller. Inside the controller, I put some value to say a line inside the model. Now I would like to get this value or just say that print this value inside javascript. How can I do it? Here is my controller class. I am adding a “movie” as a key. Now I want to display this movie name inside a java script (not inside a JSP. However inside JavaScript)

@Controller @RequestMapping("/movie") public class MovieController { @RequestMapping(value="/{name}", method = RequestMethod.GET) public String getMovie(@PathVariable String name, ModelMap model) { model.addAttribute("movie", name); return "list"; } } 

here is my jsp

 <html> <head> //I want to print movie name inside java script not inside jSP body tag. <script type="text/javascript"> var movie_name = ${movie}; alert("movies name"+ movie_name); </script> </head> <body> <h3>Movie Name : ${movie}</h3>//When i print here its working fine. </body> </html> 
+8
javascript jquery spring spring-mvc jsp
source share
2 answers

Use this:

 var movie_name = "${movie}"; 

instead:

 var movie_name = ${movie}; 

When using ${movie} value becomes placed on the page without quotes. Since I assume this is a string, Javascript requires the strings to be surrounded by quotation marks.

If you checked your browser console, you would probably see an error, for example, Unexpected identifier or ___ is not defined .

+17
source share

Try it...

If you added an object to the model as:

 model.addAttribute("someObject", new Login("uname","pass")) 

Then you get the properties of the model object as

 var user_name = ${someObject.uname}; // This is assuming that the Login class has getter as getUname(); var user_pass = ${someObject.pass}; 
+1
source share

All Articles