如何根据需要标记Spring MVC参数

时间:2014-11-27 09:22:21

标签: spring spring-mvc spring-validator

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

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

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

我该怎么做?这个或类似的东西有没有注释?

由于

4 个答案:

答案 0 :(得分:5)

是的,有。 @RequestParam(required=true)请参阅docs

默认情况下,必需标志为true,因此您需要做的只是:

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

答案 1 :(得分: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
 }

答案 2 :(得分:2)

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

@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

答案 3 :(得分: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

}

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