Search code examples
javaspringspring-mvcspring-form

Binding data with Spring MVC form


So far I am able to bind the user input data from the front end by using form binding(with POJOs). For example, I can bind

<input type="number" name="age" />

by creating method in the controller like this:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@RequestParam("age") Integer age) {}

Now I have something like this:

<input type="number" name="yourAge" />
<input type="number" name="myAge" />
<p name="ageDifference"> </p>

Here, I wrote some java script to simply calculate the age difference by substracting yourAge and myAge, and the ageDifference will automatically shows up in the <p> paragraph.What I really want to do is bind the output, i.e. ageDifference to the controller. I am thinking something like this:

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@RequestParam("ageDifference") Integer ageDifference) {}

But when I run it, I do not think spring is able to bind the data, this is a simplified question, I tried to save the data into database, but got HTTP 400 error:

Required String parameter 'ageDifference' is not present

description: The request sent by the client was syntactically incorrect.

Is this doable? Or am I in the completely wrong direction here?


Solution

  • You can make it as a hidden variable and you will get it in java to make a variable hidden ,you simply need to change your code

    to hidden by using below example,.same will be need to change in java Controller also,the name ageDifferencehidden

     <input type="hidden" name="ageDifferencehidden" value=${ageDifference}/>