Brarord
Brarord

Reputation: 651

How to handle variable from Spring controller using javascript?

Guys i have problem to get data from variable after execute rest in my controller. Here is sample to show my problem.

Controller

@RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, @PathVariable("id") Integer id)
{
    model.addAttribute("message", "why this isn't working...");
    return "redirect:/drawdiagram";
}

JavaScript drawdiagram.html

<script th:inline="javascript">
    /*<![CDATA[*/
    var message = /*[[${message}]]*/ 'default';
    /*]]>*/
</script>

Result

enter image description here

Anyony can tell me why i have null there?
I really don't know what is going on :(
Maybe this is bad way? I have chosen thymeleaf but maybe there is some other way?

All i need to do is:
1. Click button.
2. Execute some backend code and get data to variable in controller.
3. Redirect to other page.
4. Execute some JavaScript code which is based on that variable.

.

Sources:

  1. https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
  2. Setting up a JavaScript variable from Spring model by using Thymeleaf

Upvotes: 1

Views: 590

Answers (1)

BHAWANI SINGH
BHAWANI SINGH

Reputation: 729

you are redirecting to another controller drawdiagram, the values in model object won't be available in other controller. So here you need to set the value first using either RedirectAttributes#addFlashAttribute or RedirectAttributes#addAttribute, and then get the value in the other controller -using @ModelAttribute("message").

@RequestMapping(path = "/editSchema/{id}")
public String editSchemaById(Model model, @PathVariable("id") Integer id, RedirectAttributes redirectAttributes)
{
    redirectAttributes.addFlashAttribute("message", "why this isn't working...");
    return "redirect:/drawdiagram";
}

@RequestMapping(value = "drawdiagram", method = RequestMethod.GET)
public String OtherController(@ModelAttribute("message") String message, Model model) {
    model.addAttribute("message", message);
    return "drawdiagram";
}

Upvotes: 1

Related Questions