[英]How to parse the field of a binded object to int in the HTML using ThymeLeaf?
<form th:action="@{/gustos}" method="post" th:object="${gusto}">
<input type="hidden" th:field="*{id}"/>
<div class="row">
<div class="col s12">
<h2> Borrar Gusto</h2>
</div>
</div>
</form>
我正在使用绑定的对象th:object =“ $ {gusto}”来访问HTML中的每个对象属性。
捕获id的隐藏输入正在将其解析为String ...我需要再次解析它,以便可以从控制器访问变量或执行以下操作:
<div class="row delete" th:id="*{gusto.id != null}">
<div class="col s12 l8">
<form th:action="@{|/gustos/${gusto.id}/delete|}" method="post">
<button type="submit" class="button">Borrar</button>
</form>
</div>
</div>
但这并不能让我忽略该字段是一个String,并且期望一个int。
有什么方法可以使用ThymeLeaf在HTML中解析该字段(“ id”)?
这是我的控制器处理视图的方法:
@RequestMapping(value = "/gustos/{id}/delete", method = RequestMethod.POST)
public String deleteGustoId(@PathVariable int id, Model model){
Gusto gusto = gustoService.findGustoById(id);
model.addAttribute("gusto", gusto);
gustoService.delete(gusto);
return "deleteGusto";
}
我相信问题出在您的th:action
。 您使用的是我未曾见过或未使用过的语法,所以我不确定它是否可以工作。 我还没有使用其他语法方式,这种方式一直有效。 尝试使用以下代码更改代码。
<form th:action="@{'/gustos/'+ ${gusto.id} +'/delete'}" method="post">
<button type="submit" class="button">Borrar</button>
</form>
更新
因为我们得到的是String
,所以我们可以在Controller中进行简单的转换。 如果我们确定我们要接收的参数是一个int值,则为true。
@RequestMapping(value = "/gustos/{id}/delete", method = RequestMethod.POST)
public String deleteGustoId(@PathVariable String id, Model model){
int numId = Integer.parseInt(id);
Gusto gusto = gustoService.findGustoById(numId);
model.addAttribute("gusto", gusto);
gustoService.delete(gusto);
return "deleteGusto";
}
奇怪的是,Spring应该为您自动进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.