gpt4 book ai didi

java - 如何映射 ModelAttribute 的属性?

转载 作者:搜寻专家 更新时间:2023-11-01 03:55:12 25 4
gpt4 key购买 nike

我有一个像这样映射的请求

@RequestMapping(value = "/path", method = RequestMethod.POST)
public ModelAndView createNewItem(@ModelAttribute PostRequest request)

并且 PostRequest 有一些属性,例如userName (getUserName()/setUserName()) 但客户端发送的参数如 user_name=foo 而不是 userName=foo。是否有注释或自定义映射拦截器可以在不放置所有这些丑陋的 setUser_name() 方法的情况下执行此操作?

由于这种情况经常发生(我必须实现一个 API,其中所有内容都使用下划线),因此在实现方面付出一些努力是可以接受的。

最佳答案

为什么不使用Spring的表单标签库呢? http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/view.html#view-jsp-formtaglib

标签库(结合您的 Controller )自动映射您的 ModelAttribute。在对表单执行 GET 请求时,您会创建一个新的(可能是空的)PostRequest 对象并将其粘贴到模型中。发布表单后,spring 会为您提供带有表单值的 ModelAttribute。

原理图示例:

Controller :

@RequestMapping(value="/path", method = RequestMethod.GET)
public String initForm(ModelMap model) {

PostRequest pr = new PostRequest();
model.addAttribute("command", pr);

return "[viewname]";
}

@RequestMapping(value="/path", method = RequestMethod.POST)
public ModelAndView postForm(
@ModelAttribute("command") PostRequest postRequest) {

// postRequest should now contain the form values
logger.debug("username: " + postRequest.getUsername());

return "[viewname]";
}

jsp:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form:form method="post" enctype="utf8">
Username: <form:input path="username" />
<br/>
<%-- ... --%>
<input type="submit" value="Submit"/>
</form:form>

关于java - 如何映射 ModelAttribute 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733811/

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