Kenned Larsen
Kenned Larsen

Reputation: 1

Passing javascript variable to spring MVC controller with request param

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?

Upvotes: 0

Views: 1014

Answers (1)

Dropout
Dropout

Reputation: 13866

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

Upvotes: 1

Related Questions