요약
SpringMVC는 메시지 변환기를 사용하여 요청 메시지와 객체, 객체 및 응답 메시지 간의 자동 변환을 실현합니다.
SpringMVC에서는 두 개의 주석 @requestbody 및 @ResponseBody를 사용하여 요청 메시지를 객체로 각각 변환하고 응답 메시지로 개체 할 수 있습니다. 기본 유연한 메시지 변환 메커니즘은 새로 도입 된 httpmessageconverter, 메시지 변환기 메커니즘이며, 이는 Spring 3.x에서 새로 소개 된 httpmessageconverter입니다.
#http 요청의 추상화는 여전히 요청-응답으로 돌아가는 것입니다. 즉, 요청 본문을 구문 분석 한 다음 응답 메시지를 반환합니다. 이것은 가장 기본적인 HTTP 요청 프로세스입니다. Servlet 표준에서 javax.servlet.servletrequest 인터페이스의 다음 방법을 사용할 수 있음을 알고 있습니다.
공무원 getInputStream ()는 ioException을 던졌습니다.
ServletinputStream을 얻으려면. 이 servletinputStream에서는 원시 요청 메시지의 모든 내용을 읽을 수 있습니다. 마찬가지로 Javax.Servlet.ServletResponse 인터페이스에서 다음 방법을 사용할 수 있습니다.
Public ServletoutPutStream getOutputStream ()은 ioException을 던졌습니다.
ServletoutPutStream을 얻으려면 Java의 OutputStream에서 상속 된이 ServletOutputSteam을 사용하면 HTTP 응답 패킷 컨텐츠를 출력 할 수 있습니다.
SpringMVC의 디자이너처럼 생각해 보겠습니다. 우리는 HTTP 요청 및 응답 패킷이 본질적으로 일련의 문자열이라는 것을 알고 있습니다. 요청 패킷이 Java 세계에 오면 패킷을 읽을 수 있도록 ServletInputStream 입력 스트림으로 캡슐화됩니다. 응답 메시지는 ServletOutputStream의 출력 스트림을 통해 출력됩니다.
스트림에서 원래 문자열 메시지 만 읽을 수 있으며 마찬가지로 원래 문자를 출력 스트림에만 쓸 수 있습니다. Java 세계에서 비즈니스 논리의 처리는 비즈니스 별 개체를 처리 차원으로 기반으로합니다. 그런 다음 메시지가 SpringMVC에 도착하여 SpringMVC에서 종료되면 문자열과 Java 객체 사이에 임피던스 문제가 있습니다. 이 프로세스는 개발자가 수동으로 변환 할 수 없습니다. Struts2에서 OGNL 은이 문제를 다루는 데 사용되는 반면 SpringMVC에서는 HTTPMESSAGECONVERTER 메커니즘이라는 것을 알고 있습니다. 먼저 두 인터페이스를 살펴 보겠습니다.
#httpinputMessage이 클래스는 SpringMVC 내의 HTTP 요청 메시지의 추상화입니다. httpmessageconverter의 read () 메소드에는 httpinputmessage의 공식 매개 변수가 있으며, 이는 SpringMVC의 메시지 변환기에서 사용한 수용체 "요청 메시지"의 내부 추상화입니다. 메시지 변환기는 규칙에 따라 "요청 메시지"에서 메시지를 추출하고 메소드 공식 매개 변수에서 선언 된 개체로 변환합니다.
패키지 org.springframework.http; import java.io.ioexception; import java.io.inputStream; public interface httpinputMessage 확장 httpMessage {inputStream getBody () IoException;}#HTTPOUTPUTMESSAGE이 클래스는 SpringMVC 내의 HTTP 응답 메시지의 추상화입니다. httpmessageconverter의 쓰기 () 메소드에는 httpoutputmessage의 공식 매개 변수가 있으며, 이는 SpringMVC의 메시지 변환기에서 사용하는 수용체 "응답 메시지의 내부 추상화입니다. 메시지 변환기는 특정 규칙에 따라 "응답 메시지"를 응답 메시지에 씁니다.
패키지 org.springframework.http; import java.io.ioexception; import java.io.outputStream; public interface httpoutputmessage 확장 httpmessage {outputStream getbody ()가 ioexception;}#httpmessageConverter 메시지 변환기의 최고 수준 인터페이스 추상화는 메시지 변환기의 일반적인 특성을 설명합니다. 이 인터페이스에 정의 된 방법 에서이 메커니즘에 대한 Spring3.x 디자이너의 사고 과정을 이해할 수 있습니다.
패키지 org.springframework.http.converter; import java.io.ioexception; import java.util.list; import org.springframework.http.http.httpinputmessage; import org.spramepramework.httpoutputmessage; import org.spramframwork.htwerk.htwerk.htwerk.htwork.htwerk.http 인터페이스 httpmessageconverter <t> {boolean canread (class <?> clazz, mediaType mediaType); 부울 canwrite (class <?> clazz, mediaType mediaType); getSupportedMediAtypes () 목록; t read (class <? extends t> clazz, httpinputmessage inputmessage)는 ioexception, httpmessagenoTreadableException; void write (t t, mediaType contenttype, httpoutputmessage outputmessage) ioexception, httpmessagenotwablexception;}httpmessageconverter 인터페이스의 정의는 canread (), read () 및 canwrite (), write () 메소드를 페어링했습니다. MediaType은 요청 된 미디어 유형 속성의 캡슐화입니다. 예를 들어, 다음 처리 방법을 선언 할 때.
@requestmapping (value = "/string", method = requestmethod.post) public @ResponseBody String readString (@RequestBody String) {return "read" + string + " '";}SpringMVC가 readString 메소드에 들어가기 전에 @RequestBody 주석에 따라 적절한 httpMessageConverter 구현 클래스를 선택하여 요청 매개 변수를 문자열 변수에 구문 분석합니다. 구체적으로, stringhttpmessageconverter 클래스가 사용됩니다. ITS CARREAD () 메서드는 true를 반환 한 다음 read () 메소드는 요청에서 요청 매개 변수를 읽고 readString () 메소드의 문자열 변수에 바인딩합니다.
SpringMVC가 readString 메소드를 실행할 때, 리턴 값이 @ResponseBody를 식별하기 때문에 SpringMVC는 stringhttpmessageConverter의 write () 메소드를 사용하고 결과를 응답 메시지에 문자열 값으로 씁니다. 물론 CanWrite () 메소드는 현재 TRUE를 반환합니다.
다음 그림을 사용 하여이 과정을 간단히 설명 할 수 있습니다.
#requestresponseBodyMethodProcessor 위의 프로세스 세트에 설명 된 클래스는 org.springframework.web.servlet.mvc.method.annotation.requestresponsebodyMethodProcessor입니다. 이 클래스는 Handlermethodargumentresolver와 HandlermethodreturnValueHandler 인터페이스를 모두 구현합니다. 전자는 요청 메시지를 처리 방법의 공식 매개 변수에 바인딩하는 정책 인터페이스이며, 후자는 처리 방법의 반환 값을 처리하는 정책 인터페이스입니다. 두 인터페이스의 소스 코드는 다음과 같습니다.
패키지 org.springframework.web.method.support; import org.springframework.core.methodparameter; import org.springframework.web.bind.webdatabinder; import org.springframework.web.bind.support.webdatabinderfactory; org.springframework.web.context.request.nativewebrequest; public interface handlermethodargumentresolver {boolean supporameter (MethodParameter 매개 변수); Object ResolVeargument (MethodParameter 매개 변수, ModelAndViewContainer MavContainer, NativeWebRequest WebRequest, WebDatabinderFactory BindFactory)는 예외를 발생시킵니다. org.springframework.web.context.request.nativewebrequest; public interface handlermethodreturnvalueHandler {boolean supportSreturnType (MethodParameter returnType); void handlerEturnValue (객체 returnValue, MethodParameter returnType, modelAndViewContainer MavContainer, NativeWebRequest WebRequest) 예외를 던졌습니다.}RequestresponseBodyMethodProcessor 클래스는 메소드 매개 변수 분석 및 반환 값 처리의 두 가지 역할 역할을합니다. 소스 코드에서 위의 두 인터페이스의 메소드 구현을 찾을 수 있습니다.
Handlermethodargumentresolver 인터페이스 구현 :
public boolean supporameter (methodparameter parameter) {return parameter.hasparameterAnnotation (requestody.class);} public object resolveargument (methodParameter 매개 변수, modelandViewContainer mavcontainer, NativeWebRequest WebRequest, WebDatabinderFactory Throws) 예외 = readWithMessAgeConverters (WebRequest, Parameter, Parameter.GetGenericParameterType ()); 문자열 이름 = concentions.getVariableNameforParameter (매개 변수); WebDatabinder binder = bindfactory.createbinder (WebRequest, argument, name); if (argument! = null) {validate (바인더, 매개 변수); } mavcontainer.addattribute (bindingResult.model_key_prefix + 이름, binder.getBindingResult ()); 반환 인수;}HandlermethodreturnValueHandler 인터페이스 구현
public boolean supportSreturnType (MethodParameter returnType) {return returnType.getMethodAntation (responskBody.class)! = null;} public void handlerEturnValue (객체 returnValue, MethodParameter returnType, ModelViewContainer Mavcontainer, aventiveBrequest), iooxemence httpmediatecepceptableException {mavcontainer.setRequestHandled (true); if (returnValue! = null) {WriteWithMessAgeConverters (returnValue, returnType, WebRequest); }}위의 코드를 읽은 후 전체 HTTPMESSAGECONVERTER 메시지 변환 컨텍스트는 이미 매우 명확합니다. 두 인터페이스의 구현은 조건으로 @requestbody 및 @ResponseBody가 있는지 여부를 기반으로하고 HTTPMESSAGECONVERTER가 각각 메시지를 읽고 쓰기 위해 호출됩니다.
RequestresponseBodyMethodProcessor를 추적하는 방법을 문의하려면 이전 블로그 게시물의 아이디어를 따르고 Spring-MVC-Showcase로 이동하여 소스 코드를 다운로드하고 HTTPMessageConverter 관련 예제를 디버깅하십시오. 당신이 열심히 일할 의향이있는 한, 나는 당신이 확실히 당신의 자신을 얻을 것이라고 믿습니다.
#Zhang Xiaolong을 Wechat의 본질에 대해 이야기 할 때 그는 다음과 같이 말했습니다 : "Wechat은 플랫폼 일뿐이며 메시지가 순환하고 있습니다." SpringMVC 소스 코드를 분석하는 과정에서 HTTPMESSAGECONVERTER 메커니즘의 유사한 진실을 이해할 수 있습니다. SpringMVC 디자이너의 눈에는 요청 메시지와 응답 메시지가 요청 메시지 httpinputMessage 및 응답 메시지 httpoutputmessage로 각각 추출됩니다.
요청을 처리 할 때 적절한 메시지 변환기는 요청 메시지를 메소드의 공식 매개 변수 개체에 바인딩합니다. 여기에는 JSON 및 XML과 같은 동일한 객체에 대해 여러 다른 메시지 양식이있을 수 있습니다. 마찬가지로, 요청에 응답 할 때, 메소드의 반환 값은 JSON 및 XML과 같은 다른 메시지 양식으로 반환 될 수 있습니다.
SpringMVC에는 다른 메시지 양식에 대한 다양한 메시지 양식을 처리하기 위해 다른 HTTPMESSAGECONVERTER 구현 클래스가 있습니다. 그러나 이러한 메시지에 포함 된 "유효한 정보"가 일관된 한 다양한 메시지 변환기가 동일한 변환 결과를 생성합니다. 다양한 메시지 간의 구문 분석 세부 사항의 차이에 대해서는 다른 HTTPMESSAGECONVERTER 구현 클래스에서 차단됩니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.