겉바속촉
[Ethereum] remix판으로 구동해보기 본문
-
Storage.sol 작성
-
compile
-
ganache 가동 (이더리움 네트워 구동 : 예 HTTP://127.0.0.1:7545 )
5. deploy
6. servlet 프로젝트 생성
7. index.html 작성
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="main" method="get">
<input type="hidden" name="sign" value="spon">
후원금 <input name="amount"> <input type="submit" value="후원하기">
</form>
</body>
</html>
8. MainServlet.java 작성 : (별명주기) @WebServlet("/main")
MainServlet.java
package web.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/main")
public class MainServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String sign = request.getParameter("sign");
if(sign !=null) {
}else { //리퀘스트 전달 개체
RequestDispatcher disp = request.getRequestDispatcher("error.jsp");
disp.forward(request, response);
}
}
}
그럼 이제 error.jsp 만들어주기
error.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
${errMsg }
</body>
</html>
다시 MainServlet으로 가셔서 다음과 같이 추가해주세요:)
다음을 또 추가
클래스 생성
이제 maven으로 해주기
source folder
EthereumSponService.java
package web.service;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.Uint;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.PersonalListAccounts;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.http.HttpService;
public class EthereumSponService {
public void service() {
try {
String amount=request.getParameter("amount");
// 이더리움 네트웍 접속...
//계약 주소 세팅
String contract="0x36Ca42AC6f89443170167e384cBA919A9FA20Cc1";
//이더리움 네트웍 접속
Web3j web3j=Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
//accounts 얻기
Admin admin = Admin.build(new HttpService("HTTP://127.0.0.1:7545"));
PersonalListAccounts personalListAccounts = admin.personalListAccounts().send();
List<String> addressList = personalListAccounts.getAccountIds();
//토탈 후원금 보기
contractGetCall(addressList, contract, web3j);
//후원금 적립
contractSetCall(amount, addressList, web3j, contract);
//토탈 후원금 보기
contractGetCall(addressList, contract, web3j);
}catch(Exception e) {
e.printStackTrace();
}
}else
{
// 침해대응코드
RequestDispatcher disp = request.getRequestDispatcher("error.jsp");
request.setAttribute("errMsg", "올바른 요청이 아닙니다");
disp.forward(request, response);
}
}
}
private void contractGetCall(List<String> addressList, String contract, Web3j web3j) throws Exception {
// get function 호출(block생성 안함)
Function function = new Function("get", Collections.emptyList(), Arrays.asList(new TypeReference<Uint>() {
}));
Transaction transaction = Transaction.createEthCallTransaction(addressList.get(0), contract,
FunctionEncoder.encode(function));
EthCall ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
List<Type> decode = FunctionReturnDecoder.decode(ethCall.getResult(), function.getOutputParameters());
System.out.println("ethCall.getResult() = " + ethCall.getResult());
System.out.println("getValue = " + decode.get(0).getValue());
System.out.println("getType = " + decode.get(0).getTypeAsString());
}
private void contractSetCall(String amount, List<String> addressList, Web3j web3j, String contract)
throws Exception {
// set function 호출
BigInteger amount_ = new BigInteger(amount);
Function function2 = new Function("add", Arrays.asList(new Uint(amount_)), Collections.emptyList());
EthGetTransactionCount ethGetTransactionCount = web3j
.ethGetTransactionCount(addressList.get(0), DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
Transaction transaction2 = Transaction.createFunctionCallTransaction(addressList.get(0), nonce,
Transaction.DEFAULT_GAS, null, contract, FunctionEncoder.encode(function2));
EthSendTransaction ethSendTransaction = web3j.ethSendTransaction(transaction2).send();
String transactionHash = ethSendTransaction.getTransactionHash();
// ledger에 쓰여지기 까지 기다리기.
Thread.sleep(2000);
System.out.println("transactionHash = " + transactionHash);
}
}
그냥 apply
web3j maven 구글링
2_Test/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>2_Test</groupId>
<artifactId>2_Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.web3j/core -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.2.0</version>
</dependency>
</dependencies>
</project>
여기까지 하고 나면 EthereumSponService에서 에러가 사라질 것 (import부분만)
request부분만 오류
그래서 다음과 같이 괄호안에 String amount 넣어주시고
그 아랫줄은 필요없으니까 지워주세요
그리고 그 아랫부분으로 가셔서
else if 문은 모두 지워주세요
즉 다음과 같이 표시한 부분을 날려주시면 됩니다
MainServlet.java로 가셔서 다음 표시한 부분을 추가해주세요
구동 전 가나슈 상태
block 1 클릭해서 created contract address 복사해서
EthereumSponService에다가 넣어주기\
그리고 메서드 맞는 지 확인해줄것
이제 구동해서 1을 후원해볼게요
그리고 가나슈에서 블록 생성되었는 지 확인해줄것
eclipse 콘솔창 확인
'IT일기(하반기) > ETHEREUM' 카테고리의 다른 글
[Ethereum] db에 넣어보기 (0) | 2020.08.07 |
---|---|
[Ethereum] 메타마스크 설치해서 vscode로 가나슈와 연결 (1) | 2020.08.03 |
[Ethereum] Remix 해보기 (1) | 2020.07.29 |
[Ethereum] 거래 영수증 분석하기 (0) | 2020.07.29 |
[Ethereum] ethereum 시작하기 (0) | 2020.07.29 |