최근에 나는 SpringMVC 프레임 워크에 연락하기 시작했습니다. 이 프레임 워크는 사용하기에 매우 편리합니다. 프레임 워크가 구축 된 후 코드는 거의 동일한 패턴입니다. 물론,이 시점에 도달하려면 SpringMVC 관련 구성이 완료되었고 구성이 올바른지 확인해야합니다!
S-FLAT RingMVC에 대한 첫 번째 블로그로서,이 블로그는 주로 SpringMVC를 구성하는 방법에 대해 이야기하고 Bean 엔티티로 정상적으로 반환 할 수 있습니다. 여기의 Bean 엔티티는 일반적으로 JSON 문자열 형태로 프론트 엔드로 반환됩니다.
사용 된 개발 도구는 Eclipse이며 비교적 인기있는 개발 도구이기도합니다. 모든 사람이 사용하는 것으로 간주 될 수 있지만 숙련도 수준은 다릅니다!
특정 구성은 다음과 같습니다.
web.xml :
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://xmlns.jcp.org/jcp.org/xml/xmlns http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/sprger-context-4 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "id ="webapp_id "3.1"> <context-param> contextconflocation> <Param-value> classpath : ApplicationContext.xml </param- value> </context-param> <layer> <layer-class> org.springframework.web.context.contextloaderListener </lurtener-class> </Lister> <lislay-name> returnjsondemo </display-name> <welcome-file> index.jsp </welcome-file> </welcome-file-list> <servlet> <servlet-name> Dispatcher </servlet-name> <servlet-class> org.spramework.web.servlet.dispatchervlet </servlet-class> <init-param> <param-name> contextConfiglocation> <Param-value> classpath : Dispatcher-servlet.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> dispatcher </servlet-name> <Url-pattern>/</url-pattern> </serv-mapping> </web-app>
Dispatcher-Servlet.xml :
<? xml version = "1.0"alcoding = "utf-8"?> <beans xmlns : xsi = "http://www.w.w.2001/xmlschema-instance"xmlns = "http://ww.springframework.org/schema/beans" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://xmlns.jcp.org/jcp.org/xml/xmlns http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sprger-beans-4.0.xeans-4 http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <mvcoger-servleter/) <context : component-scan base-package = "com.zyq.springmvc.controller"> <context : exclude-filter type = "주석"표현 = "org.springframework.steretype.service" /> < /context : context : annotation-config /> <mvc : messe-converters> <ean> <property name = "supporedMediadiTypes"> <list> <talue> text/plain; charset = utf-8 </value> <value> text/html; charset = utf-8 </value> </list> </property> </bean> <bean> <properted mamepes "; charset = utf-8 </value> <value> 응용 프로그램/x-www-form-urlencoded; charset = utf-8 </value> </list> </property> </bean> </mvc : message-converters> </mvc : Annotation-Driven> </beans>
ApplicationContext.xml도 있지만 아무것도 쓰지 않으므로 포기하지 않습니다!
각 인터페이스의 리턴 값이 정상인지 테스트하기 위해 기본 인터페이스로 사용되는 새 index.jsp를 만듭니다! 코드도 여기에 제공됩니다.
<%@ page language = "java"contmenttype = "text/html; charset = iso-8859-1"pageencoding = "iso-8859-1"%> <! doctype html public "-// w3c // dtd html 4.01 Transitional // en" "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> html> http-tequiv ="content-type "content ="text/html; charset = iso-8859-1 "> <title> </head> <h1> 메인 페이지 </h1> </h1> < action = "/returnjsondemo/first"> <입력 유형 = "value ="first "/> </form> <form action ="/returnjsondemo/secon action = "/returnjsondemo/fourth"> <input type = "제출"value = "fourth"/> </form> </body> </html>
이 시점에서 모든 구성이 기본적으로 완료되고 컨트롤러가 선언됩니다. 특정 코드는 비교적 간단하며 기본적으로 고정 형식입니다!
MainController.java
패키지 com.zyq.springmvc.controller; import java.text.simpledateformat; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; import org.springframework.steretype.controller; org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.responsebody; import com.zyq.springmvc.bean.commonbean; import com.zyq.springmvc.bean.sonbean; @controllic class Maintontroller {Controllerpublic Class Maintroller @RequestMapping ( "/First") @ResponseBody publicbean getFirst () {CommonBean Bean = New CommonBean (); bean.setResultCode ( "성공"); bean.settimestamp (new simpledateformat ( "yyyy/mm/dd hh : mm : ss"). 형식 (System.CurrentTimeMillis ())); bean.setData ( "이것은 첫 번째 메시지입니다"); 귀환 콩; } @requestmapping ( "/sec bean.setResultCode ( "SS"); bean.settimestamp (new simpledateformat ( "yyyy/mm/dd hh : mm : ss"). 형식 (System.CurrentTimeMillis ())); List <string> data = new ArrayList <> (); data.add ( "Java"); data.add ( "c"); data.add ( "Python"); data.add ( "C ++"); bean.setData (데이터); 귀환 콩; } @RequestMapping ( "/Third") @ResponseBody Public Bean getthird () {CommonBean Bean = New CommonBean (); bean.setResultCode ( "성공"); bean.settimestamp (new simpledateformat ( "yyyy/mm/dd hh : mm : ss"). 형식 (System.CurrentTimeMillis ())); map <string, string> data = new Hashmap <> (); data.put ( "첫 번째", "Java"); data.put ( "두 번째", "파이썬"); data.put ( "세 번째", "C ++"); data.put ( "네 번째", "c"); bean.setData (데이터); 귀환 콩; } @RequestMapping ( "/fourth") @ResponseBody Public CommonBean getfourth () {CommonBean Bean = New CommonBean (); bean.setResultCode ( "성공"); bean.settimestamp (new simpledateformat ( "yyyy/mm/dd hh : mm : ss"). 형식 (System.CurrentTimeMillis ())); Sonbean Sonbean = New Sonbean (); Sonbean.setage (25); Sonbean.setName ( "해커의 기쁨"); sonbean.setgender ( "male"); Bean.SetData (Sonbean); 귀환 콩; }}코드의 실행 효과는 다음과 같습니다.
브라우저마다 인터페이스에 대한 요청 작업이 다릅니다. Eclipse Request Interface를 사용하면 JSON 파일이 다운로드되고 파일의 내용은 JSON 문자열입니다.
완전한 프로젝트를 구성 할 때는 SpringFramework JAR 패키지와 Jackson의 관련 JAR 패키지를 사용해야합니다. Tomcat8.5 나는 실행할 때 오류를 프롬프트하고 일반 로그 JAR 패키지를 소개해야합니다.
JSON 문자열을 반환하는 인터페이스를 선언 할 때는 @ResponseBody 주석을 사용해야합니다. @ResponseBody 주석을 사용해야합니다.이 주석은 반응에서 신체 영역에 인터페이스의 반환 데이터를 작성합니다.
테스트 할 때 문제가 발생했습니다. 콩을 반환 할 때는 클래스 패키지 만 반환 할 수 있지만 클래스 상속 또는 인터페이스 상속은 아닙니다. 예를 들어:
내부에 출산이 포함 된 부모 비안을 반환하면 괜찮습니다!
인터페이스가 정의되면 반환 된 상위 클래스가 실제 반환 된 서브 클래스이고 현재 오류가보고되고 하위 클래스를 상위 클래스로 변환 할 수 없으므로 문자열 객체를 객체 객체로 변환 할 수 없음을 의미합니다. 이와 관련하여 서브 클래스의 속성을 찾을 수없는 상위 클래스를 기반으로해야하며, 이는 Bean 객체를 JSON 문자열로 정상적으로 변환 할 수 없게됩니다. 따라서 프레임 워크의 인터페이스에서 Bean을 선언 할 수 없으며 Bean의 서브 클래스가 반환됩니다 (이러한 이유는 개인적인 추측 일 뿐이며 특정 이유는 프레임 워크에서 코드를 분석해야합니다!
좋아, 그게 JSON 줄을 반환하는 것입니다! 데모의 소스 코드를 첨부하십시오. 필요한 JAR 패키지도 내부에 있습니다. 필요한 경우 직접 다운로드 할 수 있습니다!
소스 코드 다운로드
JSON 문자열을 반환하기 위해 SpringMVC를 사용하는 위의 예제는 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.