首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不存在方法POST所需的请求参数。

不存在方法POST所需的请求参数。
EN

Stack Overflow用户
提问于 2021-09-12 11:18:24
回答 1查看 520关注 0票数 0

在Spring应用程序中的POST方法中,我很难用@RequestParam解决问题。我在页面上有一个简单的表单,只有一个参数:

代码语言:javascript
运行
复制
@GetMapping("/")
public String mainPage(Model model){
     return "HelloPage";
}

HelloPage则是:

代码语言:javascript
运行
复制
<div class="form-group col-sm-6">
  <form method="post" enctype="text/plain">
      <div class="form-group">
          <label>
              <input type="text" class="form-control"
                     name="authorname" placeholder="Employee name"
              />
          </label>
      </div>
      <div class="form-group">
          <button type="submit" class="btn btn-primary ml-2">Next</button>
      </div>
  </form>
</div>

我创建了一个POST方法来创建一个新的作者,并将其重定向到另一个页面,在该页面中我要显示作者的名字:

代码语言:javascript
运行
复制
@PostMapping("/")
public String postAuthor(@RequestParam("authorname") String authorname){
  Author author = authorService.saveAuthor(authorname);
  return "redirect:/surveys/" + author.getId();
}

当我在HelloPage上填写表单后单击按钮时,会出现以下错误:

有一个意外的错误(type=Bad请求,status=400)。方法参数类型字符串不存在所需的请求参数'authorname‘方法参数类型字符串不存在org.springframework.web.bind.MissingServletRequestParameterException:必需的请求参数'authorname’

我不明白为什么会发生这种情况,因为POST方法应该能够从表单中获得请求参数!

Author只是一个简单的实体模型:

代码语言:javascript
运行
复制
@Entity
@Table(name = "authors")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String authorname;

    public Author() {}

    public Author(String authorname) {
        this.authorname = authorname;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAuthorname() {
        return authorname;
    }

    public void setAuthorname(String authorname) {
        this.authorname = authorname==null || authorname.isEmpty()? "default user" : authorname;
    }
}

有人能帮我解释一下这里出了什么问题吗?

EN

回答 1

Stack Overflow用户

发布于 2021-09-12 11:59:38

尝试删除enctype="text/plain"。根据https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data

使用文本/纯文本格式的

有效载荷用于人类可读性。它们不能由计算机可靠地解释,因为格式不明确(例如,无法区分值中的文字换行符和值末尾的换行符)。

尽管如此,请尝试以下几点:

代码语言:javascript
运行
复制
<div class="form-group col-sm-6">
  <form method="post">
      <div class="form-group">
          <label>
              <input type="text" class="form-control"
                     name="authorname" placeholder="Employee name"
              />
          </label>
      </div>
      <div class="form-group">
          <button type="submit" class="btn btn-primary ml-2">Next</button>
      </div>
  </form>
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69150919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档