1

I use a Spring MVC controller method in order to display a html view and that view requires JSON data that is available in the model i.e. a collection/array of postcodes.

I thought of outputting the JSON data inline in the html view inside <script tags but before doing so I would like to know whether there isn't a better practice...

Can anyone please advise?

1 Answer 1

1

You might want to do something like:

@RequestMapping(value="/yourmapping", method=RequestMethod.GET, produces={MediaType.TEXT_HTML_VALUE, MediaType.ALL_VALUE})
public String page(Model m){        
    m.addAttribute("postcodes", new ArrayList<String>());       
    return "your-jsp-name";
}

Then in your jsp you can access the collection like ${postcodes} and loop over it or set its string representation into a hidden span for example and then your JavaScript can process the data.

EDIT:

<script type="text/javascript">
    var postcodes = "${postcodes}"; 
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I implemented your solution. I actually wanted to avoid putting hidden html in the DOM but never mind... Thanks.
Well you don't have to use a span, you could also access ${postcodes} in a script block -- see my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.