Java Code Examples for org.springframework.validation.annotation.Validated

The following examples show how to use org.springframework.validation.annotation.Validated. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: frpMgr   Author: Zo3i   File: FrpFileController.java    License: MIT License 6 votes vote down vote up
/**
 * 保存frp
 */
@RequiresPermissions("frp:frp:edit")
@PostMapping(value = "save")
@ResponseBody
public String save(@Validated Frp frp) {
	// 类型
	frp.setType(ClientType.FILE.value);
	//判断是否存在项目名称,二级域名,远程端口一样的;
	Frp isExist = frpService.isExist(frp.getProjectName(), frp.getFrpDomainSecond(), String.valueOf(frp.getServerId()), frp.getFrpRemotePort());
	if (isExist == null) {
		frp.setUserId(UserUtils.getUser().getId());
		frpService.save(frp);
	} else {
		return renderResult(Global.TRUE, text("项目名、二级域名冲突或远程端口冲突!"));
	}
	return renderResult(Global.TRUE, text("保存frp成功!"));
}
 
Example #2
Source Project: yshopmall   Author: guchengwuyue   File: StoreSeckillController.java    License: Apache License 2.0 6 votes vote down vote up
@Log("发布")
@ApiOperation(value = "发布")
@PutMapping(value = "/yxStoreSeckill")
@PreAuthorize("@el.check('admin','YXSTORESECKILL_ALL','YXSTORESECKILL_EDIT')")
public ResponseEntity update(@Validated @RequestBody YxStoreSeckill resources){
    if(ObjectUtil.isNotNull(resources.getStartTimeDate())){
        resources.setStartTime(OrderUtil.
                dateToTimestamp(resources.getStartTimeDate()));
    }
    if(ObjectUtil.isNotNull(resources.getEndTimeDate())){
        resources.setStopTime(OrderUtil.
                dateToTimestamp(resources.getEndTimeDate()));
    }
    if(ObjectUtil.isNull(resources.getId())){
        resources.setAddTime(String.valueOf(OrderUtil.getSecondTimestampTwo()));
        return new ResponseEntity(yxStoreSeckillService.save(resources),HttpStatus.CREATED);
    }else{
        yxStoreSeckillService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
}
 
Example #3
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: AdminFacultyFormController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute("facultyForm") FacultyForm facultyForm, BindingResult bindingResult){
	model.addAttribute("facultyForm", facultyForm);
	
	RedirectView redirectView = new RedirectView();
	redirectView.setContextRelative(true);
	redirectView.setUrl("/smp/admin_add_faculty.html");
	
	List<Tblfaculty> faculty = reportService.getAllFaculty();
	model.addAttribute("faculty", faculty);
	
    references(model);
    
	if(bindingResult.hasErrors()) {
		facultyForm = new FacultyForm();
		model.addAttribute("facultyForm", facultyForm);
		
	} else{
		managementService.addFaculty(facultyForm);
		facultyForm = new FacultyForm();
		model.addAttribute("facultyForm", facultyForm);
		
	}
	return redirectView;
}
 
Example #4
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: AdminDepartmentFromController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute("deptForm") DepartmentForm deptForm, BindingResult bindingResult){
	model.addAttribute("deptForm", deptForm);
	
	RedirectView redirectView = new RedirectView();
	redirectView.setContextRelative(true);
	redirectView.setUrl("/smp/admin_add_department.html");
	
	List<Tbldepartment> depts = reportService.getAllDepartment();
    model.addAttribute("depts", depts);
	
  
    
	if(bindingResult.hasErrors()) {
		deptForm = new DepartmentForm();
		model.addAttribute("deptForm", deptForm);
		
	} else{
		managementService.addDepartment(deptForm);
		deptForm = new DepartmentForm();
		model.addAttribute("deptForm", deptForm);
		
	}
	return redirectView;
}
 
Example #5
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: AdminLoginController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute LoginForm adminLoginForm, BindingResult bindingResult){
	model.addAttribute("adminLoginForm", adminLoginForm);
	RedirectView redirectView = new RedirectView();
	redirectView.setContextRelative(true);
	
	if(bindingResult.hasErrors()) {
		adminLoginForm = new LoginForm();
		redirectView.setUrl("/smp/admin_login.html");
		model.addAttribute("adminLoginForm", adminLoginForm);
	} else{
		Login login = new Login();
		login.setUserName(adminLoginForm.getUsername());
		login.setPassWord(adminLoginForm.getPassword());
		if(loginService.isAdminUser(login.getUserName(), login.getPassWord())){
			redirectView.setUrl("/smp/admin_pending.html");
		}else{
			adminLoginForm = new LoginForm();
			redirectView.setUrl("/smp/admin_login.html");
		}
	}
	return redirectView;
}
 
Example #6
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: AdminCourseFormController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute("courseForm") CourseForm courseForm, BindingResult bindingResult){
	model.addAttribute("courseForm", courseForm);
	
	RedirectView redirectView = new RedirectView();
	redirectView.setContextRelative(true);
	redirectView.setUrl("/smp/admin_add_course.html");
	
	List<Tblcourses> courses = reportService.getAllCourses();
	model.addAttribute("courses", courses);
	
    references(model);
    
	if(bindingResult.hasErrors()) {
		courseForm =  new CourseForm();
		model.addAttribute("courseForm", courseForm);
		
	} else{
		managementService.addCourse(courseForm);
		courseForm =  new CourseForm();	
		model.addAttribute("courseForm", courseForm);
		
	}
	return redirectView;
}
 
Example #7
Source Project: yshopmall   Author: guchengwuyue   File: StoreOrderController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "退款")
@PostMapping(value = "/yxStoreOrder/refund")
@PreAuthorize("@el.check('admin','YXSTOREORDER_ALL','YXSTOREORDER_EDIT')")
public ResponseEntity refund(@Validated @RequestBody YxStoreOrder resources) {
    yxStoreOrderService.refund(resources);

    //模板消息通知
    try {
        YxWechatUserDto wechatUser = generator.convert(wechatUserService.getOne(new QueryWrapper<YxWechatUser>().eq("uid",resources.getUid())),YxWechatUserDto.class);
        if (ObjectUtil.isNotNull(wechatUser)) {
            //公众号与小程序打通统一公众号模板通知
            if (StrUtil.isNotBlank(wechatUser.getOpenid())) {
                templateService.refundSuccessNotice(resources.getOrderId(),
                        resources.getPayPrice().toString(),wechatUser.getOpenid(),
                        OrderUtil.stampToDate(resources.getAddTime().toString()));
            }
        }
    } catch (Exception e) {
        log.info("当前用户不是微信用户不能发送模板消息哦!");
    }


    return new ResponseEntity(HttpStatus.NO_CONTENT);
}
 
Example #8
Source Project: batch-scheduler   Author: hzwy23   File: TaskDefineController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.update(parse(request));
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
Example #9
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: AdminLoginController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute LoginForm adminLoginForm, BindingResult bindingResult){
	model.addAttribute("adminLoginForm", adminLoginForm);
	RedirectView redirectView = new RedirectView();
	redirectView.setContextRelative(true);
	
	if(bindingResult.hasErrors()) {
		adminLoginForm = new LoginForm();
		redirectView.setUrl("/smp/admin_login.html");
		model.addAttribute("adminLoginForm", adminLoginForm);
	} else{
		Login login = new Login();
		login.setUserName(adminLoginForm.getUsername());
		login.setPassWord(adminLoginForm.getPassword());
		if(loginService.isAdminUser(login)){
			redirectView.setUrl("/smp/admin_pending.html");
		}else{
			adminLoginForm = new LoginForm();
			redirectView.setUrl("/smp/admin_login.html");
		}
	}
	return redirectView;
}
 
Example #10
Source Project: lams   Author: lamsfoundation   File: MethodValidationInterceptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine the validation groups to validate against for the given method invocation.
 * <p>Default are the validation groups as specified in the {@link Validated} annotation
 * on the containing target class of the method.
 * @param invocation the current MethodInvocation
 * @return the applicable validation groups as a Class array
 */
protected Class<?>[] determineValidationGroups(MethodInvocation invocation) {
	Validated validatedAnn = AnnotationUtils.findAnnotation(invocation.getMethod(), Validated.class);
	if (validatedAnn == null) {
		validatedAnn = AnnotationUtils.findAnnotation(invocation.getThis().getClass(), Validated.class);
	}
	return (validatedAnn != null ? validatedAnn.value() : new Class<?>[0]);
}
 
Example #11
Source Project: das   Author: ppdaicorp   File: ServerConfigController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public ServiceResult<String> delete(@Validated(DeleteServerConfig.class) @RequestBody ServerConfig serverConfig, @CurrentUser LoginUser user, Errors errors) throws Exception {
    ValidateResult validateRes = serverConfigService.validatePermision(user, errors)
            .addAssert(() -> serverConfigDao.deleteServerAppConfig(serverConfig) > 0, message.db_message_delete_operation_failed).validate();
    if (!validateRes.isValid()) {
        return ServiceResult.fail(validateRes.getSummarize());
    }
    return ServiceResult.success("阿波罗配置请自行删除!!");
}
 
Example #12
Source Project: Spring-MVC-Blueprints   Author: PacktPublishing   File: PersonalUpdateController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(method=RequestMethod.POST)
public String submitForm(Model model, @ModelAttribute("personForm") @Validated Personal personForm, BindingResult binding){
	model.addAttribute("personForm", personForm);
   	String returnVal = "personal";
	if(binding.hasErrors()) {
		references(model);
		returnVal = "personal_update";
	} else{
		model.addAttribute("personSess", personForm);
		model.addAttribute("pStatusSess", "undefault");
	}
	return returnVal;
   	
}
 
Example #13
Source Project: mall   Author: macrozheng   File: PmsProductCategoryController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation("添加产品分类")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@Validated @RequestBody PmsProductCategoryParam productCategoryParam,
                     BindingResult result) {
    int count = productCategoryService.create(productCategoryParam);
    if (count > 0) {
        return CommonResult.success(count);
    } else {
        return CommonResult.failed();
    }
}
 
Example #14
Source Project: AthenaServing   Author: xfyun   File: ServiceDiscoveryController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 新增版本
 *
 * @param body
 * @param result
 * @return
 */
@RequestMapping(value = "/addApiVersion", method = RequestMethod.POST)
public Response<ServiceApiVersionDetailResponseBody> add(@Validated @RequestBody AddServiceApiVersionRequestBody body, BindingResult result) {
    if (result.hasErrors()) {
        return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, result.getFieldError().getDefaultMessage());
    }
    return this.serviceApiVersionImpl.add(body);
}
 
Example #15
Source Project: eladmin   Author: elunez   File: DatabaseController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("新增数据库")
   @ApiOperation(value = "新增数据库")
   @PostMapping
@PreAuthorize("@el.check('database:add')")
   public ResponseEntity<Object> create(@Validated @RequestBody Database resources){
	databaseService.create(resources);
       return new ResponseEntity<>(HttpStatus.CREATED);
   }
 
Example #16
Source Project: watchdog-framework   Author: watchdog-framework   File: UserController.java    License: MIT License 5 votes vote down vote up
@PostMapping(value = {"/reset-password"})
@ApiOperation(value = "重置密码")
@SysLogs("重置密码")
@ApiImplicitParam(paramType = "header",name = "Authorization",value = "身份认证Token")
public ResponseResult resetPassword(@RequestBody
                                       @Validated @ApiParam(value = "用户及密码数据") ResetPasswordDTO dto){
    userService.resetPassword(dto);
    return ResponseResult.e(ResponseCode.OK);
}
 
Example #17
Source Project: seezoon-framework-all   Author: 734839030   File: SysDeptController.java    License: Apache License 2.0 5 votes vote down vote up
@RequiresPermissions("sys:dept:save")
@PostMapping("/save.do")
public ResponeModel save(@Validated SysDept sysDept, BindingResult bindingResult) {
	SysDept parent = null;
	if (StringUtils.isNotEmpty(sysDept.getParentId())) {
		parent = sysDeptService.findById(sysDept.getParentId());
	} 
	treeHelper.setParent(sysDept, parent);
	int cnt = sysDeptService.save(sysDept);
	return ResponeModel.ok(cnt);
}
 
Example #18
Source Project: cola-cloud   Author: leecho   File: DictController.java    License: MIT License 5 votes vote down vote up
/**
 * 修改数据字典目录
 */
@PostMapping(value = "/update")
@ApiOperation("修改数据字典目录")
public Result<String> update(@Validated Dict dict) {
    dictService.updateById(dict);
    return this.success();
}
 
Example #19
Source Project: spring-boot-plus   Author: geekidea   File: SysDepartmentController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 部门分页列表
 */
@PostMapping("/getPageList")
@RequiresPermissions("sys:department:page")
@OperationLog(name = "部门分页列表", type = OperationLogType.PAGE)
@ApiOperation(value = "部门分页列表", response = SysDepartmentQueryVo.class)
public ApiResult<Paging<SysDepartmentQueryVo>> getSysDepartmentPageList(@Validated @RequestBody SysDepartmentPageParam sysDepartmentPageParam) throws Exception {
    Paging<SysDepartmentQueryVo> paging = sysDepartmentService.getSysDepartmentPageList(sysDepartmentPageParam);
    return ApiResult.ok(paging);
}
 
Example #20
Source Project: supplierShop   Author: guchengwuyue   File: SysJobController.java    License: MIT License 5 votes vote down vote up
/**
 * 新增保存调度
 */
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@RequiresPermissions("monitor:job:add")
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@Validated SysJob job) throws SchedulerException, TaskException
{
    return toAjax(jobService.insertJob(job));
}
 
Example #21
Source Project: yshopmall   Author: guchengwuyue   File: MaterialController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping
@Log("新增素材管理")
@ApiOperation("新增素材管理")
public ResponseEntity<Object> create(@Validated @RequestBody YxMaterial resources){
    resources.setCreateId(SecurityUtils.getUsername());
    return new ResponseEntity<>(yxMaterialService.save(resources),HttpStatus.CREATED);
}
 
Example #22
Source Project: java-master   Author: jufeng98   File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建用户
 */
@Secured("ROLE_ADMIN")
@PostMapping("/createUser")
@AopLock(lockKeySpEL = "#reqVo.username", errorMsg = "用户名已被占用,请重新输入")
public Result<SysUser> createUser(@Validated @RequestBody CreateUserReqVo reqVo) {
    return new Result<>(userService.createUser(reqVo));
}
 
Example #23
Source Project: das   Author: ppdaicorp   File: GroupController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 删除组
 */
@RequestMapping(value = {"", "/", "/delete"}, method = RequestMethod.DELETE)
public ServiceResult<String> delete(@Validated(DeleteGroup.class) @RequestBody DasGroup group, @CurrentUser LoginUser user, Errors errors) throws Exception {
    Long groupId = group.getId();
    ValidateResult validateRes = groupService.validatePermision(user, errors)
            .addAssert(() -> CollectionUtils.isEmpty(projectDao.getProjectByGroupId(groupId)), "当前DAS Team中还有Project,请清空Project后再操作!")
            .addAssert(() -> CollectionUtils.isEmpty(dataBaseDao.getGroupDBsByGroup(groupId)), "当前DAS Team中还有DataBase,请清空DataBase后再操作!")
            .addAssert(() -> CollectionUtils.isEmpty(databaseSetDao.getAllDatabaseSetByGroupId(groupId)), "当前DAL Team中还有DataBaseSet,请清空DataBaseSet后再操作!")
            .addAssert(() -> CollectionUtils.isEmpty(loginUserDao.getUserByGroupId(groupId)), "当前DAS Team中还有Member,请清空Member后再操作!")
            .addAssert(() -> groupDao.deleteDalGroup(groupId) > 0, message.db_message_delete_operation_failed).validate();
    if (!validateRes.isValid()) {
        return ServiceResult.fail(validateRes.getSummarize());
    }
    return ServiceResult.success();
}
 
Example #24
Source Project: AthenaServing   Author: xfyun   File: ServiceVersionController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询最近的版本列表
 *
 * @param body
 * @param result
 * @return
 */
@RequestMapping(value = "/lastestList", method = RequestMethod.GET)
public Response<QueryPagingListResponseBody> lastestList(@Validated QueryServiceVersionRequestBody body, BindingResult result) {
    if (result.hasErrors()) {
        return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, result.getFieldError().getDefaultMessage());
    }
    return this.serviceVersionImpl.findLastestList(body);
}
 
Example #25
Source Project: spring-boot-doma2-sample   Author: miyabayt   File: CodeCategoryHtmlController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 検索結果
 *
 * @param form
 * @param br
 * @param attributes
 * @return
 */
@PostMapping("/find")
public String findCodeCategory(@Validated @ModelAttribute("searchCodeCategoryForm") SearchCodeCategoryForm form,
        BindingResult br, RedirectAttributes attributes) {
    // 入力チェックエラーがある場合は、元の画面にもどる
    if (br.hasErrors()) {
        setFlashAttributeErrors(attributes, br);
        return "redirect:/system/code_categories/find";
    }

    return "redirect:/system/code_categories/find";
}
 
Example #26
Source Project: flow-platform-x   Author: FlowCI   File: JobController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/rerun")
@Action(JobAction.RUN)
public void rerun(@Validated @RequestBody RerunJob body) {
    Job job = jobService.get(body.getJobId());
    Flow flow = flowService.getById(job.getFlowId());
    jobService.rerun(flow, job);
}
 
Example #27
Source Project: yshopmall   Author: guchengwuyue   File: SysUserController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("修改用户:个人中心")
@ApiOperation("修改用户:个人中心")
@PutMapping(value = "center")
public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources){

    UserDto userDto = userService.findByName(SecurityUtils.getUsername());
    if(!resources.getId().equals(userDto.getId())){
        throw new BadRequestException("不能修改他人资料");
    }
    userService.saveOrUpdate(resources);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example #28
Source Project: sk-admin   Author: DengSinkiang   File: EmailController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("发送邮件")
@PostMapping
@ApiOperation("发送邮件")
public ResponseEntity<Object> send(@Validated @RequestBody EmailVo emailVo) throws Exception {
    emailService.send(emailVo, emailService.find());
    return new ResponseEntity<>(HttpStatus.OK);
}
 
Example #29
Source Project: das   Author: ppdaicorp   File: DatabaseController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 同步数据到db
 */
@RequestMapping(value = "/syncdb")
public ServiceResult<String> syncdb(@Validated(AddDataBase.class) @RequestBody DataBaseInfo dataBaseInfo, @CurrentUser LoginUser user, Errors errors) throws Exception {
    DasGroup dasGroup = groupDao.getGroupByName(dataBaseInfo.getGroup_name());
    if (dasGroup == null) {
        return ServiceResult.fail("请先同步组!" + dataBaseInfo.getGroup_name());
    }
    dataBaseInfo.setDal_group_id(dasGroup.getId());
    return addDataBase(dataBaseInfo, user, errors);
}
 
Example #30
Source Project: staffjoy   Author: spring2go   File: CompanyController.java    License: MIT License 5 votes vote down vote up
@PutMapping(path= "/update")
@Authorize(value = {
        AuthConstant.AUTHORIZATION_AUTHENTICATED_USER,
        AuthConstant.AUTHORIZATION_SUPPORT_USER
})
public GenericCompanyResponse updateCompany(@RequestBody @Validated({Group1.class}) CompanyDto companyDto) {
    if (AuthConstant.AUTHORIZATION_AUTHENTICATED_USER.equals(AuthContext.getAuthz())) {
        permissionService.checkPermissionCompanyAdmin(companyDto.getId());
    }
    CompanyDto updatedCompanyDto = companyService.updateCompany(companyDto);
    return new GenericCompanyResponse(updatedCompanyDto);
}