繁体   English   中英

将对象从视图页面传递到Spring控制器

[英]Passing an object from view page to Spring controller

我需要将一个复杂的对象从视图页面传递给Spring控制器。 我正在尝试使用modelattribute(查看页面是使用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>

请对此提出建议。 除传递给对象的模型属性以外的任何其他选项也是可以的。 如果是这样,请详细说明您的其他选择。

您似乎想将Thymeleaf的选择器表达式与th:object="${refreshFacetsRequest}" 表示法是*{someField} 相应地更改您的元素

<input type="hidden" id="category" name="category" th:if="*{category}" th:value="*{category}"/>

以上将解析为${refreshFacetsRequest.category}

编辑

从View到Controller,您正在做的是使浏览器将HTTP请求发送到HTTP服务器(您的servlet容器)。 这里没有对象的概念。 名称category<input>字段将作为请求参数传递到HTTP POST中。

Spring通常足够聪明,可以将请求参数转换为对象,但是它需要一些信息。 Category是枚举吗? 如果是这样,Spring将尝试使用Category.valueOf(requestParam)进行转换。 如果它是一个类,它将尝试使用名称与Category类的字段匹配的其他请求参数来实例化它,并将其设置在使用@ModelAttribute声明的refreshFacetsRequestDTO对象中。

我不太了解您所检索的值是String值i的意思 是否出现错误消息?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM