겉바속촉
[Ethereum] db에 넣어보기 본문
이번에는 db에 넣어보려고합니다:)
프로젝트 하나 생성해주세요
저는 8_IITP_etherem으로 dynamic web project 생성했습니다
그리고 maven으로 바꾸어주신후에!! 시작해볼게요 !^^!
우선 먼저 각 파일들의 위치가 중요하기 때문에
다 만들고나서의 상태를 캡쳐한 사진을 먼저 보고 시작해주세요
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/1.0.2/ReactRouter.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
<title>React App</title>
</head>
<body>
<div id="root" ></div>
<script type="text/babel" src="index.jsx" />
</body>
</html>
2. index.jsx
var {Component} = React;
var {Router, Route, IndexRoute, Link} = ReactRouter;
class Main extends Component{
render(){
return(
<div>
<h1>BlockChain Study</h1>
<ul className="header" >
<li><Link exact to="/">Home</Link></li>
<li><Link to="/bitcoin">Bitcoin</Link></li>
<li><Link to="/ethereum">Ethereum</Link></li>
<li><Link to="/hyperledger">Hyperledger</Link></li>
</ul>
<div className="content">
{this.props.children}
</div>
</div>
);
}
}
class Home extends Component{
render(){
return(
<div>
<h2>HELLO</h2>
<p>안녕하세요? BlockChain Java 웹 예제(dApp)입니다. 잘해보죠~!!!</p>
</div>
);
}
}
class BitcoinNetwork extends Component{
state={
blockNumber:0,
acc1_balance:0,
acc2_balance:0
}
bit_network_connect=()=>{
axios.get('/bit_network/connect')
.then((response)=>{
console.log(response);
this.setState({
blockNumber:response.data.blockNumber,
acc1_balance:response.data.acc1_balance,
acc2_balance:response.data.acc2_balance
});
})
.catch((error)=>{
console.log(error);
});
}
send=()=>{
alert(this.amount.value);
axios.post('/bit_network/send',{"amount":this.amount.value})
.then((response)=>{
console.log(response);
this.setState({
blockNumber:response.data.blockNumber,
acc1_balance:response.data.acc1_balance,
acc2_balance:response.data.acc2_balance
});
})
.catch((error)=>{
console.log(error);
});
}
render(){
return(
<div>
<h2>BitcoinNetwork</h2>
<p><button onClick={this.bit_network_connect}>연결</button></p>
<br/>
block number : {this.state.blockNumber} <br/>
acc1 balance : {this.state.acc1_balance} <br/>
acc2 balance : {this.state.acc2_balance} <br/>
<br/>
<div>acc1가 acc2에게 {' '}
<input placeholder='송금량' ref={ref=>this.amount=ref} />BTC {' '}
<button onClick={this.send} > 보내기</button><br/>
</div>
</div>
);
}
}
/* 이더리움 연동 요청 */
class EthereumNetwork extends Component{
createUser=(event)=>{
window.open("createUser.html",'_blank','width=800,height=550');
}
send1=(event)=>{
alert(this.state.name);
event.preventDefault();
axios.post('main',{"name":this.state.name,"sign":this.state.team})
.then((response)=>{
console.log(response);
this.setState({
result1:response.data.result,
message2:response.data.message,
});
})
.catch((error)=>{
console.log(error);
});
}
send2=(event)=>{
alert(this.state.name);
event.preventDefault();
axios.post('main',{"name":this.state.name,"sign":this.state.team})
.then((response)=>{
console.log(response);
this.setState({
result2:response.data.result,
message2:response.data.message,
});
})
.catch((error)=>{
console.log(error);
});
}
send3=(event)=>{
alert(this.token.value);
event.preventDefault();
axios.post('main',{"name":this.token.value,"sign":this.state.team})
.then((response)=>{
console.log(response);
this.setState({
result3:response.data.result,
message3:response.data.message,
});
})
.catch((error)=>{
console.log(error);
});
}
state = {
name: "React",
team : "team",
result1 : 0,
result2 : 0,
result3 : 0,
message1 : "no message",
message2 : "no message",
message3 : "no message"
};
onChangeTeam1 =(event)=> {
console.log(event.target.name);
this.setState({team:event.target.name});
}
onChangeValue1 =(event)=> {
this.setState({name:event.target.value});
console.log(this.state.team);
}
onChangeTeam2 =(event)=> {
console.log(event.target.name);
this.setState({team:event.target.name});
}
onChangeValue2 =(event)=> {
this.setState({name:event.target.value});
console.log(this.state.team);
}
onChangeTeam3 =(event)=> {
console.log(event.target.name);
this.setState({team:event.target.name});
}
render(){
return(
<div>
<div>
<h2>EthereumNetwork 연결 해보세요</h2>
<button onClick={this.createUser} name="team1"> 회원가입 </button>
</div>
<br/><br/>
<div>
<a href="#team1"> 1조 </a> |
<a href="#team2"> 2조 </a> |
<a href="#team3"> 3조 </a> |
<a href="#team4"> 4조 </a> |
<a href="#team5"> 5조 </a> |
<a href="#team6"> 6조 </a> |
</div>
<br/><br/>
<div id="team1">
<a name="team1"> 1조 [아마곗돈] </a>
<button onClick={this.onChangeTeam1} name="team1"> 1조 서비스 받기 </button>
<br/><br/>
<form onSubmit={this.send1}>
<div onChange={this.onChangeValue1}>
<input type="radio" value="노트북계" name="team1" /> 노트북계
<input type="radio" value="쌍수계" name="team1" /> 쌍수계
<input type="radio" value="여행계" name="team1" /> 여행계
</div>
<input type="submit" value="입금하기" />
</form>
{this.state.message1} : 총 곗돈 : {this.state.result1}
</div>
<div id="team2">
<a name="team2"> 2조 [키다리아저씨]</a>
<button onClick={this.onChangeTeam2} name="team2"> 2조 서비스 받기 </button>
<br/>
<form onSubmit={this.send2}>
<div onChange={this.onChangeValue2}>
<input type="radio" name="team2" value="밀알복지재단"/>밀알 복지 재단<br/>
<input type="radio" name="team2" value="삼육재단"/>삼육 재단<br/>
<input type="radio" name="team2" value="한국유기동물복지 협회"/>한국 유기동물 복지 협회<br/>
</div>
<input type="submit" value="후원하기"/>
</form>
{this.state.message2} : 총 후원금 : {this.state.result2}
</div>
<div id="team3">
<a name="team3"> 3조 </a>
<button onClick={this.onChangeTeam3} name="team3"> 3조 서비스 받기 </button>
<br/>
<b>장동건</b>님과의 거래진행중...
<br/>
<br/>
<img alt=""
src="https://funshop.akamaized.net/abroad/025/12727/nike-adapt-bb_0.jpg"
width="400" border="1"/>
<br/>
<br/> 상품명 : 나이키
<br/> 거래 가격 : 5,000원
<br/>
<br/>
<form onSubmit={this.send3}>
<b>토큰</b>
<input ref={ref=>this.token=ref} /><input type="submit" value="토큰 보내기"/>
</form>
{this.state.message3} : 총 토큰: {this.state.result3}
</div>
<div>
<a name="team4"> 4조 </a>
</div>
<div>
<a name="team5"> 5조 </a>
</div>
<div>
<a name="team6"> 6조 </a>
</div>
</div>
);
}
}
class HyperledgerNetwork extends Component{
render(){
return(
<div>
<h2>HyperledgerNetwork 연결 해보세요</h2>
</div>
);
}
}
ReactDOM.render(
(<Router>
<Route path="/" component={Main} >
<Route path="bitcoin" component={BitcoinNetwork}/>
<Route path="ethereum" component={EthereumNetwork} />
<Route path="hyperledger" component={HyperledgerNetwork} />
<IndexRoute component={Home} />
</Route>
</Router>)
,document.getElementById("root")
);
3. index.css
body{
background-color: #FFCC00;
padding:20px;
margin:0;
}
h1,h2,p,ul,li{
font-family:sans-serif;
}
ul.header li{
display: inline;
list-style-type:none;
margin:0;
}
ul.header{
background-color: #111;
padding: 0;
}
ul.header li a{
color:#FFF;
font-weight: bold;
text-decoration: none;
padding: 20px;
display: inline-block;
}
.content{
background-color: #FFF;
padding: 20px;
}
.content h2{
padding: 0;margin:0;
}
.content li{
margin-bottom: 10px;
}
a:hover{
background-color: #0099ff;
}
#team1{
background-color: #ccccff;
padding: 20px;margin:10px;
}
#team2{
background-color: #ccffcc;
padding: 20px;margin:10px;
}
#team3{
background-color: #ffcccc;
padding: 20px;margin:10px;
}
4. MainServlet.java
package web.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.web3j.*;
import web.dao.UserDAO;
import web.service.Team1Service;
import web.service.Team2Service;
import web.service.Team3Service;
@WebServlet("/main")
public class MainServlet extends HttpServlet {
Team1Service service1;
Team2Service service2;
Team3Service service3;
public void init() {
try {
service1=new Team1Service();
service2=new Team2Service();
service3=new Team3Service();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
process(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
process(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("process....");
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out=response.getWriter();
BufferedReader br=request.getReader();
JSONObject obj=(JSONObject)JSONValue.parse(br);
JSONObject result_obj=new JSONObject();
System.out.println(obj);
String sign=(String) obj.get("sign");
System.out.println(sign);
if(sign==null){
System.out.println("sign is null");
}else{
if(sign.equals("createUser")){
UserDAO t=new UserDAO();
String id=(String) obj.get("id");
String pw=(String) obj.get("p_w");
String name=(String) obj.get("name");
String wallet_path=getServletContext().getRealPath("/")+"wallet\\";
String result=t.createUser(id,pw,name,wallet_path);
System.out.println(result);
if(result!=null){
setResultMsg(out, result_obj, result, "User가 생성되었습니다");
}else{
setResultMsg(out, result_obj, 0, "회원 가입 처리 오류");
}
}else if(sign.equals("login")){
UserDAO t=new UserDAO();
String id=(String) obj.get("id");
String pw=(String) obj.get("p_w");
String result=t.readUser(id, pw);
System.out.println(result);
if(result!=null){
setResultMsg(out, result_obj, result, "로그인되었습니다");
}else{
setResultMsg(out, result_obj, 0, "다시 로그인 해주세요");
}
}else if(sign.equals("team1")){
String gye=(String) obj.get("name");
System.out.println(gye);
service1.saveGyeddon(gye);
Object result=service1.totalGyeddon(gye);
if(result!=null){
setResultMsg(out, result_obj, result, gye+"를 선택하셨습니다");
}else{
setResultMsg(out, result_obj, 0, "처리오류");
}
}else if(sign.equals("team2")){
String candidate=(String) obj.get("name");
System.out.println(candidate);
service2.voteForCandidate(candidate);
Object result=service2.totalVotesFor(candidate);
if(result!=null){
setResultMsg(out, result_obj, result, candidate+"를 후원하셨습니다");
}else{
setResultMsg(out, result_obj, 0, "처리오류");
}
}else if(sign.equals("team3")){
String token=(String) obj.get("name");
System.out.println(token);
service3.setNumber(token);
Object result=service3.getNumber();
obj=new JSONObject();
if(result!=null){
setResultMsg(out, result_obj, result, token+"이 전달되었습니다");
}else{
setResultMsg(out, result_obj, 0, "처리오류");
}
}
}
}
private void setResultMsg(PrintWriter out, JSONObject obj, Object result, String message) {
obj.put("result", result);
obj.put("message", message);
out.print(obj);
}
}
아마 오류가 나서 빨간 줄들이 그어져있을 겁니다:)
dependency 추가해줄게요!!
5. pom.xml에 다음 추가
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
</dependencies>
6. 그리고 각각의 team1, team2, team3에 service를 붙여서 class 생성해줍니다
7. UserDao.java 작성
package web.dao;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Optional;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.WalletUtils;
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.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;
import org.web3j.utils.Convert.Unit;
import org.xml.sax.SAXException;
public class UserDAO {
public void transferEther(String address) throws Exception {
Web3j web3 = Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
System.out.println("Successfuly connected to Ethereum");
System.out.println("Balance: " + Convert.fromWei(web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).send().getBalance().toString(), Unit.ETHER));
Admin admin= Admin.build(new HttpService("HTTP://127.0.0.1:7545"));
PersonalListAccounts personalListAccounts = admin.personalListAccounts().send();
List<String> addressList = personalListAccounts.getAccountIds();
// Get the latest nonce of Sender
String senderAddress=addressList.get(0);
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(senderAddress, DefaultBlockParameterName.LATEST).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
// Recipient address
String recipientAddress = address;
// Value to transfer (in wei)
BigInteger value = Convert.toWei("10", Unit.ETHER).toBigInteger();
// Gas Parameters
BigInteger gasLimit = BigInteger.valueOf(21000);
BigInteger gasPrice = Convert.toWei("1", Unit.GWEI).toBigInteger();
// Prepare the rawTransaction
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
nonce,
gasPrice,
gasLimit,
recipientAddress,
value);
// Sign the transaction
Credentials credentials=Credentials.create("b354032e302daab331f19d8192dc39e586b9aa9e645a943787b069321d879dbf");// sender의 private key
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
// Send transaction
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).send();
String transactionHash = ethSendTransaction.getTransactionHash();
System.out.println("transactionHash: " + transactionHash);
// Wait for transaction to be mined
Optional<TransactionReceipt> transactionReceipt = null;
do {
System.out.println("checking if transaction " + transactionHash + " is mined....");
EthGetTransactionReceipt ethGetTransactionReceiptResp = web3.ethGetTransactionReceipt(transactionHash).send();
transactionReceipt = ethGetTransactionReceiptResp.getTransactionReceipt();
Thread.sleep(3000); // Wait 3 sec
} while(!transactionReceipt.isPresent());
System.out.println("Transaction " + transactionHash + " was mined in block # " + transactionReceipt.get().getBlockNumber());
System.out.println("Balance: " + Convert.fromWei(web3.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance().toString(), Unit.ETHER));
}
public String createUser(String id, String pw, String name, String wallet_path) {
String pri_key="",pub_key="",address="";
try {
//str이 결국 지갑의 이름이 되는 것
String str=WalletUtils.generateNewWalletFile(pw, new File(wallet_path), true);
System.out.println(str);
Credentials credentials = WalletUtils.loadCredentials(pw, wallet_path+str);
ECKeyPair keyPair=credentials.getEcKeyPair();
pri_key=keyPair.getPrivateKey().toString()+"";
pub_key=keyPair.getPublicKey().toString()+"";
address=credentials.getAddress();
System.out.println("pri_key:"+pri_key);
System.out.println("pub_key:"+pub_key);
System.out.println("address:"+address);
transferEther(address);
}catch(Exception e) {
e.printStackTrace();
}
StringBuffer result=new StringBuffer();
Connection con=null;
PreparedStatement st=null;
int rs=0;
try {
con = EConnection.getConnection(this,wallet_path);
st = con.prepareStatement("insert into Users(id,pw,name,pri_key,pub_key,address) values ( ?, ? , ? , ?, ?, ?) ");
st.setString(1, id);
st.setString(2, pw);
st.setString(3, name);
st.setString(4, pri_key);
st.setString(5, pub_key);
st.setString(6, address);
rs = st.executeUpdate();
result.append("insert row: "+rs);
} catch (SQLException e1) {
e1.printStackTrace();
result.append("요청처리에러발생");
}
if ( st != null ) try { st.close(); }catch(SQLException e){}
if ( con != null ) try { con.close(); }catch(SQLException e){}
return result.toString();
}
public String readUser(String id, String pw) {
StringBuffer result=new StringBuffer();
Connection con=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
con = EConnection.getConnection(this);
st = con.prepareStatement("select * from users where id=? and pw=? ");
st.setString(1, id);
st.setString(2, pw);
rs = st.executeQuery();
if ( rs.next() ) {
result.append("pri_key: "+rs.getString("pri_key"));
result.append("\npub_key: "+rs.getString("pub_key"));
result.append("\naddress: "+rs.getString("address"));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
result.append("요청처리에러발생");
}
if ( rs != null ) try { rs.close(); }catch(SQLException e){}
if ( st != null ) try { st.close(); }catch(SQLException e){}
if ( con != null ) try { con.close(); }catch(SQLException e){}
return result.toString();
}
}
8. EConnection.java 작성
package web.dao;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class EConnection {
static String wallet_path;
public static Connection getConnection(Object o) {
return getConnection(o,wallet_path);
}
public static Connection getConnection(Object o, String wallet_path) {
EConnection.wallet_path=wallet_path;
Connection con=null;
Properties properties = new Properties();
try {
String str=wallet_path+"..\\WEB-INF\\config\\dbconn.properties";
System.out.println(str);
properties.load(new FileReader(str));
String driver = properties.getProperty("jdbc.driver");
System.out.println(driver);
//properties.load( o.getClass().getClassLoader().getResourceAsStream(str));
} catch (IOException e) {
System.out.println("DB 정보 로드 실패");
return null;
}
String driver = properties.getProperty("jdbc.driver");
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
try {
Class.forName(driver);
con=DriverManager.getConnection(url,username,password);
}catch(Exception e){
e.printStackTrace();
System.out.println("DB 연결 오류");
return null;
}
return con;
}
}
9. dbconn.properties 작성
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = root
jdbc.password = 1234
10. MySQL 켜서 TABLE 작성해줄게요
mysql> show databases;
mysql> use test
mysql> create table users(
-> id varchar(50),
-> pw varchar(50),
-> name varchar(50),
-> pri_key varchar(500),
-> pub_key varchar(500),
-> address varchar(500),
-> balance int(50),
-> token int(50)
-> )
-> ;
그럼 다음과 같이 나옵니다:)
mysql> describe users;
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id | varchar(50) | YES | | NULL | |
| pw | varchar(50) | YES | | NULL | |
| name | varchar(50) | YES | | NULL | |
| pri_key | varchar(500) | YES | | NULL | |
| pub_key | varchar(500) | YES | | NULL | |
| address | varchar(500) | YES | | NULL | |
| balance | int(50) | YES | | NULL | |
| token | int(50) | YES | | NULL | |
+---------+--------------+------+-----+---------+-------+
11. 퀀텀 DB에서 확인해볼게요
잘 생성이 되었네요:)
12. 가나슈 가동해주세요
13. REMIX도 가동해주세요
14. 그래서 각각 TEAM별로 SOL파일을 만들어 줍니다
15. GANACHE와 연동을 시키기 위해 ENVIRONMENT를 다음과 같이 바꿔주셔야합니다
그리고 포트번호는 가나슈가 7545이기 때문에 바꿔주셔야겠쥬??
16. DEPLOY한 후 가나슈로 가서 BLOCK이 생성되었나 확인하고
생성된 BLOCK 클릭해서 CONTRACT address를 복사해서 eclipse의 각각의 파일에 반영해주세요
포트번호도 7545로 바꿔줄게요:)
17. createUser.html 작성
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/grid.css" type="text/css" media="screen">
<script src="js/jquery-1.6.2.min.js" type="text/javascript"></script>
<!-- 리액트 관련-->
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="createUser" />
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel" src="createUser.jsx"></script>
</body>
</html>
18. createUser.jsx 작성
class CreateUser extends React.Component{
send=()=>{
axios.post('main',{"sign":"createUser","id":this.id.value,"p_w":this.pw.value,"name":this.name.value})
.then((response)=>{
console.log(response);
alert(response.data.message);
window.opener = null;
window.open('', '_self');
window.close();
})
.catch((error)=>{
console.log(error);
});
}
render(){
const main={
width:'500px',
height:'300px',
margin:'30px auto'
}
const first={
width:'400px',
height:'400px',
boxShadow:'0 0 0 1px rgba(14,41,57,0.12),0 2px 5px rgba(14,41,57,0.44),inset 0 -1px 2px rgba(14,41,57,0.15)',
float:'left',
padding:'10px 50px 0',
background:'linear-gradient(#fff,#f2f6f9)'
}
const label={
fontSize:'17px'
}
const input={
width:'400px',
padding:'5px',
marginTop:'10px',
marginBottom:'10px',
borderRadius:'5px',
border:'1px solid #cbcbcb',
boxShadow:'inset 0 1px 2px rgba(0,0,0,0.18)',
fontSize:'16px'
}
const select={
padding:'13px'
}
const input_type_submit={
background:'linear-gradient(to bottom,#22abe9 5%,#36caf0 100%)',
boxShadow:'inset 0 1px 0 0 #7bdcf4',
border:'1px solid #0F799E',
color:'#fff',
fontSize:'19px',
fontWeight:'700',
cursor:'pointer',
textShadow:'0 1px 0 #13506D'
}
const center={
align:'center'
}
return (
<div style={main}>
<div style={first}>
<h1>회원 가입</h1>
<h4>Please fill all entries.</h4><hr/>
<label style={label}>ID :</label>
<input style={input} placeholder="아이디" ref={ref=>this.id=ref}/>
<label style={label}>PW :</label>
<input style={input} placeholder="패스워드" ref={ref=>this.pw=ref}/>
<label style={label}>NAME :</label>
<input style={input} placeholder="이름" ref={ref=>this.name=ref}/>
<input style={input_type_submit} onClick={this.send} type="submit" value="Send"/>
</div>
</div>
)
}
}
ReactDOM.render(
<CreateUser / > ,
document.getElementById('createUser')
);
20. 서버 restart 해주세요:)
다음과 같이 결과창이 나오게 되는데요
1조 서비스 받기 click -> 노트북계 click -> 입금하기 click
그리고 다음과 같이 총 곗돈도 바뀌는 지 확인해주세요:)
클릭하면서 잘 되는 지 확인 하기 위해서 fn + F12 단축키를 눌러서 검사창의 Console부분을 보면서
실행시켜보세요:)
이제 회원가입을 확인해볼게요~
우선 우리가 wallet 폴더를 만들어주셔야해요
다음 경로로 설정해주세요:)
서버 restart
회원가입 click
그리고 wallet 폴더 보시면 다음과 같이 정보가 저장되있는 것을 확인할 수 있쥬!!
terminal에서도 볼게요
table이 깨지긴 했지만 다음과 같이 잘 출력이 되네요:)
바로 json형태의 지갑이 생성된 것입니다
user를 추가해볼게요
겉바속촉 추가할 거에요 !^^!
table을 확인해보니 잘 들어와있네요:)
'IT일기(하반기) > ETHEREUM' 카테고리의 다른 글
[Ethereum] 로그인 기능 추가 (2) | 2020.08.07 |
---|---|
[Ethereum] 메타마스크 설치해서 vscode로 가나슈와 연결 (1) | 2020.08.03 |
[Ethereum] remix판으로 구동해보기 (2) | 2020.07.31 |
[Ethereum] Remix 해보기 (1) | 2020.07.29 |
[Ethereum] 거래 영수증 분석하기 (0) | 2020.07.29 |