Search code examples
spring-bootthymeleaf

How to POST a input string value using thyemeleaf?


My project based on spring boot,Thymeleaf,mysql,html and Jquery.

i tried to post the input String data to @RestController page,but it received as EMPTY which means null. Here is my Code Details

HTML

<form id="addchargesformid" method="post" th:action="@{/addcharge}">  
 <!-- input box add -->
 <div class="form-group">
    <label for="chargeName">Add New Charge*</label> 
    <input th:id="chargeName" th:name="chargeName" th:value="${chargeName}" type="text" class="form-control" placeholder="Ex : Maintanence charge">
</div>
<br/>
<button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
</form>

@RestController

/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@ModelAttribute String chargeName)
{
    ModelAndView respondResult = new ModelAndView();
    try {
        String result  = serAssignCharges.doAddCharges(chargeName);
        if(result.equals("success"))
        {
            doGetChargesList();
        }
        else {
            respondResult.addObject("warning","sorry! failed to add");
        }

    } catch (Exception e) {
        // TODO: handle exception
    }
    return respondResult;
}

Please help me to resolve this...


Solution

  • Since you don't do any binding activities from that form to a model class, and you just want to pass the string, try using @RequestParam instead of @ModelAttribute:

    public ModelAndView doAddCharge(@RequestParam("chargeName") String chargeName)