記錄

Spring) ajax _2(@ResponseBody, @RequestBody 사용) 본문

Web/Spring framework

Spring) ajax _2(@ResponseBody, @RequestBody 사용)

surhommejk 2018. 5. 11. 11:27



1. pom.xml 에서 jackson dependency 선언

(비동기로 json타입의 데이터를 가져올 것이기 때문에)

<!-- jackson lib -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.7.3</version>
        </dependency>
        <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
        </dependency>
        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.3</version>
        </dependency>
        






2. DispatcherServlet 에 다음과 같이 선언(네임스페이스에 유의, xmlns:mvc 설정과 이를 이용한 맨 밑 두 줄)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">

<!-- @ResponseBody messageConverter 동작 -->
<mvc:annotation-driven />
<context:component-scan base-package="kosta.controller" />

<bean name="/index.kosta" class="org.springframework.web.servlet.mvc.
ParameterizableViewController">
    <property name="viewName" value="index"></property>
</bean>
</beans>







3. 컨트롤러에서 아래와 같이 처리 (@ResponseBody, @RequestBody 설정)

@RequestMapping(value="response2.kosta",method=RequestMethod.POST)
    public @ResponseBody Employee add(@RequestBody Employee emp)
         // 응답 타입에 @ResponseBody 설정해서 이를 return하면 json으로 자동 변환
         // 파라미터에는 @RequestBody (객체 형태로 데이터 받기)
           // Employee의 멤버 필드명과 보낸 데이터의 key값이 일치해야 함
    { System.out.println("response");
        System.out.println(emp.toString());
        
        // dto를 json 형태로 넘기게 된다
        return emp;
    }
}







4. 비동기 요청 코드

var _param = {firstname:$("#firstName").val(), lastname:$("#lastName").val() ,
email:$("#email").val()};

_data = JSON.stringify(_param); //jsonString으로 변환
alert(_data);


$.ajax({
type : 'POST',
url : "response2.kosta",
cache: false,
dataType: "json",
data: _data,
processData: false,
contentType: "application/json; charset=utf-8",
success : function(data, status){
console.log("status:"+status+","+"data:"+data);
alert(data.email);
},
error: function(request, status, error){
//alert("loading error:" + request.status);
console.log("code : " + request.statusText + "\r\nmessage : "
+ request.responseText);
}
});


Comments