Search code examples
spring-boothidden-field

Get value of hidden field in form


Here is my login form with hidden field name "callbackUrl". How can i get the value of this hidden field in controller? User's attributes are username and password. callbackUrl is not.

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="/resources/css/bootstrap.min.css" rel="stylesheet">
    <link href="/resources/css/common.css" rel="stylesheet">
<title>Authentication Service</title>
</head>
<body>
<form method="POST" action="/login" modelAttribute="userFormLogin" class="form-signin">
    <h2 class="form-heading">Log in</h2>
    <input name="username" type="text" class="form-control" placeholder="Username"
       autofocus="true"/>
    <input name="password" type="password"  class="form-control" placeholder="Password"/>
    <input name="callbackUrl" type= "hidden" id="callbackUrl">
    <h2>${error}</h2>
    <br/>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
    <h4 class="text-center"><a href="/registration">Create an account</a></h4>
</form>
</body>
<script>
    var url_string = window.location.href; //window.location.href
    var url = new URL(url_string);
    var c = url.searchParams.get("callbackUrl");
    console.log(c);
    document.getElementById("callbackUrl").value = c;
</script>
</html>

Solution

  • add @RequestParam("callbackUrl") String callBackUrl to the method in your controller.

    Like so:

    public String myMethod(@RequestParam("callbackUrl") String callBackUrl, …) {
        System.out.println(callBackUrl); //this will print the url to console
    }