gpt4 book ai didi

java - Spring表单——modelAttribute名称作为java常量

转载 作者:行者123 更新时间:2023-12-01 05:21:48 25 4
gpt4 key购买 nike

为了不在代码中重复我自己,我使用了 modelAttribute 名称作为 java 常量

@Controller
@RequestMapping("/")
public class Controller {
public static final String MODEL_ATTRIBUTE = "myModel";

public String renderPage(Model model) {
model.addAttribute(MODEL_ATTRIBUTE, ...);
return "index";
}
}

现在我使用 scriptlet 将此常量导入到 JSP 中(我知道 scriptlet 很糟糕,但我不熟悉更好的解决方案)。

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<%@page import="static com.example.Controller.*" %>

<form:form action="/" modelAttribute="<%= MODEL_ATTRIBUTE %>">

<form:label path="attr1">Attribute:</form:label>
<form:input path="attr1" />

<c:forEach items="${???.attr2}" var="item">
...
</c:forEach>
<input type="submit" />
</form:form>

我应该如何在 forEach 循环中引用 modelAttribute 对象? DRY有更好的解决方案吗?以 Spring 形式?

最佳答案

使用型号名称,

<c:forEach items="${myModel.attributeNameFromYourModel}" var="item">
...
</c:forEach>

关于java - Spring表单——modelAttribute名称作为java常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10297788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com