경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Passing Javascript object and object list to Spring controller 

Passing one Java object from Spring controller to Javascript is quite straightforward, all we have to do is add Jackson dependency in POM file. If the request is for JSON object, Spring automatically converts the Java object to JSON. 

When we need to pass Javascript object or object list to Spring controller which will convert this Javascript object or list to Java object or object list, this also can be done using Jackson. First we have to add Jackson dependency to POM file: 

<dependency>

      <groupId>org.codehaus.jackson</groupId>

      <artifactId>jackson-mapper-asl</artifactId>

      <version>1.9.13</version>

</dependency>

With this Spring will be able to perform the automatic conversion to Java object. The Java object has to use JsonIgnoreProperties annotation so it'll exclude this class name and make it possible to conform to exact JSON format: 

@JsonIgnoreProperties(ignoreUnknown = true)

public class Person {

      private String name;

       public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }      

}

When sending a single object (not list) that Spring controller will accept as a Java object, the JSON format has to be only pair of curly braces with properties inside , avoid using JSON.stringify() which actually adds one more property with object name and Jackson can't match. Following is the Javascript code snippet to pass an object from Javascript to Spring controller:

var person = {"name":"John"};

 $.ajax({

            url:"/abc/addPerson",

            type: 'POST',

            data:  person,             

            dataType: "html",          

            contentType: 'application/json',

            mimeType: 'application/json',

            success: function(data){ 

                console.log(data);              

                return false;     

            } 

        });

And in Spring controller:

@RequestMapping(value = "/addPerson",

    method = RequestMethod.POST)

    public @ResponseBody

    String addPerson(

            @RequestBody Person person)

            throws ParseException, IOException {

        log.debug("Adding new person");

        try {

           // perform add operation

            return "Successfully added person";

        } catch (Exception ex) {

            // 

        }

    }

Note that the parameter is with @RequestBody, @RequestParam didn't work for me.

Now, when sending a list of Javascript person object, on Spring controller using Person List will not work because Jackson cannot parse a list, it needs an object to perform parsing. To achieve this we have to create an object which will hold the persons list and Jackson will simply transform it to Java list of Person object. The class will look like this:

@JsonIgnoreProperties(ignoreUnknown = true)

public class PersonList {   

    List<Person> persons;    

    public List<Person> getPersons() {

        return persons;

    }

    public void setPersons(List<Person> persons) {

        this.persons= persons;

    } 

}

Now the JSON should have this persons block which will have all persons with properties. Using JSON.stringify()  will simply do this: 

var persons= [];

var person1 = {"name":"John"};

var person2 = {"name":"Doe"};

persons.push(person1);

persons.push(person2);

persons = JSON.stringify({

            'persons' : persons 

        });    

 $.ajax({

            url:"/abc/addPersons",

            type: 'POST',

            data:  persons,             

            dataType: "html",          

            contentType: 'application/json',

            mimeType: 'application/json',

            success: function(data){ 

                console.log(data);              

                return false;      

            } 

        });


In the controller: 

@RequestMapping(value = "/addPersons",

    method = RequestMethod.POST)

    public @ResponseBody

    String addPersons(

            @RequestBody PersonList persons)

            throws ParseException, IOException {

        log.debug("Adding new persons");

        try {

           // perform add operation

            return "Successfully added persons";

        } catch (Exception ex) {

            // 

        } 

    }

That's all, it'll now get the list of Person object in PersonList class.


[출처] https://www.linkedin.com/pulse/passing-javascript-object-list-spring-controller-rashedul-hasan-khan
본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
26 [bootstrap] spring 프로젝트에 bootstrap 적용 file 졸리운_곰 2017.01.29 164
25 eGov 표준프레임워크(전자정부프레임워크) 공통 컴포넌트 사용법 : Common Component file 졸리운_곰 2017.01.29 1030
» Passing Javascript object and object list to Spring controller 졸리운_곰 2017.01.23 92
23 뷰에 모델(Model) 전달 file 졸리운_곰 2017.01.22 128
22 CentOS에서 Apache Tomcat 설치하기 졸리운_곰 2017.01.18 490
21 Spring MVC Tiles Plugin with Example file 졸리운_곰 2017.01.15 1384
20 Spring MVC Tiles 3 Integration Tutorial file 졸리운_곰 2017.01.15 173
19 Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse file 졸리운_곰 2017.01.15 194
18 MyBatis 에서 한 insert 태그로 여러 Insert문 수행 졸리운_곰 2016.12.09 112
17 Web App Architecture - the Spring MVC - AngularJs stack file 졸리운_곰 2016.11.20 208
16 Introduction to Angular 2 with Spring MVC file 졸리운_곰 2016.11.20 676
15 Migrating a Spring Web MVC application from JSP to AngularJS file 졸리운_곰 2016.11.20 114
14 스프링(Spring) MVC 프레임워크(Model View Controller Framework) file 졸리운_곰 2016.11.16 151
13 JSP 정리 졸리운_곰 2016.09.11 332
12 JSP 요약 정리 file 졸리운_곰 2016.09.11 1294
11 전자정부 eGov 프레임워크 모바일 실행환경 Upgrade 가이드 file 졸리운_곰 2016.08.02 327
10 전자정부 eGov 프레임워크 개발프레임워크 개발환경 졸리운_곰 2016.08.02 474
9 표준프레임워크 실행환경 3.5 졸리운_곰 2016.08.02 172
8 전자정부 표준프레임워크 3.5 기반 개발 시작하기(Getting Started) file 졸리운_곰 2016.08.02 291
7 스프링(Spring) MVC 프레임워크(Model View Controller Framework) file 졸리운_곰 2016.07.31 103
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED