我需要将一个复杂的对象从视图页传递到Spring控制器。我正在尝试使用using属性(视图页是使用Thymeleaf和HTML构建的)。
我的问题是,对象是作为字符串传递的,而不是实际的对象,这会导致控制器端的强制转换异常。例如,下面的“类别”是一个复杂的对象,其中包含一个列表、一个数组、一个字符串和其他作为变量的对象。类别作为字符串而不是对象本身传递。如何将此对象传递给控制器?
@Controller
public class QController extends WZController{
@RequestMapping(value = "/refreshfacets")
public String refreshfacets(HttpServletRequest request, HttpServletResponse response, Model model,
@ModelAttribute("refreshFacetsRequest") refreshFacetsRequestDTO refreshfacetsrequest) throws Exception {
Map<String, Object> responseMap = new HashMap<String, Object>();
ProductSearchResult productsearchresult = new ProductSearchResult();
//super.refreshFacets(request, response, model, productsearchresult);
return XXXX;
}
}
public class refreshFacetsRequestDTO {
private static final long serialVersionUID = 1L;
private Category category;
private String state;
private String program;
private String subject;
private String year;
private String price;
// Constructor, getter, setter methods;
}
<div th:remove="tag">
<form method="post" id="form1" th:action="@{/refreshfacets}" th:object="${refreshFacetsRequest}">
<input type="hidden" id="category" name="category" th:if="${category}" th:value="${category}"/>
<input type="text" id="state" name="state" th:if="${state}" th:value="${state}"/>
<input type="text" id="program" name="program" th:if="${program}" th:value="${program}"/>
<input type="text" id="subject" name="subject" th:if="${subject}" th:value="${subject}"/>
<input type="submit" th:attr="onsubmit=${'doAjaxPost()'}"></input>
</form>
</div>
请对此提出建议。传递对象的任何其他选项(模型属性除外)也是可以的。如果是的话,请详细说明你的其他选择。
发布于 2013-08-27 10:28:26
您似乎希望将Thymeleaf
的选择器表达式与th:object="${refreshFacetsRequest}"
一起使用。该表达式的表示法是*{someField}
。相应地更改元素。
<input type="hidden" id="category" name="category" th:if="*{category}" th:value="*{category}"/>
以上将解决${refreshFacetsRequest.category}
问题。
编辑
从View到Controller,您要做的是让浏览器向HTTP服务器( servlet容器)发送HTTP请求。这里没有物体的概念。名为<input>
的category
字段将作为请求参数在HTTP中传递。
Spring通常足够聪明,可以从请求参数转换为对象,但它需要一些信息。Category
是一个枚举吗?如果是的话,Spring将尝试使用Category.valueOf(requestParam)
来转换它。如果它是一个类,它将尝试使用其他具有与Category
类字段匹配的名称的请求参数来实例化它,并在您用@ModelAttribute
声明的refreshFacetsRequestDTO
对象中设置它。
我不太明白您所说的检索值是字符串值是什么意思。是否出现了错误消息?
https://stackoverflow.com/questions/18471196
复制相似问题