developers.kakao.com에서 오픈API 가져오기
로그인 -> 내 애플리케이션 -> 애플리케이션 추가하기 -> 플렛폼 설정 -> 플렛폼 등록 ( 내 ip주소로 작성 )
앱 키 복사 -> 원하는 코드 가져와서 작성후 앱 키 붙여넣기
paho-mqtt 라이브러리
●map02.html
<!DOCTYPE html>
<html>
<head>
<title>MQTT Web Client</title>
<style type="text/css">
body {
font-family: "Open Sans", sans-serif;
}
</style>
</head>
<body>
<H1>MQTT Web Subscribe Client</H1><br><br>
<h3>please enter Server host and port.</h3><br>
<label for="text_host">host</label> : <input type="text" id="text_host" /><br>
<label for="text_port">port</label> : <input type="text" id="text_port" /><br>
<label for="text_topic">topic</label> : <input type="text" id="text_topic" /><br><br>
<input type="button" id="mqtt_con_but" value="Connect" onclick="beginMQTTweb()">
<br><br>
connection status : <div id="con_status" style="display:inline">disconnect</div><br>
Message : <div id="msg" style="display:inline"></div><br>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=80752ce2966a591509701d0b0d88c2c7"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
<script type="text/javascript">
function beginMQTTweb() {
if (document.getElementById("mqtt_con_but").value == "Connect") {
host = document.getElementById("text_host").value;
port = document.getElementById("text_port").value;
topic = document.getElementById("text_topic").value;
if ((host == "") || (port == "")) {
alert("Please enter host and port.");
} else {
mqclient = new Paho.MQTT.Client(host, Number(port), "clientId_pcm");
// set callback handlers
mqclient.onConnectionLost = onConnectionLost;
mqclient.onMessageArrived = onMessageArrived;
// connect the client
mqclient.connect({
onSuccess : onConnect,
onFailure : onFailure
});
}
} else if (document.getElementById("mqtt_con_but").value == "Disconnect") {
mqclient.disconnect();
document.getElementById("con_status").textContent = "disconnect";
document.getElementById("mqtt_con_but").value = "Connect";
console.log("Disconnect");
}
}
function onFailure() {
alert("Please enter host and port again.")
}
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
document.getElementById("con_status").textContent = "connect";
mqclient.subscribe(topic);
document.getElementById("mqtt_con_but").value = "Disconnect";
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
document.getElementById("con_status").textContent = "disconnect";
document.getElementById("mqtt_con_but").value = "Connect";
}
}
// called when a message arrives
function onMessageArrived(message) {
var msg = JSON.parse(message.payloadString);
console.log("onMessageArrived:" + msg.lat +":" + msg.lng);
//document.getElementById("msg").textContent = message.payloadString;
document.getElementById("msg").innerHTML =msg.lat +":" + msg.lng;
// -- 지도 서비스
var mapContainer = document.getElementById('map'), // 지도를 표시할 div
mapOption = {
center: new kakao.maps.LatLng(msg.lat, msg.lng), // 지도의 중심좌표
level: 3 // 지도의 확대 레벨
};
var map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다
// 마커가 표시될 위치입니다
var markerPosition = new kakao.maps.LatLng(msg.lat, msg.lng);
// 마커를 생성합니다
var marker = new kakao.maps.Marker({
position: markerPosition
});
// 마커가 지도 위에 표시되도록 설정합니다
marker.setMap(map);
// 아래 코드는 지도 위의 마커를 제거하는 코드입니다
// marker.setMap(null);
}
</script>
<hr>
<div id="map" style="width:100%;height:350px;"></div>
</body>
</html>
mosquitto.conf파일을 VSCode로 열어서 web소켓 ( 490번줄에 ) 다음과같이 코드 작성 ▼
#websockets_log_level 0
listener 9001
protocol websockets
log_type all
websockets_log_level 1023
connection_messages true
9001번 포트 열어주기 ▼
브라우저에서 9001번으로 Connect누르면 연결 된다.
MQTT에서 위도 / 경도 입력하고 Publish누르면 웹브라우저에서 위치가 뜬다
mysql 접속하기
●board.sql
-- tb_user
CREATE TABLE tb_user (
userid VARCHAR(30) NOT NULL, -- 아이디
username VARCHAR(50) NOT NULL, -- 이름
password VARCHAR(20) NOT NULL, -- 비밀번호
use_yn VARCHAR(5) NOT NULL, -- 사용여부
PRIMARY KEY (userid)
);
insert into tb_user values('admin','관리자','manager', 'Y');
insert into tb_user values('guest','사용자','guest', 'Y');
insert into tb_user values('guest2','사용자2','guest2', 'Y');
CREATE TABLE tb_board (
idx INT NOT NULL AUTO_INCREMENT, -- 자동증가(게시물아이디)
title VARCHAR(100) NOT NULL, -- 제목
contents VARCHAR(4000) NOT NULL, -- 내용
count INT, -- 조회수
writer VARCHAR(30) NOT NULL, -- 등록자
indate DATETIME DEFAULT NOW() NOT NULL, -- 등록일
PRIMARY KEY (idx)
);
insert into tb_board(title, contents, count, writer)
values('전자정부 표준프레임워크','전자정부 표준프레임워크',0,'개발자');
select * from tb_board;
CREATE TABLE tb_reply (
idx INT NOT NULL, -- 게시물아이디
seq INT NOT NULL, -- 순번
reply VARCHAR(1000) NOT NULL, -- 댓글
writer VARCHAR(50) NOT NULL, -- 작성자
indate DATETIME DEFAULT NOW() NOT NULL, -- 작성일
PRIMARY KEY (idx,seq)
);
CREATE TABLE tb_attach (
idx INT NOT NULL, -- 게시물아이디
seq INT NOT NULL, -- 순번
filename VARCHAR(256), -- 파일명
writer VARCHAR(50) NOT NULL, -- 등록자
indate DATETIME DEFAULT NOW() NOT NULL, -- 등록일
PRIMARY KEY (idx,seq)
);
●context-datasource.xml
<!-- Mysql (POM에서 commons-dbcp, mysql-connector-java 관련 라이브러리 설정 ) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/iot" />
<property name="username" value="root"/>
<property name="password" value="12345"/>
</bean>
resources -> egovframework -> spring 폴더
context-datasource.xml 에서 사용할 DB(Mysql) 주석을 풀어준다
dbcp - data base connection pool
pom.xml 에서도 DB(Mysql) 주석 풀어주기 - 자동 다운로드됨
◆DAO없이 Mapper로 처리하기
board_SQL.xml에서 설정한 id값과 BoardMapper.java의 이름이 같아야 한다
DAO를 만들지않고 interface기반의 mapper클래스의 함수명과 sql.xml의 id값을 동일하게 해야함
BoardService.java - 인터페이스
BoardServiceimple.java - ▲ 상속받아서 구현하는 클래스
●web.xml
●dispatcher-servlet.xml
egovframework 안에있는 것들중 annotation이 있는 class들을 메모리에 올려 scan해서 필요할때 사용한다
●context-mapper.xml
<!-- MapperConfigurer setup for MyBatis Database Layer with @Mapper("deptMapper") in DeptMapper Interface -->
<bean class="egovframework.rte.psl.dataaccess.mapper.MapperConfigurer">
<property name="basePackage" value="egovframework.example.**.service.impl" />
</bean>
** 를 붙여줘서 모든것 읽게하기
index.jsp 로 브라우저에 검색하면 list.do가 실행됨 ▼
@Controller
public class BoardController {
/** EgovSampleService */
@Resource(name = "boardService")
private BoardService boardService;
@RequestMapping(value="/list.do")
public String list(BoardVO boardvo, Model model) throws Exception{
// DAO연동 해서 데이터 가져오는 작업
// Controller - Service - DAO
List<?> list = boardService.selectBoardList(boardvo);
model.addAttribute("list",list);
return "board/list"; //forward방식
}
Controller에서 list.do를 받고 board/list.jsp 로 foward함 ▼
BoardController.java
@RequestMapping(value="/mgmt.do" , method = RequestMethod.GET) // 1개의 경로로 2개의 일을 하기위해 하나는 get방식, 하나는 post방식
public String mgmt(Model model) throws Exception{
// DAO연동 해서 데이터 가져오는 작업
// Controller - Service - DAO
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
Calendar cal = Calendar.getInstance();
String strToday = sdf.format(cal.getTime());
model.addAttribute("strToday",strToday);
return "board/mgmt"; // mgmt.jsp
}
@RequestMapping(value="/mgmt.do" , method = RequestMethod.POST) // 1개의 경로로 2개의 일을 하기위해 하나는 get방식, 하나는 post방식
public String mgmt2(/*@ModelAttribute("boardVO")*/BoardVO boardvo, Model model) throws Exception{
return "redirect:/list.do"; // redirect 등록완료시 list로 돌아가기
}
하나의 경로로 두가지 일을 처리하기 위해 하나는 get(화면) , 하나는 post방식(등록)으로 한다
boardvo에서 가져와야되는데 @ModelAttribute 방법도 있음
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="egovframework.example.board.service.impl.BoardMapper">
<select id = "selectBoardList" parameterType="boardVO" resultType="boardVO">
select * from tb_board
</select>
<insert id = "insertBoard" parameterType="boardVO">
insert into tb_board(title, contents, count, writer, indate) values(
#{title},#{contents},#{count, jdbcType=VARCHAR},#{writer},NOW())
</insert>
</mapper>
insert하는 쿼리문 만들기 ▼ BoardMapper 에 쿼리문을 처리할 코드 작성
BoardMapper
@Mapper("boardMapper")
public interface BoardMapper { // DAO
List<?> selectBoardList(BoardVO searchVO) throws Exception;
void insertBoard(BoardVO boardVO) throws Exception;
}
BoardService.java에도 동일하게해주기
imple에서 메소드 오버라이딩
contoller
'Spring' 카테고리의 다른 글
Spring - mysql 연동 환경설정 (0) | 2021.05.24 |
---|---|
Android에서 연동 (0) | 2021.04.30 |
카메라 사용 (0) | 2021.04.14 |
MONGO + MQTT로 브라우저LED제어 (0) | 2021.04.07 |
Spring 게시판 (0) | 2021.03.31 |