利用@RequestBody和@ResponseBody处理参数校验

是的,今天继续聊@RequestBody和@ResponseBody。

上次通过@RequestMapping注解了解到了RequestMappingHandlerMapping和RequestMappingHandlerAdaptor。
这两兄弟在处理请求的过程中,RequestMappingHandlerMapping帮忙做了url与方法的具体映射,RequestMappingHandlerAdaptor帮忙做了查找具体的处理程序和查找具体的将返回值处理为一个ModelAndView实例的程序。
今天主要来聊他们两兄弟的其他功能。

写一个简单的接口,用@RequestBody修饰方法参数,然后打断点看调用链。

还是在上篇文章中关注的这一行,现在需要关注的是变量ha,发现他的类型是RequestMappingHandlerAdapter。
在这里插入图片描述
发现这个处理器也是通过mappedHandler确定的。
现在看一下具体逻辑。
在这里插入图片描述
其中的handlerAdapters,则是在Spring容器初始化的过程中填充的。
在这里插入图片描述
以上是RequestMappingHandlerAdapter的加载过程,现在找它的应用代码。
在这里插入图片描述
在invokeHandlerMethod中,会设置两个参数,argumentResolvers和returnValueHandlers,如同变量名,一个负责解析参数,一个负责处理返回值。
解析参数的过程中,第一次进入的请求将会进入if代码块,其余请求将直接从缓存获取参数解析器。

这里的解析器,在现在的程序中,就是指将请求参数反序列化为对象的请求参数处理程序和将对象序列化为流的返回参数处理程序。

在这里插入图片描述

这里可以看到,Spring自带了27种解析器,而@RequestBody和@ResponseBody的解析器就是图中标出的RequestResponseBodyMethodProcessor。
在这里插入图片描述

在图中可以看到,判断的依据就是是否使用@RequestBody和@ResponseBody修饰过。
在这里插入图片描述
在程序启动后的第一个@RequestBody的请求进入时,将缓存处理程序。
如图所示,下一次进入时就不需要轮训程序列表了,可以直接从Map中读取,效率有保障。
在这里插入图片描述
resolveArgument方法是处理参数的方法,如图所示,这是一个反序列化的方法,将流转换为对象。
在这里插入图片描述
转换完成后,将进入我们程序中的@Controller类,然后再经过RequestResponseBodyMethodProcessor的handleReturnValue方法将对象序列化为流,返回给浏览器。

以上是@RequestBody和@ResponseBody的处理流程。那么我们写的程序可以利用这一点做什么呢?

在RequestResponseBodyMethodProcessor的父类AbstractMessageConverterMethodArgumentResolver中,Spring贴心的保留了一个供开发者利用的窗口。
在这里插入图片描述
通过使用@RestControllerAdvice注解可以在请求参数的进出处改写它,这种操作在处理大量参数的校验时挺好用。
以下代码是个人在处理大量参数的合法校验时使用的处理程序,如果有帮助就点个赞吧

@RestControllerAdvice
@Slf4j
public class RequestResponseBodyAdvice implements RequestBodyAdvice, ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        try {
            return handlerRequestBody(body);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            log.error("afterBodyRead", e);
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(ApiOperation.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            return handlerResponseBody(body);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            log.error("beforeBodyWrite", e);
        }
        return body;
    }

    private Object handlerRequestBody(Object argument) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        // 新增
        Class<?> argumentClass = argument.getClass();
        Field[] fields = argumentClass.getDeclaredFields();
        handlerRequestDefaultValue(fields, argument, argumentClass);
        Class<?> superclass = argumentClass.getSuperclass();
        while (null != superclass) {
            Field[] superFields = superclass.getDeclaredFields();
            handlerRequestDefaultValue(superFields, argument, superclass);
            superclass = superclass.getSuperclass();
        }
        return argument;
    }

    private void handlerRequestDefaultValue(Field[] fields, Object argument, Class<?> argClass) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {

        for (Field field : fields) {
            field.setAccessible(true);
            if (null != field.getAnnotation(ApiModelProperty.class)) {
                String fieldName = toUpperFirstOne(field.getName());
                Method getMethod = argClass.getDeclaredMethod("get" + fieldName);
                getMethod.setAccessible(true);
                Object o = getMethod.invoke(argument);
                Class<?> type = field.getType();
                if (null == o) {
                    String value = field.getAnnotation(ApiModelProperty.class).defaultValue();
                    String[] dict = field.getAnnotation(ApiModelProperty.class).dict();
                    boolean isEnums = dict.length > 1;
                    boolean isContains = Arrays.asList(dict).contains(value);
                    Method setMethod = argClass.getDeclaredMethod("set" + fieldName, type);
                    setMethod.setAccessible(true);
                    if (type.equals(String.class)) {
                        if (isEnums && isContains) {
                            setMethod.invoke(argument, value);
                        }else if(isEnums && StringUtils.hasText(value)){
                            setMethod.invoke(argument, dict[0].split(":")[0]);
                        }else
                        if (StringUtils.hasText(value)) {
                            setMethod.invoke(argument, value);
                        }
                    } else if (type.equals(Integer.class)) {
                        /*if (isEnums && isContains) {
                            setMethod.invoke(argument, Integer.valueOf(value));
                        }else if(isEnums && StringUtils.isNotBlank(value)){
                            setMethod.invoke(argument, Integer.valueOf(dict[0].split(":")[0]));
                        }else*/
                        if (StringUtils.hasText(value)) {
                            setMethod.invoke(argument, Integer.valueOf(value));
                        }
                    } else if (type.equals(Boolean.class)) {
                        /*if (isEnums && isContains) {
                            setMethod.invoke(argument, "1".equals(value));
                        }else if(isEnums && StringUtils.isNotBlank(value)){
                            setMethod.invoke(argument, "1".equals(dict[0].split(":")[0]));
                        }else*/
                        if (StringUtils.hasText(value)) {
                            setMethod.invoke(argument, "1".equals(value));
                        }
                    }
                }
            }
        }
    }

    private Object handlerResponseBody(Object argument) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        // 新增
        Class<?> argumentClass = argument.getClass();
        Field[] fields = argumentClass.getDeclaredFields();
        handlerResponseDefaultValue(fields, argument, argumentClass);
        Class<?> superclass = argumentClass.getSuperclass();
        while (null != superclass) {
            Field[] superFields = superclass.getDeclaredFields();
            handlerResponseDefaultValue(superFields, argument, superclass);
            superclass = superclass.getSuperclass();
        }
        return argument;
    }

    private void handlerResponseDefaultValue(Field[] fields, Object argument, Class<?> argClass) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {

        for (Field field : fields) {
            field.setAccessible(true);
            if (null != field.getAnnotation(ApiModelProperty.class)) {
                String fieldName = toUpperFirstOne(field.getName());
                Method getMethod = argClass.getDeclaredMethod("get" + fieldName);
                getMethod.setAccessible(true);
                Object o = getMethod.invoke(argument);
                Class<?> type = field.getType();
                if (null == o) {
                    String value = field.getAnnotation(ApiModelProperty.class).defaultValue();
                    Method setMethod = argClass.getDeclaredMethod("set" + fieldName, type);
                    setMethod.setAccessible(true);
                    if (type.equals(String.class) && StringUtils.hasText(value)) {
                        setMethod.invoke(argument, value);
                    } else if (type.equals(Integer.class) && StringUtils.hasText(value)) {
                        if (StringUtils.hasText(value)) {
                            setMethod.invoke(argument, Integer.valueOf(value));
                        }
                    } else if (type.equals(Boolean.class) && StringUtils.hasText(value)) {
                        setMethod.invoke(argument, "1".equals(value));
                    } else if (type.equals(List.class)) {
//                        Type genericType = field.getGenericType();
//                        if (genericType instanceof ParameterizedType) {
//                            ParameterizedType pt = (ParameterizedType) genericType;
//                            Class<?> genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
//                            if (isPrimitive(genericClazz)) {
//                                setMethod.invoke(argument, new ArrayList<>());
//                                continue;
//                            }
//                            Object o1 = genericClazz.newInstance();
//                            Field[] argufields = genericClazz.getDeclaredFields();
//                            handlerResponseDefaultValue(argufields, o1, genericClazz);
//                            setMethod.invoke(argument, Collections.singletonList(o1));
//                        } else {
                        setMethod.invoke(argument, new ArrayList<>());
//                        }
                    } else if (!isPrimitive(type)) {
                        Field[] argufields = type.getDeclaredFields();
                        Object o1 = type.newInstance();
                        handlerResponseDefaultValue(argufields, o1, type);
                        setMethod.invoke(argument, o1);
                        //setMethod.invoke(argument, new Object());
                    }
                }
            }
        }
    }

    private String toUpperFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return Character.toUpperCase(s.charAt(0)) +
                    s.substring(1);
        }
    }

    private boolean isPrimitive(Class<?> clazz) {
        return clazz.equals(Integer.class) ||
                clazz.equals(Byte.class) ||
                clazz.equals(Long.class) ||
                clazz.equals(Double.class) ||
                clazz.equals(Float.class) ||
                clazz.equals(Character.class) ||
                clazz.equals(Short.class) ||
                clazz.equals(Boolean.class);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于 Spring Boot 的用户登录案例: 1. 创建 User 实体类 ```java @Data public class User { private String username; private String password; } ``` 2. 创建 UserService 接口和实现类 ```java public interface UserService { User login(String username, String password); } @Service public class UserServiceImpl implements UserService { @Override public User login(String username, String password) { // 在这里校验用户名和密码是否正确,省略实现 return new User(username, password); } } ``` 3. 创建 UserController 控制器 ```java @Controller public class UserController { @Autowired private UserService userService; @PostMapping("/login") @ResponseBody public String login(@RequestBody User user) { User loginUser = userService.login(user.getUsername(), user.getPassword()); if (loginUser != null) { return "登录成功"; } else { return "用户名或密码错误"; } } } ``` 4. 配置 mybatis 和数据库信息 在 application.properties 文件中添加以下配置: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 spring.datasource.username=root spring.datasource.password=root mybatis.mapper-locations=classpath:mapper/*.xml ``` 5. 创建 UserMapper 接口和 XML 映射文件 ```java @Mapper public interface UserMapper { User selectByUsernameAndPassword(@Param("username") String username, @Param("password") String password); } ``` 在 mapper 文件夹下创建 UserMapper.xml 文件,编写 SQL 语句: ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="username" property="username" /> <result column="password" property="password" /> </resultMap> <select id="selectByUsernameAndPassword" resultMap="BaseResultMap"> select * from user where username=#{username} and password=#{password} </select> </mapper> ``` 6. 编写测试代码 ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTests { @Autowired private UserController userController; @Test public void testLogin() { User user = new User(); user.setUsername("admin"); user.setPassword("123456"); String result = userController.login(user); assertEquals("登录成功", result); } } ``` 以上就是一个基于 Spring Boot 的用户登录案例的实现过程,希望对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值