20220414 수업안온날
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>home</title>
</head>
<body>
<div style="padding:10px">
<h3>판매자 홈, 파일위치:templates/seller_home.html</h3>
<hr />
<h3>주문내역</h3>
<table border="1">
<tr>
<th>주문번호</th>
<th>주문수량</th>
<th>주문일짜</th>
<th>물품이름</th>
<th>물품가격</th>
<th>주문자</th>
<th>주문자연락처</th>
</tr>
<tr th:each="tmp : ${list2}">
<td th:text="${tmp.bno}"></td>
<td th:text="${tmp.bcnt}"></td>
<td th:text="${tmp.bregdate}"></td>
<td th:text="${tmp.ItemIname}"></td>
<td th:text="${tmp.ItemIprice}"></td>
<td th:text="${tmp.MemberUname}"></td>
<td th:text="${tmp.MemberUphone}"></td>
<tr>
</table>
<hr />
<h3>물품목록</h3>
<hr />
<a th:href="@{/seller/insertitem}">물품등록</a>
<form th:action="@{/seller/home}" method="get">
<input type="text" name="txt" placeholder="검색어" />
<input type="submit" value="검색" />
</form>
<table border="1">
<tr>
<th>번호</th>
<th>물품코드</th>
<th>물품명</th>
<th>가격</th>
<th>수량</th>
<th>등록일</th>
<th>버튼</th>
</tr>
<tr th:each="tmp, idx : ${list}">
<td th:text="${idx.count}"></td>
<td>
<a th:href="@{/seller/itemselectone(code=${tmp.icode})}"
th:text="${tmp.icode}"></a>
</td>
<td th:text="${tmp.iname}"></td>
<td th:text="${tmp.iprice}"></td>
<td th:text="${tmp.iquantity}"></td>
<td th:text="${tmp.iregdate}"></td>
<td>
<button th:onclick="|javascript:handleUpdate('${tmp.icode}')|">수정</button>
<button th:onclick="|javascript:handleDelete('${tmp.icode}')|">삭제</button>
</td>
</tr>
</table>
<th:block th:each="i : ${#numbers.sequence(1, pages)}">
<a th:href="@{/seller/home(page=${i}, txt=${param.txt})}"
th:text="${i}"></a>
</th:block>
</div>
<script src="https://unpkg.com/[email protected]/dist/mqtt.min.js"></script>
<script>
const state = {
message : '', // 보낼 메세지
client : '' , // 접속한 클라이언트 객체
options : {
clean : true, //세션 초기화
reconnectPeriod : 20000, // 주기적인 접속 시간
// 고유값 ex)d200, d212 등
clientId : 'd200_'+ new Date().getTime(),
username : 'ds606', // 아이디
password : 'ds606', // 암호
},
topic : 'ds/class606/#',
qos : 0, // 0부터 2까지의 숫자
};
const url = 'ws://1.234.5.158:11884';
try {
state.client = mqtt.connect(url, state.options);
console.log(state.client);
state.client.on('connect', () => {
console.log('connect success!!');
});
state.client.on('error', () => {
console.log('connect error!!');
});
state.client.on('message',(topic, message) => {
console.log(topic, JSON.parse(message));
location.reload(); //F5을 누름
});
state.client.subscribe(state.topic, {qos:state.qos}, (error, res) => {
if(error) {
console.log('subscribe topic error', error);
return;
}
console.log('subscribe success', res);
});
}
catch(e){
console.log('mqtt error', e);
}
/////////////////////////////////////////////////////////////
function handleUpdate(no) {
// GET으로 삭제 처리 주소창을 바꿈
location.href="/ROOT/seller/updateitem?code=" + no;
}
function handleDelete(no) {
if(confirm('삭제할까요?')){
console.log(no);
// GET으로 삭제 처리 주소창을 바꿈
// location.href="/ROOT/seller/deleteitem?code=" + no;
// POST으로 처리
//<form th:action="@{/seller/deleteitem}" method="post">
var form = document.createElement("form");
form.method="post";
form.action="/ROOT/seller/deleteitem";
//<input type="text" name="code" value="전달되는 번호" />
var input = document.createElement("input");
input.name="code";
input.value=no;
// 시큐리티를 csrf 토큰값 전송용
var input1 = document.createElement("input");
input1.type="hidden";
input1.name="_csrf";
input1.value='[[${_csrf.token}]]';
// input type을 form태그에 추가
form.appendChild(input);
form.appendChild(input1);
// form document에 추가
document.body.appendChild(form);
// <input type="submit">를 누름
form.submit();
}
}
</script>
</body>
</html>
package com.example.restcontroller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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.RestController;
import com.example.entity.BuyEntity;
import com.example.entity.BuyProjection;
import com.example.entity.ItemEntity;
import com.example.entity.MemberEntity;
import com.example.jwt.JwtUtil;
import com.example.repository.BuyRepository;
@RestController
@RequestMapping(value = "/api/buy")
public class BuyRestController {
@Autowired BuyRepository bRepository;
@Autowired JwtUtil jwtUtil;
// { bcnt:2, item:{icode: 3}} + headers token으로 전송됨.
@RequestMapping(value = "/insert2",
method = { RequestMethod.POST },
consumes = { MediaType.ALL_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> buyInsert2Post(
@RequestHeader(name = "token") String token,
@RequestBody BuyEntity buyEntity){
Map<String, Object> map = new HashMap<String, Object>();
try {
// 토큰에서 이메일 추출
String email = jwtUtil.extractUsername(token);
// 회원엔티티 객체 생성 및 이메일 추가
MemberEntity memberEntity = new MemberEntity();
memberEntity.setUemail(email);
// 주문엔티티에 추가
buyEntity.setMember(memberEntity);
// 저장소를 이용해서 DB에 추가
bRepository.save(buyEntity);
map.put("status", 200);
}
catch(Exception e) {
e.printStackTrace();
map.put("status", 0);
}
return map;
}
// 127.0.0.1:9090/ROOT/api/buy/insert
// { bcnt:2, icode: 3, uemail:'b3'}
@RequestMapping(value = "/insert",
method = { RequestMethod.POST },
consumes = { MediaType.ALL_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> buyInsertPost(
@RequestBody Map<String, Object> buy){
System.out.println(buy.toString());
BuyEntity buyEntity = new BuyEntity();
buyEntity.setBcnt(Long.parseLong( buy.get("bcnt").toString() ));
ItemEntity itemEntity = new ItemEntity();
itemEntity.setIcode(
Long.parseLong(buy.get("icode").toString()));
buyEntity.setItem( itemEntity);
MemberEntity memberEntity = new MemberEntity();
memberEntity.setUemail((String) buy.get("uemail"));
buyEntity.setMember( memberEntity );
bRepository.save(buyEntity);
Map<String, Object> map = new HashMap<String, Object>();
map.put("status",200);
return map;
}
// { bcnt:2, item:{icode: 3}, member:{uemail:'b3'}}
@RequestMapping(value = "/insert1",
method = { RequestMethod.POST },
consumes = { MediaType.ALL_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> buyInsertPost(
@RequestBody BuyEntity buyEntity){
System.out.println(buyEntity.toString());
Map<String, Object> map = new HashMap<String, Object>();
bRepository.save(buyEntity);
map.put("status",200);
return map;
}
// 주문 1개 조회
// 127.0.0.1:9090/ROOT/api/buy/selectone?bno=8
@RequestMapping(value = "/selectone",
method = { RequestMethod.GET },
consumes = { MediaType.ALL_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> buyInsertGET(
@RequestParam(name = "bno") long bno ){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println(bno);
//BuyEntity buy = bRepository.findById(bno).orElse(null);
//System.out.println(buy.toString());
BuyProjection buy = bRepository.findByBno(bno);
map.put("result",buy);
map.put("status",200);
return map;
}
// 127.0.0.1:9090/ROOT/api/buy/selectlist?uemail=b3
@RequestMapping(value = "/selectlist",
method = { RequestMethod.GET },
consumes = { MediaType.ALL_VALUE },
produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> buySelectGET(
@RequestParam(name = "uemail") String uemail){
Map<String, Object> map = new HashMap<String, Object>();
List<BuyProjection> buy = bRepository.findByMember_uemail(uemail);
//System.out.println(buy.toString());
map.put("result",buy);
map.put("status",200);
return map;
}
}
<template>
<div>
<h3>주문하기</h3>
주문할 물품명 : <input type="text" v-model="state.itemno" /><br />
주문 수량 : <input type="text" v-model="state.buycnt" /><br />
<button @click="handleBuy">주문하기</button>
</div>
</template>
<script>
import mqtt from 'mqtt';
import { onMounted, reactive } from 'vue';
import axios from 'axios';
export default {
setup () {
const state = reactive({
itemno : 22,
buycnt : 10,
token : sessionStorage.getItem("TOKEN"),
message : '', // 보낼 메세지
client : '' , // 접속한 클라이언트 객체
host : '1.234.5.158', //서버주소
port : 11884, // web용 포트번호
options : {
clean : true, //세션 초기화
reconnectPeriod : 20000, // 주기적인 접속 시간
// 고유값 ex)d200, d212 등
clientId : 'd200_'+ new Date().getTime(),
username : 'ds606', // 아이디
password : 'ds606', // 암호
},
topic : 'ds/class606/#',
qos : 0, // 0부터 2까지의 숫자
});
const handleBuy = async() => {
const url = `/ROOT/api/buy/insert2`;
const headers = {
"Content-Type":"application/json",
"token":state.token
}
const body = {
bcnt : state.buycnt,
item : {
icode: state.itemno
}
}
const response = await axios.post(url, body, {headers});
console.log(response.data);
if(response.data.status=== 200){
console.log('주문성공');
// 신호전송 구현....
sendMessage();
}
}
const createConnection = () => {
const url = `ws://${state.host}:${state.port}`;
try {
state.client = mqtt.connect(url, state.options);
console.log(state.client);
state.client.on('connect', () => {
console.log('connect success!!');
});
state.client.on('error', () => {
console.log('connect error!!');
});
state.client.on('message',(topic, message) => {
console.log(topic, JSON.parse(message));
});
}
catch(e){
console.log('mqtt error', e);
}
};
const sendMessage = () => {
// json object => string : JSON.stringify( )
// string => json object : JSON.parse( )
const payload = JSON.stringify({
userid : 'd200',
msg : state.message
});
// 보낼 토픽, 보내는 내용(문자), QOS(0~2)
state.client.publish('ds/class606/d200', payload, 0, error => {
if(error) {
console.log('publish error', error);
return;
}
});
}
onMounted(()=>{
createConnection();
});
return {state, handleBuy}
}
}
</script>
<style lang="scss" scoped>
</style>
Author And Source
이 문제에 관하여(20220414 수업안온날), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@gegus1220/20220414-수업안온날저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)