在Spring

时间:2016-06-16 05:46:59

标签: java spring rest validation spring-mvc

在发布此问题之前,我做了很多研究并尝试了很多解决方案。

这是我陷入困境的棘手情况。

我有一个Spring控制器,它有多个请求映射,它们都有@PathVariables

这是Controller的样子:

@Controller
@EnableWebMvc
public class ChildController extends ParentController<InterfaceController> implements InterfaceController{

    @Override
    @RequestMapping(value = "/map/{name}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody   
    public List<Friends> getAllFriendsByName(
        @PathVariable("name") String name,
        @RequestParam(value="pageSize", required=false) String pageSize,
        @RequestParam(value="pageNumber", required=false) String pageNumber,            
        HttpServletRequest request) throws BasicException {

    //Some logic over here;

    return results;
    }

@Override
    @RequestMapping(value = "/map/{id}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody   
    public List<Friends> getAllFriendsById(
        @PathVariable("id") String id,
        @RequestParam(value="pageSize", required=false) String pageSize,
        @RequestParam(value="pageNumber", required=false) String pageNumber,            
        HttpServletRequest request) throws BasicException {

    //Some logic over here;

    return results;
    }

}

现在我最近了解到你无法在Spring中验证路径变量,与我尝试的这些示例相反,它发现它不起作用 (试过的例子:@PathVariable Validation in Spring 4

所以我想到为我的路径变量添加一个自定义JSR303约束验证并创建我自己的东西,如

 import static java.lang.annotation.ElementType.TYPE;
 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 import java.lang.annotation.Documented;
 import java.lang.annotation.Retention;
 import java.lang.annotation.Target;
 import javax.validation.Constraint;
 import javax.validation.Payload;

 @Target({ TYPE})
 @Retention(RUNTIME)
 @Constraint(validatedBy = PathVariableValidator.class)
 @Documented
 public @interface RequestValidationNeeded {

String id();

String name();

Class<?>[] constraints() default {};

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

String message() default "totally wrong, dude!";

 }

这不是我最初的想法,它受到了这篇文章的启发 http://techblogs4u.blogspot.ca/2012/09/method-parameter-validation-in-spring-3.html

我无法弄清楚我是如何将@RequestValidationNeeded注释映射到PathVriables,即idname并调用相同的验证器并根据调用验证器的字段调用适当的验证。

我不喜欢这种方式,但我的选择已经用尽了,这是我能想到的最后一件事可能有用但是即便如此我需要找出一种方法来注释具有相同注释的两个路径变量并调用相同的方法验证器。

我很感激对此有任何帮助或指导。

我根据我的尝试发布的其他一些问题可能会帮助您更好地了解我尝试过哪些验证。

P.S。我发布链接而不是代码只是为了让问题简短。

链接: How to make customEditor in Spring dynamic enough to call validation on appropriate methods

Spring REST Service Controller not being validate by @PathVariable and @Valid

0 个答案:

没有答案