服务层和控制器层的验证?

时间:2017-05-19 03:31:43

标签: spring spring-mvc

是否需要在service图层中进行另一轮输入验证,非业务逻辑?

服务层

@Service
@Transactional
@Validated
public class AppServiceImpl implements AppService {

    public App createApp(@Valid App app) { // is there a need to do @Valid here?
        return appRepository.save(app);
    }
}

控制器层

@RestController
@RequestMapping("/api")
public class AppResource {
    private final AppRepository appRepository;

    private final AppServiceImpl appServiceImpl;

    @Autowired
    public AppResource(AppRepository appRepository, AppServiceImpl appServiceImpl) {
        this.appServiceImpl = appServiceImpl;
        this.appRepository = appRepository;
    }

    /**
     * POST  /apps : Create a new app.
     *
     * @param app the app to create
     * @return the ResponseEntity with status 201 (Created) and with body the new app, or with status 400 (Bad Request) if the app has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/apps")
    @Timed
    public ResponseEntity<App> createApp(@Valid @RequestBody App app) throws URISyntaxException {
        log.debug("REST request to save App : {}", app);
        if (app.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new app cannot already have an ID")).body(null);
        }
        App result = appServiceImpl.createApp(app);
        return ResponseEntity.created(new URI("/api/apps/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }
}

1 个答案:

答案 0 :(得分:0)

简短形式:是的,您必须再次验证。

从设计角度来看,您的类提供了一个公共接口,您通常不知道谁调用该方法。因此,为了确保您的类/方法正常工作,您必须验证输入。

如果使用该类的上下文是众所周知的,并且您“知道”在您跳过附加验证之前已完成验证。在这种情况下,您接受的风险是,如果将来未在控制层中完成验证,或者您添加其他类/用例,则调用可能会失败或产生意外结果。