定义一个注解:@RequestJson
import java.lang.annotation.*;
/**
* @author yz
* @className RequestJson
* @description 该注解可以接收post请求时前台传来的String类型参数
* @date 2020/3/26 17:40
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestJson {
String value();
}
注解的具体实现:
import java.io.BufferedReader;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.alibaba.fastjson.JSONObject;
/**
* @author yz
* @className RequestJsonHandlerMethodArgumentResolver
* @description
* @date 2020/3/26 17:42
*/
public class RequestJsonHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestJson.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
RequestJson requestJson = parameter.getParameterAnnotation(RequestJson.class);
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
BufferedReader reader = request.getReader();
StringBuilder sb = new StringBuilder();
char[] buf = new char[1024];
int rd;
while ((rd = reader.read(buf)) != -1) {
sb.append(buf, 0, rd);
}
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
String value = requestJson.value();
if (jsonObject == null) {
return null;
}
return jsonObject.get(value);
}
}
添加自定义的方法参数处理器
import com.lyun.examsite.base.annotation.RequestJsonHandlerMethodArgumentResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
* @author yz
* @className WebMvcConfig
* @description 添加自定义的方法参数处理器(RequestJsonHandlerMethodArgumentResolver)
* @date 2020/3/26 17:49
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(requestJsonHandlerMethodArgumentResolver());
}
@Bean
public RequestJsonHandlerMethodArgumentResolver requestJsonHandlerMethodArgumentResolver() {
return new RequestJsonHandlerMethodArgumentResolver();
}
}
@RequestMapping("/getSiteNavigationPoints")
public OutDTO<Map<String, Set<String>>> getSiteNavigationPoints(@RequestJson("examSiteId") String examSiteId) {
List<ExamSiteNavigationEntity> points = examSiteDao.getAllNavigation(examSiteId);
......
}