使用案例:
>让我们使用POST HTTP动词设计RESTful创建操作 – 创建票证,其中创建者(分配者)指定票证受让人
>我们在以下位置创建一个新的“票证”:/ companyId / userId / ticket
>我们提供包含assigneeId的票证正文:
{
“assigneeId”:10
}
>我们需要在URL – companyId路径变量中验证assigneeId属于公司
至今:
@RequestMapping(value="/{companyId}/{userId}/ticket",method=POST)
public void createTicket(@Valid @RequestBody Ticket newTicket,@PathVariable Long companyId,@PathVariable Long userId) {
...
}
>我们可以轻松指定自定义Validator(TicketValidator)(甚至包含依赖项)并验证Ticket实例
>我们不能轻易将companyId传递给此验证器!我们需要验证ticket.assigneeId是否属于companyId公司.
期望的输出:
>在自定义验证器中访问路径变量的能力
任何想法如何在这里实现所需的输出?
最佳答案
如果我们假设我们的自定义验证器知道所需的属性名称,那么我们可以这样做:
原文链接:https://www.f2er.com/spring/431781.html方法一:
1)我们可以将这个获取路径变量逻辑移动到某种基本验证器:
public abstract class BaseValidator implements Validator {
@Override
public boolean supports(Class> clazz)
{
// supports logic
}
@Override
public void validate(Object target,Errors errors)
{
// some base validation logic or empty if there isn't any
}
protected String getPathVariable(String name) {
// Getting current request (Can be autowired - depends on your implementation)
HttpServletRequest req = HttpServletRequest((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if (req != null) {
// getting variables map from current request
Map
2)使用TicketValidator实现扩展它:
public class TicketValidator extends BaseValidator {
@Override
public void validate(Object target,Errors errors)
{
// Getting our companyId var
String companyId = getPathVariable("companyId");
...
// proceed with your validation logic. Note,that all path variables
// is `String`,so you're going to have to cast them (you can do
// this in `BaseValidator` though,by passing `Class` to which you
// want to cast it as a method param). You can also get `null` from
// `getPathVariable` method - you might want to handle it too somehow
}
}
方法二:
我认为值得一提的是,你可以使用SpEL的@PreAuthorize注释来进行这种验证(你可以传递路径变量并向它请求体).如果验证通过,你将获得HTTP 403代码,所以我想这不是你想要的exaclty.