如何在spring boot中验证@RequestHeader

时间:2018-04-27 09:21:46

标签: java spring rest validation spring-boot

如果标题丢失或格式错误,如何验证所需的标题?

    @RequestMapping(value = "/example/{id}", method = RequestMethod.PUT)        
    public ResponseEntity<> update(@RequestHeader(value="last-modified-date") String lastModDate, HttpServletRequest request,
                @RequestBody ReBody rebody, @PathVariable("id") int id) throws Exception{
    // Stuff here...
    }

“lastModDate”的格式喜欢“周一,2017年8月28日02:51:09 GMT”

我想对标题属性进行一些自定义验证,即

if (lastModDate == null) {
    throw Exception();
}

或者当格式错误时抛出异常。

4 个答案:

答案 0 :(得分:0)

您已经回答了问题。你可以像下面这样简单地做: -

public ResponseEntity<> update(@RequestHeader(value="last-modified-date") String lastModDate, HttpServletRequest request,
            @RequestBody ReBody rebody, @PathVariable("id") int id) throws Exception{

         if (lastModDate == null) {
         throw Exception();
         }

         // Stuff here...

     }

答案 1 :(得分:0)

只需添加@Valid注释。

@RequestMapping(value = "/example/{id}", method = RequestMethod.PUT)        
public ResponseEntity<> update(@Valid @RequestHeader(value="last-modified-date") String lastModDate, HttpServletRequest request,
            @RequestBody ReBody rebody, @PathVariable("id") int id) throws Exception{
    // Stuff here...
}

但您仍需要手动执行格式验证。或者将您的lastModDate类型从String更改为Date或将其转换为timestamp

答案 2 :(得分:0)

您可以使用@Valid和@Pattern

@RequestMapping(value = "/example/{id}", method = RequestMethod.PUT)        
public ResponseEntity<> update(@RequestHeader(value="last-modified-date", required = true) @Pattern(regexp =  "^\\d{4}-\\d{2}-\\d{2}$") String lastModDate, HttpServletRequest request,
                @RequestBody ReBody rebody, @PathVariable("id") int id) throws Exception{
    // Stuff here...
}

答案 3 :(得分:0)

我使用的更简单的选项是为标头定义一个默认值,因此,如果标头值等于默认值,则会丢失它。已经重写了您的方法。见下文

// -- defaultValue = "missingHeader" --
@RequestMapping(value = "/example/{id}", method = RequestMethod.PUT)        
public ResponseEntity<> update(@RequestHeader(value="last-modified-date", defaultValue = "missingHeader") String lastModDate, HttpServletRequest request,
            @RequestBody ReBody rebody, @PathVariable("id") int id) throws Exception
{
    // --added this---
    if (lastModDate.equals("missingHeader")) // means header is missing
    {
        throw Exception();
    }
}