HTTP状态码400 - 必需的字符串参数'xx'不存在。

4
我将会翻译这段内容为:

我正在尝试制作一个简单的Spring MVC应用程序。

以下是我的HelloController

package com.springapp.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model,@RequestParam(value = "xx",required
=true)String xx) {

        model.addAttribute("message", "Hello Mahdi");

    return "hello";
}
}

JSP文件:

<html>
<body>
<h1>${message}</h1>
<form action="/" method="GET">
    <input type="text" name="xx">
    <button type="submit">submit</button>
</form>
</body>
</html>

当我尝试运行应用程序时,出现了以下错误:

HTTP Status 400 - Required String parameter 'xx' is not present

我是Spring MVC的新手,请帮忙。


您是否在文本框中输入了文本? - Sotirios Delimanolis
在加载 JSP 页面之前,我收到了该错误消息。 - Super Hornet
你为什么将请求映射到控制器的 / 路径?你是如何访问 JSP 的? - AllTooSir
你需要一个控制器方法来加载包含表单的页面,另一个控制器方法来处理表单提交。 - Sotirios Delimanolis
没有特别的原因,顺便说一下,如果没有"@RequestParam(value = "xx",required=true)String xx",一切都正常工作,我可以看到页面。 - Super Hornet
如果 required="false",也应该能够正常工作。 - Roman C
1个回答

7

您的使用场景需要执行两个操作:

  1. 查看和编辑 <form>
  2. 提交 <form>

这应该映射到两个处理程序方法。

@RequestMapping(method = RequestMethod.GET)
public String getForm() {

    model.addAttribute("message", "Hello Mahdi");
    return "hello"; // assume hello.jsp
}

@RequestMapping(params={"submit"}, method = RequestMethod.GET)
public String printWelcome(ModelMap model, @RequestParam(value = "xx",required=true) String xx) {

    /*
     Do something with submitted parameter
     and return some view name
    */
}

当您想访问表单时,可以通过GET请求/。当您提交表单时,也可以使用GET请求/,但需要其他方式来区分请求。在这里,我使用了params="submit"。因此,您需要将提交输入更改为:

<input type="submit" name="submit">submit</button>

或者只需使用您已经在使用的参数 (params={"xx"})。


1
我在这里显然做出了假设,请解释正在发生的事情。 - Sotirios Delimanolis
我遇到了这个错误:所请求的资源不可用。HTTP 404- - Super Hornet
当您向 / 发出 GET 请求时,是否会发生这种情况?您是否有一个名为 hello.jsp 的 jsp 文件,并且它在您的 ViewResolver 中进行了映射? - Sotirios Delimanolis
很高兴听到这个消息,@RequestMapping 属性的 Javadoc 非常有用。祝你好运! - Sotirios Delimanolis
我只是忘记在@RequestMapping中声明params{"xx"}了! - Super Hornet
我忘记在@RequestParam(value = "xx",required=true)中将required设置为false了,这个参数对我的解决方案有所帮助,谢谢。 - André Luís Tomaz Dionisio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接