目錄
SpringMVC自定義基於注解的參數解析器
例如:
支持請求:/user/add?userid=100&dept={"id":1,"name":"部門1"}
自動將json格式值轉換為JavaBean對象
前期准備
JavaBean
public class Dept {
private Integer id;
private String name;
}
自定義注解
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonParam {
String value();
}
Controller
@Controller
public class UserController {
@RequestMapping("/users/add")
@ResponseBody
public Map<String, Object> addUser(Integer userid, @JsonParam("dept") Dept userDept) {
Map<String, Object> data = new HashMap<>(2);
data.put("userId", userid);
data.put("userDept", userDept);
return data;
}
}
自定義參數解析器
public class JsonParamProvider implements HandlerMethodArgumentResolver {
/**
* 判斷是否是需要我們解析的參數類型
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(JsonParam.class);
}
/**
* 真正解析的方法
*/
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
Map<String, String[]> parameterMap = request.getParameterMap();
JsonParam jsonParam = methodParameter.getParameterAnnotation(JsonParam.class);
String paramName = jsonParam.value();
//注解沒有給定參數名字,默認取參數類型的小寫
if (StringUtils.isEmpty(paramName)) {
String parmTypeName = methodParameter.getParameterType().getSimpleName();
paramName = parmTypeName.substring(0, 1).toLowerCase() + parmTypeName.substring(1);
}
//從request中能拿到參數值
if (parameterMap.containsKey(paramName)) {
String paramVal = parameterMap.get(paramName)[0];
//解析json
ObjectMapper objectMapper = new ObjectMapper();
Dept dept = objectMapper.readValue(paramVal.getBytes("UTF-8"), Dept.class);
return dept;
} else {
return new Dept();
}
}
}
配置自定義參數解析器
一、xml方式配置
spring-mvc.xml內容
<?xml version="1.0" encoding="UTF-8"?>
<context:component-scan base-package="com.demo" />
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="com.demo.JsonParamProvider"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
</beans>
二、注解方式配置
spring-mvc.xml內容
<?xml version="1.0" encoding="UTF-8"?>
<context:component-scan base-package="com.demo" />
<!--不能添加該標簽,否則注解類不生效-->
<!--<mvc:annotation-driven/>-->
</beans>
自定義注解類內容
@Configuration
@EnableWebMvc
public class MyConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new JsonParamProvider());
}
}
SpringBoot自定義基於注解的參數解析器
自定義注解類內容
@Configuration
public class MyConfiguration extends WebMvcConfigurationSupport {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new JsonParamProvider());
}
}