我的项目基于spring boot,Thymeleaf,mysql,html和Jquery。
我试图将输入的String数据发布到@RestController页面,但它收到的是EMPTY,这意味着null。 这是我的代码详细信息
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;
}
请帮我解决这个问题......
答案 0 :(得分:2)
由于您没有从该表单到模型类的任何绑定活动,并且您只想传递字符串,请尝试使用@RequestParam而不是@ModelAttribute:
public ModelAndView doAddCharge(@RequestParam("chargeName") String chargeName)
答案 1 :(得分:0)
我进行了代码更改....在HTML中添加
个:对象= “$ {chargeName}”
在表单中,添加输入标记
名称= “chargeName”
完整代码
<form id="addchargesformid" method="post" th:action="@{/addcharge}" th:object="${chargeName}">
<!-- input box add -->
<div class="form-group">
<label for="chargeNameid">Add New Charge</label>
<input id="chargeNameid" name="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 强>
将@ModelAttribute更改为@RequestParam
/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@RequestParam String chargeName)
{
ModelAndView respondResult = new ModelAndView();
try {
String result = serAssignCharges.doAddCharges(chargeName);
if(result.equals("success"))
{
respondResult = new ModelAndView("redirect:" + "/getchargeslist"); /*it is redirecting from
"/addcharge" to "/getchargeslist" */
}
else {
respondResult.addObject("warning","sorry! failed to add");
}
} catch (Exception e) {
// TODO: handle exception
}
return respondResult;
}