5

我在弹簧控制器中有这样的方法

@RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
@ResponseBody
public void updateArticle(Long id,  String name, String description) {
  ...
}

我想要 id 和 name 是必需的。换句话说,如果它们是空值,则必须抛出异常。

我怎样才能做到这一点?是否有任何注释或类似的东西?

谢谢

4

4 回答 4

7

就在这里。@RequestParam(required=true)请参阅文档

默认情况下, required 标志甚至为 true,因此您需要做的就是:

@RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
@ResponseBody
public void updateArticle(@RequestParam Long id, @RequestParam String name, @RequestParam String description) {
  ...
}
于 2014-11-27T09:25:20.680 回答
6

您必须在控制器中添加 RequestParam 和所需的 true 注释

@RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
@ResponseBody
public void updateArticle(@RequestParam(value="id",required=true) long id,@RequestParam(value="name",required=true)  String name, @RequestParam(value="description",required=true) String description) {
  ...
}

当您从浏览器中点击此控制器 URL 时,如果其中一个参数是任务,那么您将进入incorrect syntax error浏览器

于 2014-11-27T09:26:31.103 回答
2
@RequestMapping (value = "/gethomeworkinfo.json", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
public @ResponseBody
HomeworkReport getHomeworkReportInfo(@RequestParam (value = "schoolid", required = false) String schoolId, @RequestParam (value = "homeworkid") String homeworkId,
        @RequestParam (value = "startdate", required = false, defaultValue = "2014-06-01") @DateTimeFormat (pattern = "yyyy-MM-dd") Date startdate,
        @RequestParam (value = "enddate", required = false, defaultValue = "2014-12-30") @DateTimeFormat (pattern = "yyyy-MM-dd") Date enddate,
        @RequestParam (value = "userid", required = false) String userId, HttpServletRequest request) {

    // some actions

}

我目前使用这种方法。它会帮助你。

于 2014-11-27T12:39:05.887 回答
2

我假设您正在将表单传递给此控制器。因此,将所有表单字段转换为 Form 对象,然后您可以对它们使用 Java 验证。因此,例如,您在表单中有 id、name 和 description 字段:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class ArticleForm {

    @NotNull
    private Long id;

    @Size(min = 2, max = 20)
    private String name;

    @Size(min =2, max =20)
    private String description;

    // getters and setters
}

然后,在您的控制器中:

 @RequestMapping(value = "/updateArticle", method = RequestMethod.POST)
 @ResponseBody
 public void updateArticle(@Valid ArticleForm articleForm) {
      // do something with the article form object using getters and this retrieves
      // values sent in the HTTP Form
 }
于 2014-11-27T09:24:28.953 回答