我的项目基于spring、Thymeleaf、mysql、html和Jquery。
我试图将输入的字符串数据发送到@RestController页面,但是它接收为空,这意味着null。这是我的代码细节
<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;
}
请帮我解决这个问题..。
发布于 2017-11-16 04:52:54
由于您不执行从该表单到模型类的任何绑定活动,并且只想传递字符串,所以尝试使用@RequestParam而不是@ModelAttribute:
public ModelAndView doAddCharge(@RequestParam("chargeName") String chargeName)
发布于 2017-11-16 21:56:58
我做了一个代码changes....In HTML添加
th:object="${chargeName}“
在形式中,添加输入标记
name="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;
}
https://stackoverflow.com/questions/47328701
复制相似问题