首页 > 其他分享 >spring mvc3.2 requestbody json显示原理

spring mvc3.2 requestbody json显示原理

时间:2023-04-25 18:04:46浏览次数:44  
标签:mvc3.2 return spring Object requestbody webRequest outputMessage returnType Meth


1,
public interface HandlerMethodReturnValueHandler {

	/**
	 * Whether the given {@linkplain MethodParameter method return type} is 
	 * supported by this handler.
	 *
	 * @param returnType the method return type to check
	 * @return {@code true} if this handler supports the supplied return type; 
	 * {@code false} otherwise
	 */
	boolean supportsReturnType(MethodParameter returnType);

	/**
	 * Handle the given return value by adding attributes to the model and 
	 * setting a view or setting the 
	 * {@link ModelAndViewContainer#setRequestHandled} flag to {@code true}
	 * to indicate the response has been handled directly.  
	 * 
	 * @param returnValue the value returned from the handler method
	 * @param returnType the type of the return value. This type must have 
	 * previously been passed to 
	 * {@link #supportsReturnType(org.springframework.core.MethodParameter)} 
	 * and it must have returned {@code true}
	 * @param mavContainer the ModelAndViewContainer for the current request
	 * @param webRequest the current request
	 * @throws Exception if the return value handling results in an error
	 */
	void handleReturnValue(Object returnValue,
						   MethodParameter returnType,
						   ModelAndViewContainer mavContainer,
						   NativeWebRequest webRequest) throws Exception;

}
2,
public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor {

	public RequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> messageConverters) {
		super(messageConverters);
	}

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(RequestBody.class);
	}

	public boolean supportsReturnType(MethodParameter returnType) {
		return returnType.getMethodAnnotation(ResponseBody.class) != null;
	}

	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

		Object arg = readWithMessageConverters(webRequest, parameter, parameter.getParameterType());
		Annotation[] annotations = parameter.getParameterAnnotations();
		for (Annotation annot : annotations) {
			if (annot.annotationType().getSimpleName().startsWith("Valid")) {
				String name = Conventions.getVariableNameForParameter(parameter);
				WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
				Object hints = AnnotationUtils.getValue(annot);
				binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
				BindingResult bindingResult = binder.getBindingResult();
				if (bindingResult.hasErrors()) {
					throw new MethodArgumentNotValidException(parameter, bindingResult);
				}
			}
		}
		return arg;
	}

	public void handleReturnValue(Object returnValue, MethodParameter returnType,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
			throws IOException, HttpMediaTypeNotAcceptableException {

		mavContainer.setRequestHandled(true);
		if (returnValue != null) {
			writeWithMessageConverters(returnValue, returnType, webRequest);
		}
	}

}

3,AbstractMessageConverterMethodProcessor
	protected <T> void writeWithMessageConverters(T returnValue,
												  MethodParameter returnType,
												  NativeWebRequest webRequest)
			throws IOException, HttpMediaTypeNotAcceptableException {
		ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
		ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
		writeWithMessageConverters(returnValue, returnType, inputMessage, outputMessage);
	}

4,AbstractMessageConverterMethodProcessor
	public final void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {

		HttpHeaders headers = outputMessage.getHeaders();
		if (headers.getContentType() == null) {
			if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
				contentType = getDefaultContentType(t);
			}
			if (contentType != null) {
				headers.setContentType(contentType);
			}
		}
		if (headers.getContentLength() == -1) {
			Long contentLength = getContentLength(t, headers.getContentType());
			if (contentLength != null) {
				headers.setContentLength(contentLength);
			}
		}
		writeInternal(t, outputMessage);
		outputMessage.getBody().flush();
	}

5,MappingJacksonHttpMessageConverter
	protected void writeInternal(Object object, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {

		JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
		JsonGenerator jsonGenerator =
				this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);

		// A workaround for JsonGenerators not applying serialization features
		// https://github.com/FasterXML/jackson-databind/issues/12
		if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) {
			jsonGenerator.useDefaultPrettyPrinter();
		}

		try {
			if (this.prefixJson) {
				jsonGenerator.writeRaw("{} && ");
			}
			this.objectMapper.writeValue(jsonGenerator, object);
		}
		catch (JsonProcessingException ex) {
			throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}



标签:mvc3.2,return,spring,Object,requestbody,webRequest,outputMessage,returnType,Meth
From: https://blog.51cto.com/u_16088628/6224789

相关文章

  • spring mvc3.2启动分析
    1,GenericServletpublicvoidinit(ServletConfigconfig)throwsServletException{ this.config=config; this.init();}2,HttpServletBean publicfinalvoidinit()throwsServletException{ if(logger.isDebugEnabled()){ logger.debug("......
  • Springboot 在linux后台运行的方法
    1、后台运行程序nohupjava-jar自己的springboot项目.jar>日志文件名.log2>&1&命令详解:nohup:不挂断地运行命令,退出帐户之后继续运行相应的进程。>日志文件名.log:是nohup把command的输出重定向到当前目录的指定的“日志文件名.log”文件中,即输出内容不打印到屏幕上,而......
  • Springboot日期注解失败:while it seems to fit format ‘yyyy-MM-dd‘T‘HH:mm:ss.SSS
    提交字符串到后台映射为Date类型可以加上@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")注解,但是报错了!前端提交字符串到后台,出现如下错误:whileitseemstofitformat'yyyy-MM-dd'T'HH:mm:ss.SSSZ',parsingfails(leniency?null))错误的大致意思就是字符串映射到Da......
  • 使用Dockerfile部署springboot打包jar包
    1、docker下载JDK1.8镜像dockerpulljava:82、编写Dockerfile文件#依赖的父镜像FROMjava:8#作者MAINTAINERdocker-admin#jar包添加到镜像中ADDxxl-job-admin-2.1.2.jarxxl-job-admin.jar#容器暴露的端口即jar程序在容器中运行的端口EXPOSE8080#容器启动之后......
  • java面试题--springboot
    一、SpringBoot自动装配原理是什么?@SpringBootApplication@EnableAutoConfigration\@SpringBootConfigration\@ComponentScan@AutoConfigrationPackage\@ImportMETA-INF\spring.factories二、说一下@Configuration中的属性proxyBeanMethods的作用?首先,引入两个概念:Full全......
  • SpringSecurity从入门到精通:授权基本流程&设置资源所需权限&封装权限信息
    授权基本流程在SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验,在FilterSecurityInterceptor中会从SecurityContextHilder获取其中的Authentication,然后获取其中的权限信息,当前用户是否拥有访问当前资源所需的权限所以我们在项目中只需要把当前登......
  • SpringBoot 使用 Sa-Token 完成权限认证
    一、设计思路所谓权限认证,核心逻辑就是判断一个账号是否拥有指定权限:有,就让你通过。没有?那么禁止访问!深入到底层数据中,就是每个账号都会拥有一个权限码集合,框架来校验这个集合中是否包含指定的权限码。例如:当前账号拥有权限码集合["user-add","user-delete","user-get"]......
  • Consider defining a bean of type 'org.springframework.security.authentication.Au
    Considerdefiningabeanoftype'org.springframework.security.authentication.AuthenticationManager'inyourconfiguration.[2023-04-2514:44:36.426][main][ERROR]o.s.b.diagnostics.LoggingFailureAnalysisReporter-***************************......
  • Spring Security的四种权限控制方式
    关注我了解更多Java技术知识,带你一路“狂飙”到底!上岸大厂不是梦!在前面的章节中,已经给大家介绍了SpringSecurity的很多功能,在这些众多功能中,我们知道其核心功能其实就是认证+授权。下面班分享:Spring教程之SpringSecurity的四种权限控制方式。在前面我们分别基于内存模型、基......
  • SpringBoot 日志切面
    SpringBoot日志切面在SpringBoot中搞一下AOP切面,复习一下。太详细的概念就不用说了,直接看SpringAOP实现吧,当时写的除了有点模糊也没什么大问题。AOP概念在SpringBoot中使用AOP,直接引入spring-boot-starter-aop的包即可:<dependency><groupI......