【问题标题】:HttpServletRequest in spring getting parameters values as null for post requestSpring中的HttpServletRequest为发布请求获取参数值为null
【发布时间】:2017-03-11 09:12:24
【问题描述】:
@ResponseBody

@RequestMapping(value = {"apiRequest"}, method = {RequestMethod.POST})

public String contestApiSignUp(HttpServletRequest req) throws JSONException {
try {
    String username = req.getParameter("username");
    String firstname = req.getParameter("firstname");
    String lastname = req.getParameter("lastname");
    String password = req.getParameter("password");
    String phone = req.getParameter("phone");

这里我得到的值都是空的。那就是用户名=null,名字=null...

我正在使用这些值发送帖子请求 http://localhost:8080/apiRequest.htm

username = Subhajit
firstname = Subha
...

像这样。

但是当我使用相同的代码时,

@RequestMapping(value = {"apiRequest"}, method = {RequestMethod.GET})

使用 GET 而不是 POST 然后我得到正确的值。

【问题讨论】:

  • 你能用标题显示你的确切发布请求吗

标签: spring post request-mapping


【解决方案1】:

当您通过 POST 将 HTML 表单发送到您的 URL /apiRequest 时,您是否在表单中的字段中填写了您的数据(用户名、名字等),或者您是否将它们附加到发送的 URL(例如apiRequest.htm?username=test&... ) ?

因为使用第二种方法,您的数据只能通过 GET 请求而不是 POST 访问。第一种方法适用于 POST 请求。

另外,您不需要在 Spring Controller 中显式调用 HttpServletRequest 上的 getParameter。

你可以这样做:

@ResponseBody
@RequestMapping (value = "apiRequest", method = RequestMethod.POST)
public String contestApiSignUp(
        @RequestParam ("username") String username,
        @RequestParam ("firstname") String firstname,
        @RequestParam ("lastname") String lastname,
        @RequestParam ("password") String password,
        @RequestParam ("phone") String phone) {
    return "Hello World";
}

【讨论】:

  • 非常感谢您的回复。 " apiRequest.htm?username=test& " 我不会像这样发布数据。我正在使用邮递员将参数设置为标题及其值。
  • 好的,我从没用过邮递员,但它应该像其他 API 请求工具一样工作。您不应尝试在请求的标头中传递任意键/值对。这些标头用于请求的元数据,而不是数据。要在 POST 请求中传递数据,您必须构建一个包含这些键/值对的请求正文。检查邮递员的文档,您可以使用类似表单的界面进行操作。请参阅getpostman.com/docs/requests,请求正文 > 表单数据部分。
【解决方案2】:

来自 cmets,您说您正在尝试使用邮递员发布请求,那么您是在构建网站还是 Web 服务? 无论哪种方式,您都不应该在标题中发送数据。

  • 如果您正在构建一个网站,则将一个 HTML 文件放在一起 您可以向此控制器提交表单
  • 如果您正在构建 web 服务,请更改控制器并让它 接受 JSON(或 XML - 不过我不鼓励这样做)正文。跟随 这个https://stackoverflow.com/a/40226580/6785908。然后从 邮递员(或 curl),请改为发布 json。

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2017-03-21
    • 2017-08-24
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多