学习视频教程Spring Security开发REST服务到3-5 修改和删除请求(参数验证注意事项)

对参数进行验证,可以在Model进行验证注解的地方定制提示信息,比如:

    @NotBlank(message = "用户名不能为空")
	private String userName;
	@NotBlank(message = "密码不能为空")
	private String password;
	private String id;
	@Past(message = "生日必须是过去的时间")
	private Date birthday;    

获取一年后的时间的方法:
 

//1年以后的时间
Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());

对于校验时使用BindingResult erros时,有两点需要注意:

1. 有了这个定义,代码会正常执行,所以返回的类型不是4xx,而是200(.isOK());

    @Test
	public void whenUpdateUserCurrent() throws Exception {
		Date currentDate = new Date();
		updateUser(currentDate);
	}
	

	@Test
	public void whenUpdateUserAfterYear() throws Exception {
		//1年以后的时间
		Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
		updateUser(date);
	}
	
	private void updateUser(Date birthday) throws Exception {
		User u = new User();
		u.setUserName("chen123");
		u.setPassword("123456");		
		u.setBirthday(birthday);
		String content = JSONObject.toJSONString(u);
		String result = mockMvc.perform((put("/user/1")).contentType(MediaType.APPLICATION_JSON_UTF8)
				.content(content))
				.andExpect(status().isOk())    //這裡不變
				.andExpect(jsonPath("$.id").value("1"))
				.andReturn().getResponse().getContentAsString();
		System.out.println(result);
	}

2. BindingResult erros 要緊挨着要驗證的參數,否則不起作用,如果把BindingResult erros与路径参数ID换了为在,就不会有验证的输出。

@PutMapping("/user/{id:\\d+}")
	public User updateUser(@Valid @RequestBody User u, BindingResult erros, @PathVariable String id) {
		if (erros.hasErrors()) {
			//如果验证有错误则进行输出
			erros.getAllErrors().stream().forEach(error->{
//				FieldError fieldError = (FieldError) error;
//				String errorMessage = fieldError.getField() + "  " +  error.getDefaultMessage();
				String errorMessage = error.getDefaultMessage();
				System.out.println(errorMessage);
				
			});
		}
		u.setId(id);
		return u;
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值