controller注解使用 resultful

可以使用正则

@PutMapping("/{id:\\d+}")
status().is4xxClientError() 参数异常

JsonView

public class User {
	public interface UserSimpleView {};
	public interface UserDetailView extends UserSimpleView {};
	
	@JsonView(UserSimpleView.class) //简单视图 显示用户名
	public String getUsername() {
	@JsonView(UserDetailView.class) //细节显示密码
	public String getPassword() {

此外 在 controller接口上,也需要加入
	@GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getInfo(@ApiParam("用户id") @PathVariable String id) {

日期处理 传递时间戳

	@Test
	public void whenUpdateSuccess() throws Exception {
		
		Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
		System.out.println(date.getTime());
		String content = "{\"id\":\"1\", \"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
		String reuslt = 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(reuslt);
	}
	@PutMapping("/{id:\\d+}")
	public User update(@Valid @RequestBody User user, BindingResult errors) {
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday()); //打印出来是 英文的年月日

		user.setId("1");
		return user; //返回给前台,依然是时间戳
	}

分页

	@RequestMapping
	public List<User> query(@PageableDefault(size = 15,page = 3,sort = {"age,desc"}) Pageable pageable){
		//参数传递:size "15"
		//page "3"
		//sort "age,desc"
		System.out.println(pageable.getPageSize());
		System.out.println(pageable.getPageNumber());
		System.out.println(pageable.getSort());
		return null;
	}
	@Test
	public void whenQuerySuccess() throws Exception {
		String result = mockMvc.perform(
				get("/user").param("username", "jojo").param("age", "18").param("ageTo", "60").param("xxx", "yyy")
						// .param("size", "15")
						// .param("page", "3")
						// .param("sort", "age,desc")
						.contentType(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk()).andExpect(jsonPath("$.length()").value(3))
				.andReturn().getResponse().getContentAsString();
		
		System.out.println(result);
	}

Hibernate Validator

在这里插入图片描述

在这里插入图片描述

	@NotBlank(message = "密码不能为空")
	private String password;
	@Past(message = "生日必须是过去的时间")
	private Date birthday;
    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(
                    error -> {
                        FieldError fieldError = (FieldError) error;
                        System.out.println(fieldError.getField()+":::"+fieldError.getDefaultMessage());
                        System.out.println(error.getDefaultMessage());
                    }
            );
        }

自定义注解校验逻辑

注解

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
	String message();
	Class<?>[] groups() default { };
	Class<? extends Payload>[] payload() default { };
	String field() default "";
}

实现

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
	@Autowired
	private HelloService helloService;
	@Override
	public void initialize(MyConstraint constraintAnnotation) {
		System.out.println("my validator init");
	}
	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		helloService.greeting("tom");
		System.out.println(value);
		return true;
	}
}
	@MyConstraint(message = "这是一个测试")
	private String username;

错误全局页面

在这里插入图片描述

自定义异常处理

@ControllerAdvice
public class ControllerExceptionHandler {

	@ExceptionHandler(UserNotExistException.class) //自己的异常
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}

}
public class UserNotExistException extends RuntimeException {
	private static final long serialVersionUID = -6112780192479692859L;
	private String id; //提供get set
	public UserNotExistException(String id) {
		super("user not exist");
		this.id = id;
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Controller注解是Spring MVC框架中用于标识控制器的注解使用@Controller注解可以将一个POJO对象标识为控制器,用于处理客户端的请求。下面是@Controller注解使用步骤: 1. 在Spring配置文件中配置组件扫描,让Spring自动扫描@Controller注解。 2. 创建一个POJO对象,并在其类声明上添加@Controller注解。 3. 在该对象中添加一个或多个处理请求的方法,并在方法上添加@RequestMapping注解,指定处理请求的URL路径。 4. 在处理请求的方法中添加业务逻辑代码,如数据查询、数据修改等。 下面是一个简单的示例,演示如何使用@Controller注解: ```java @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/list") public ModelAndView listUsers() { List<User> users = userService.listUsers(); ModelAndView modelAndView = new ModelAndView("user/list"); modelAndView.addObject("users", users); return modelAndView; } // 其他方法省略... } ``` 在上述示例中,UserController是一个控制器,使用@Controller注解标识。其中,@RequestMapping注解用于指定处理请求的URL路径。listUsers()方法用于处理/list请求,查询所有用户数据并返回一个包含用户数据的ModelAndView对象。在Spring配置文件中还需要配置ViewResolver,将ModelAndView对象渲染为HTML视图。 总之,使用@Controller注解创建控制器非常简单,只需要添加@Controller和@RequestMapping注解,并编写处理请求的方法即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值