ajax 통신

자바(Spring) 2020. 9. 6. 16:58
A라는 서비스에서 스크래핑해서

JSON 파일 저장후 

C라는 레포팅 서비스로 JSON파일 경로를 던저주는걸 개발중이다.

nodejs면 비동기로 때리면 끝나는데
스프링이니  ajax에 대한 결과를 alert이나 console.log밖에 안들어 온다

파일다 저장한 뒤에 페이지를 호출 해야된다.
 



JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

newFile zzzzzzzzzzz




<form id="add-form" action="" method="post">

<input id="input-submit" type="submit" value="보내기" />


 </form>


<script>

$("#add-form").submit( function(event){

   

         $.ajax({

        type: "GET", 

        url:"/insert.do",

        dataType:"text", 

        success : function(result){

        alert(result);

        location.href = "http://localhost?result=" +result;   

        },

        error : function(a, b, c){

        alert(a + b + c);

        }

})

});

</script>



</body>

</html>



컨트롤러 


/*

 * Copyright 2008-2009 the original author or authors.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package egovframework.example.sample.web;


import java.io.FileReader;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


import egovframework.example.sample.service.EgovSampleService;

import egovframework.example.sample.service.LombokVO;

import egovframework.example.sample.service.SampleDefaultVO;

import egovframework.example.sample.service.SampleVO;


import egovframework.rte.fdl.property.EgovPropertyService;

import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;


import javax.annotation.Resource;


import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.ui.ModelMap;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.ModelAttribute;

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.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.support.SessionStatus;

import org.springmodules.validation.commons.DefaultBeanValidator;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;



@Controller

public class EgovSampleController {

@RequestMapping(value = "/jsonList.do")

public String jsonList(SampleVO sampleVO) throws Exception {


System.out.println("jsonList : " );

return "sample/NewFile";

}


@ResponseBody

@RequestMapping("/insert.do")

public String insert() {

System.out.println("insert");

return "aaaaaaaaaaaaaaaaaaaa";

}

}



바쁘니간 우선 돌아가게 만들어 놓고

나중에 코드 보수 좀 해야곘다.



'자바(Spring)' 카테고리의 다른 글

AsyncRestTemplate Spring boot 비동기  (0) 2021.02.09
JSON 파일 파싱 스프링 java VO저장  (0) 2020.08.29
블로그 이미지

iesay

,

 

개발환경 : egov3.9

 이디러리움 샘플을 가지고 왔다.

nodejs는 자바스크립트 기반이니   json파싱은 일도 아닌데 ㅎㅎㅎ

스프링에서는 경험이 적다보니 시간이 좀 걸렸다

 

공유겸 정리해 놓을려구 한다.

 

해당 트렌젝션의 result값을 VO에 집어 넣고

출력하는 부분을 만들 예정이다.

 

 

ethscan.json 이더리움 송금 트랜젝션

 {
 "status":"1",
 "message":"OK",
 "result":[
  {
   "blockNumber":"4473164",
   "timeStamp":"1542787987",
   "hash":"0xac86d44f53a22e4b12853f5f8234f95b831e1521694c4072fd6a97b219ec3cb7",
   "nonce":"17012682",
   "data": {
    "blockHash":"0x4ee9b9d29f78f7aab230613f8827e9e070d5b60b2cd06d61e83b17aaaa5b1e67",
    "transactionIndex":"54",
    "from":"0x81b7e08f65bdf5648606c89998a9cc8164397647",
    "to":"0xff0797d06e8f9897b1d5066c10d9497ed7054a47"
   },
   "Price": [
    {
     "value":"1000000000000000000",
     "gas":"21000",
     "gasPrice":"1000000000"
    },
    {
     "value":"1000000000000000000",
     "gas":"21000",
     "gasPrice":"1000000000"
    },
    {
     "value":"1000000000000000000",
     "gas":"21000",
     "gasPrice":"1000000000"
    }
   ]
  }
 ]
}

 

 

Json 파싱은 이상한거 쓰지말고 org.json.simple 쓰는게 가장 좋다

pom.xml에 추가 하고

<dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
 </dependency>

 

 

 

VO

package egovframework.example.sample.service;

import java.util.List;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;


@Getter
@Setter
@ToString
public class LombokVO {
 


    private String blockNumber;
    private String timeStamp;
    private String hash;
    private String nonce;
    private String blockHash;
    private String transactionIndex;
    private String from;
    private String to;

   
    public Data data;
    class Data{
     private String blockHash;
     private String transactionIndex;
     private String from;
     private String to;
    }
    
    
    public List<Price> Price;
    
    class Price{
     private String value;
     private String gas;
     private String gasPrice;
    }  
}


 

 

 

컨트롤러

package egovframework.example.sample.web;

import java.io.FileReader;
import java.util.List;

import egovframework.example.sample.service.EgovSampleService;
import egovframework.example.sample.service.LombokVO;
import egovframework.example.sample.service.SampleDefaultVO;
import egovframework.example.sample.service.SampleVO;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springmodules.validation.commons.DefaultBeanValidator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


@Controller
public class EgovSampleController {
 
 
 @RequestMapping(value = "/jsonList.do")
 public String jsonList(SampleVO sampleVO) throws Exception { 
 Object jsonVO = new LombokVO();
 
   
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("C:\\work-space\\json-test\\jsonsample\\ethscan.json"));

 
    jsonVO =jsonObject.get("result");
   
   
   
 //System.out.println("");
 System.out.println("jsonList : " + jsonVO);
 
 return null;  
 } 

}

 

배열 형식일때는 Array로 VO클래스를 만들고

Object 형식일때는 List로 VO로 만들면 된다.

 

그 뒤로는 알아서 잘 밖힌다.

접근 할때는 일반 클래스 처럼 . 사용하여 접근하면 된다. 

 

 

'자바(Spring)' 카테고리의 다른 글

AsyncRestTemplate Spring boot 비동기  (0) 2021.02.09
ajax 통신  (0) 2020.09.06
블로그 이미지

iesay

,

라디오 버튼 제이쿼리

2020. 8. 24. 15:16

출처 :

https://codepen.io/jaehee/pen/PZKeRy

 

 

<style>
body {margin: 30px;}
body * { margin: 0; padding: 0;}
a {text-decoration: none;}
ul {list-style: none}
li.selected  { width: 500px; background-color: #ddd;}

</style>

<h1>First UL</h1>
<ul id="uldata">
    <li id="lidata"><a href="#none">Lorem ipsum dolor sit amet.</a></li>
    <li id="lidata"><a href="#none">Lorem ipsum dolor sit amet. Lorem ipsum dolor.</a></li>
    <li id="lidata"><a href="#none">Lorem ipsum dolor sit amet.</a></li>
    <li id="lidata"><a href="#none">Lorem ipsum dolor sit amet. Lorem ipsum dolor.</a></li>
</ul>
<br/>
<br/>

 

 

 

<script type="text/javascript">
(function(global, $){
    'use strict';

    var plugin = 'radioClass';
    $.fn[plugin] = $.fn[plugin] || function(className, context) {

            context = context || '';
            var _this = context ? this.closest(context) : this;
            _this.addClass(className);

            var $siblings = _this.siblings();
            $.each($siblings, function(index, item) {
                var _$sibling = $siblings.eq(index);
                if ( _$sibling.hasClass(className) ) {
                    _$sibling.removeClass(className);
                }
            });
            // jQuery 체이닝을 위한 this 반환 설정
            return this;

        }; // 끝: $.fn.radioClass

})(window, window.jQuery);

$(function () {
 console.log($(this.$ul));
    // 접근성을 위해 a 를 클릭하도록 합니다. (탭 포커스 이동시를 고려)
    var $ul = $('ul#uldata');
    $ul.on('click','li#lidata a', function (e) {

        e.preventDefault();
        // a 에 selected 가 되지 않도록 radioClass context 를 li 로 설정
        $(this).radioClass('selected', 'li');
    })
});
</script>

'' 카테고리의 다른 글

ubuntu nginx php mysql 구축  (0) 2021.03.03
DB튜닝 테이블에 데이터가 많은 경우  (0) 2021.01.31
GS인증(보안성)  (7) 2020.04.13
express + morgan  (0) 2019.04.01
promise  (0) 2019.03.28
블로그 이미지

iesay

,