springmvc自定义参数解析器

由于开发中一般使用参数提交方式是json格式,对于单个参数的传递使用无法接收只能自定义参数解析器处理

springmvc的自定义参数解析器实现HandlerMethodArgumentResolver接口并且实现下面两个方法

 

第一个方法是 是否解析改参数 如果返回true 代表需要处理 则会调用resolveArgument方法进行解析

自定义参数注解(标识注解位置PARAMETER,以及运行时期

实现supportsParameter方法 如果方法中包含该注解返回true

将参数从流中读取出来保存到request请求体中,这样第二次参数解析调用就直接从请求体中获取即可

public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver {
	private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";

	@Override
	public boolean supportsParameter(MethodParameter methodParameter) {
		return methodParameter.hasParameterAnnotation(JsonParam.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
		String body = getRequestBody(webRequest);
		Object val = null;
		try {
			if (StringUtil.isNotBlank(body)) {
				JSONObject jsonObject = JSONObject.parseObject(body);
				val = jsonObject.get(parameter.getParameterAnnotation(JsonParam.class).value());
			}

			if (parameter.getParameterAnnotation(JsonParam.class).required() && val == null) {
				throw new RuntimeException(parameter.getParameterAnnotation(JsonParam.class).value() + "不能为空");
			}

		} catch (Exception exception) {
			if (parameter.getParameterAnnotation(JsonParam.class).required()) {
				/*返回*/
				throw exception;
			}
		}
		return val;
	}
	private String getRequestBody(NativeWebRequest webRequest) {
		HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
		String jsonBody = (String) servletRequest.getAttribute(JSON_REQUEST_BODY);
		if (jsonBody == null) {
			try {
				jsonBody = IOUtils.toString(servletRequest.getInputStream());
				servletRequest.setAttribute(JSON_REQUEST_BODY, jsonBody);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return jsonBody;

	}

}

然后需要装载自定义的参数解析器

最后使用的时候只需要在参数前加上自定义的注解即可获取到传递的json值

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IDONTCARE8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值