【问题标题】:How to send String value back to Spring MVC?如何将字符串值发送回 Spring MVC?
【发布时间】:2014-09-07 17:16:42
【问题描述】:

问题

我的观点有两种形式:

<form:form method="post" action="/insertChapter" modelAttribute="Chapter">
<form:input type="hidden" path="chapter" value="${info.chapter}"/>
<form:input path="title" />
<input type="submit" value="Insert" />
</form:form>

<form:form method ="GET" action="/deleteChapter" modelAttribute="What is here?">
<form:hidden path = "chapter" value ="${info.chapter}"/>
<input type="submit" value="Delete Chapter ${info.chapter}" />
</form:form>

控制器:

@RequestMapping("/insertChapter")
public String insertChapter(@ModelAttribute Chapter chapter) {
    if (chapter != null)
        infoService.insertChapter(chapter.getChapter(), chapter.getChapter());
        return "redirect:/getInfoListList";
}
@RequestMapping("/deleteChapter")
public String deleteChapter(@RequestParam String chapter) {
    infoService.deleteChapter(chapter);
    return "redirect:/getInfoListList";
}

但服务器抱怨:

在第 62 行处理 JSP 页面时发生异常

Neither BindingResult nor plain target object for bean name 'chapter' available as request attribute

然后

Bean 名称“command”的 BindingResult 和普通目标对象都不是 可用作请求属性

问题/答案

那么设置隐藏字段值的正确方法是什么?我的控制器需要知道该值并且该值不是恒定的,因为我有不同形式的不同值。

我需要做什么才能让章节自动传送到控制器?

什么时候使用 form:input 什么时候使用 just input?我有时看到网上的例子只是使用&lt;input ...&gt;而不是&lt;form:input&gt;

答案:

看来我应该在生成第一页的控制器中使用 ModelAttribute(除了用于处理帖子的页面)。

其他问题

那么就来了第二个问题,如何让控制器处理一个String ModelAttribute,如何设置let Chapter和String处理?下面的功能够吗?

@RequestMapping("/getInfoListList")
public ModelAndView getInfoListList(@ModelAttribute Chapter chapter, @ModelAttribute String chaptertobedeleted) {
    List<List<Info>> infoList = infoService.getInfoListList();
    ModelAndView aModel =new ModelAndView("infoListList", "infoListList", infoList);
    return aModel;
}

【问题讨论】:

  • 应该不止于此。您在哪里看到该错误?
  • 感谢您的指出。该错误表明 Bean 名称“Chapter”的 BindingResult 和普通目标对象都不能用作请求属性。我想我会调查一下
  • 是的,关于该问题有多个问题/答案。您只是没有在 this 请求中提供名为 Chapter 的请求/模型属性。
  • 您不会将@ModelAttribute 用于String,而只是使用@RequestParam。我建议删除这个问题并提出一个新问题,并提供回答所需的所有详细信息。
  • 那里有很多例子。以this 为例。在 Stack Overflow 或其他地方搜索。 Spring 的文档非常详细。

标签: java forms spring-mvc hidden-field


【解决方案1】:

有多个问题。

控制器中指定的 commandName 是什么。 是infoinfochapter 属性吗。

如果infocommandName,请尝试使用它

<form:form method="post" action="/insertChapter" commandName="info">

【讨论】:

  • 章节有字符串章节,标题所以这是一个坏主意,该字段与除大小写外的类型相同。
  • 信息来自另一个 ModelView。此处未显示的另一个 jsp 使用 info 以传递到 /insertChapter 的形式生成 ModelAttribute Chapter 中的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
相关资源
最近更新 更多