0

Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view? I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.

Maybe there's a way to do it with thymeleaf?

4
  • @RequestParam can be used to pass values.May be you can share some more info and some code to have better understanding of the problem you are facing. Commented Dec 5, 2021 at 23:27
  • I have a controller method that I wish to pass a variable from a javascript function. ``` @GetMapping("/project/task") public String test(@RequestParam long id) { // create model from task id that goes to new view page return "taskpage"; } ``` The javascript function retrieves the variable (task id), when clicking on a task (gantt diagram from google charts api). ``` $.ajax({ contentType: "application/json", type: "GET", data: taskId url: "/project/task/"+id, }); } ``` It doesnt work without requestbody (which doesnt load the new page) Commented Dec 5, 2021 at 23:38
  • From Javascript you are passing id in the url. So you can use @PathVariable to get it in controller. @GetMapping(“project/task/{id}”) public String test(@PathVariable Long id) Commented Dec 5, 2021 at 23:44
  • @Cozimetzer That almost works, except it still won't load the new html page, but stays on the same page.. hmm.. Commented Dec 5, 2021 at 23:58

1 Answer 1

1

If you're using Thymeleaf then just reference the template you want to return to the user by its filename.

@Controller
public class YourController {

    @GetMapping("/someUrl")
    public String getTemplate(@RequestParam String templateName){
        return templateName;
    }
}

This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.

Edit: Reading through the comments I realized there might be a confusion between @RequestParam and @PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do

@Controller
public class YourController {

    @GetMapping("/someUrl/{templateName}")
    public String getTemplate(@PathVariable String templateName){
        return templateName;
    }
}

Resources for both below:

https://www.baeldung.com/spring-request-param

https://www.baeldung.com/spring-pathvariable

Sign up to request clarification or add additional context in comments.

Comments

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.