2016년 7월 17일 일요일

[Spring MVC]@RequestBody요청처리예제 - 스프링실무교육학원

[Spring MVC]@RequestBody요청처리예제 - 스프링실무교육학원

<!--[if !supportLists]-->n  <!--[endif]-->@RequestBody 어노테이션은 HTTP 요청 몸체(Request Body)를 자바 객체로 변환하고 @ResponseBody 어노테이션은 자바 객체를 HTTP 응답 몸체로 변환하는 데 사용한다.(응답을 Body에 직접 씀):namespace prefix = o />
 
<!--[if !supportLists]-->n  <!--[endif]-->Spring MVC를 이용하여 @RequestBody를 실습해보자.
 
“springrequest” 라는 이름으로 File -> New -> Spring Legacy Project -> Spring MVC 프로젝트를 생성하고 top level package명을 a.b.springrequest 라고 주자.
 
[pom.xml]
Spring Framework 버전은 4.X 이상으로 수정하자.
<properties>
           ……
           <org.springframework-version>4.2.4.RELEASE</org.springframework-version>
           ……
</properties>
 
 
브라우저에 json형태로 출력하기 위한 라이브러리를 추가하자.
<!-- Jackson -->
<dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-annotations</artifactId>
           <version>2.4.2</version>
</dependency>
 
<dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-core</artifactId>
           <version>2.4.2</version>
</dependency>
<dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
           <version>2.4.2</version>
</dependency>
 
[Emp.java]
 
package a.b.springrequest;
 
public class Emp {
           int empno;
           String ename;
           public int getEmpno() {
                     return empno;
           }
           public void setEmpno(int empno) {
                     this.empno = empno;
           }
           public String getEname() {
                     return ename;
           }
           public void setEname(String ename) {
                     this.ename = ename;
           }
           public String toString() {
                     return "empno = " + empno + ", ename = " + ename;
           }
}
 
[HomeController.java]
 
package a.b.springrequest;
 
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HomeController {
           @RequestMapping(value="/rest", method = RequestMethod.GET, headers="Accept=application/json")
           public Emp getHandler() {
                     Emp e = new Emp();
                     e.setEmpno(1111);
                     e.setEname("OracleJavaCommunity");                   
                     return e;
           }
          
           @RequestMapping(value="/rest", method = RequestMethod.POST, headers="Accept=application/json")
           public @ResponseBody Emp postHandler(@RequestBody final Emp e) {
                     System.out.println(e + ">>>>>>>>>>>>>>>>>>>>");
                     return e;
           }         
}
 
[src/main/webapp/WEB-INF/web.xml]
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
           <!-- Processes application requests -->
           <servlet>
                     <servlet-name>appServlet</servlet-name>
                     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                     <init-param>
                                <param-name>contextConfigLocation</param-name>
                                <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
                     </init-param>
                     <load-on-startup>1</load-on-startup>
           </servlet>
                    
           <servlet-mapping>
                     <servlet-name>appServlet</servlet-name>
                     <url-pattern>/rest</url-pattern>
           </servlet-mapping>
 
</web-app>
 
[ src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml]
 
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:beans="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
           <!-- Enables the Spring MVC @Controller programming model -->
           <annotation-driven />
           <context:component-scan base-package="a.b.springrequest" />
</beans:beans>
 
4. src/main/webapp/index.html
 
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>@Request, @Response 테스트</title>
 <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
  sendAjax();
});
 
function sendAjax() {
$.ajax({
    url: "/springrequest/rest",
    type: 'POST',
    dataType: 'json',
    data: "{\"empno\":9999, \"ename\":\"오라클자바커뮤니티\"}",
    contentType: 'application/json; charset=utf-8',
    mimeType: 'application/json',
    success: function(data) {
        alert(data.empno + " " + data.ename);
    },
    error:function(data,status, er) {
        alert("error: "+data+" status: "+status+" er:"+er);
    }
});
}
</script>
</head>
<body>
</body>
</html>
 
[실행]
1.프로젝트에서 우쪽 마우스 버튼 -> Run as -> Run On Server 클릭 후 STS에 기본적으로 내장되어 있는 Pivotal tc Server를 선택하고 Finish  클릭하여 실행하자http://localhost:8080/springrequest/rest 라고 URL창에서 입력하면(Get방식컨트롤로의 getHandler() 메소드가 호출되어 생성한 Emp 객체를 JSON 형태로 브라우저에 출력한다. JSON형태로 출력하기 위해 Jackson 라이브러리를 pom.xml에 추가했다.
 
 
 
2. http://localhost:8080/springrequest/ 라고 입력하면 index.html 이 호출되어 다시 서버로 POST 방식으로http://localhost:8080/springrequest/rest 요청을 보내 컨트롤러의 postHandler() 메소드가 호출되고 index.html에서 ajax 형태로 요청바디에 넘겨주는 empno : 9999, ename = “오라클자바커뮤니티” 값이 컨트롤러 메소드의 @RequestBody 어노테이션에 의해Emp 객체로 매핑되고 이 Emp 객체를 다시 index.html로 보내줘서 아래와 같은 결과화면이 출력된다.
 

댓글 없음:

댓글 쓰기