简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM