ZipcodeSearch.WebContent.servlet.ZipcodeController
package servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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;
import model2.Action;
import model2.ZipcodeAction;
import model2.ZipcodeOkAction;
/**
* Servlet implementation class ZipcodeController
*/
@WebServlet("*.do")
public class ZipcodeController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
try {
request.setCharacterEncoding("utf-8");
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "/model2/error.jsp";
Action baction = null;
if(path.equals("/*.do") || path.equals("/zipcode.do")) {
baction = new ZipcodeAction();
baction.execute(request, response);
url = "/model2/zipcode.jsp";
} else if(path.equals("/zipcode_ok1.do")) {
baction = new ZipcodeOkAction();
baction.execute(request, response);
url = "/model2/zipcode_ok1.jsp";
} else if(path.equals("/zipcode_xml.do")) {
baction = new ZipcodeOkAction();
baction.execute(request, response);
url = "/model2/zipcode_xml.jsp";
} else if(path.equals("/zipcode_json.do")) {
baction = new ZipcodeOkAction();
baction.execute(request, response);
url = "/model2/zipcode_json.jsp";
} else if(path.equals("/zipcode_ajax.do")) {
baction = new ZipcodeAction();
baction.execute(request, response);
url = "/model2/zipcode_ajax.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ZipcodeSearch.WebContent.model2.zipcode_ajax
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
alert(dong);
});
});
</script>
</head>
<body>
<form>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
</form>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: './zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'text',
success: function(data) {
alert(data);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: './zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: './zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: './zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'json',
success: function(data) {
console.log('데이터 갯수 : ' + data.length);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: './zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'json',
success: function(data) {
console.log('데이터 갯수 : ' + data.length);
//console.log(data[0].zipcode);
//console.log(data[0].sido);
output = '<table border="1" width="800">';
$.each(data, function(index, item) {
output += '<tr>';
output += ' <td>' + item.zipcode + '</td>';
output += ' <td>' + item.sido + '</td>';
output += ' <td>' + item.gugun + '</td>';
output += ' <td>' + item.dong + '</td>';
output += ' <td>' + item.ri + '</td>';
output += ' <td>' + item.bunji + '</td>';
output += '</tr>';
});
output += '</table>';
$('#result').html(output);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
위에가 web 2.0버전으로 for문을 쓰는게 아니라 $.each를 사용해서
$.each(data, function(index, item) {
output += '<tr>';
output += ' <td>' + item.zipcode + '</td>';
output += ' <td>' + item.sido + '</td>';
output += ' <td>' + item.gugun + '</td>';
output += ' <td>' + item.dong + '</td>';
output += ' <td>' + item.ri + '</td>';
output += ' <td>' + item.bunji + '</td>';
output += '</tr>';
});
output += '</table>';
$('#result').html(output);
디자인을 추가하여 출력을 하였다.
for(var i=0; i<rowdatas.length; i++) {
var coldatas = rowdatas[i].split(',');
result += '<tr>';
result += ' <td>' + coldatas[0] + '</td>';
result += ' <td>' + coldatas[1] + '</td>';
result += ' <td>' + coldatas[2] + '</td>';
result += '</tr>';
}
result += '</table>';
console.log(result);
위와 같은 방식으로 사용하려 하였으나 위 방식을 사용하면 좀 더 실력있다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: 'http://192.168.0.48:8080/ZipcodeSearch/zipcode_json.do',
data: {
dong: dong
},
type: 'post',
dataType: 'json',
success: function(data) {
console.log('데이터 갯수 : ' + data.length);
//console.log(data[0].zipcode);
//console.log(data[0].sido);
output = '<table border="1" width="800">';
$.each(data, function(index, item) {
output += '<tr>';
output += ' <td>' + item.zipcode + '</td>';
output += ' <td>' + item.sido + '</td>';
output += ' <td>' + item.gugun + '</td>';
output += ' <td>' + item.dong + '</td>';
output += ' <td>' + item.ri + '</td>';
output += ' <td>' + item.bunji + '</td>';
output += '</tr>';
});
output += '</table>';
$('#result').html(output);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
위와 같이 AJAX 보안이 걸리면 상대방 IP주소로 접근해도 엑세스가 거부된다. 같은 서버에 있으면 가능하다. 구글 API는 가져가라고 풀어줘서 가능했던 것이다. 서버에서 풀어주는 방법과 강제로 가져오는 방법이 있다. 강제로 가져오는 방법도 알아야 하는데 이는 데이터 가져오는 방법에 사용된다.
http://192.168.0.48:8080/ZipcodeSearch/zipcode_json.do?dong=%EC%8B%A0%EC%82%AC
위와 같이 URL 접속하면 데이터를 받아 올 수 있다.
zipcodeproxy
zipcodeproxy.proxy
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import var="data" url="http://192.168.0.48:8080/ZipcodeSearch/zipcode_json.do">
<c:param name="dong" value="신사" />
</c:import>
${ data }
ZipcodeSearch.WebContent.model2.zipcode_ajax
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<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,minimum-scale=1.0,maximum-scale=1.0">
<title>Insert title here</title>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').on('click', function() {
var dong = $('#dong').val();
$.ajax({
url: '/zipcodeproxy/proxy.jsp',
data: {
dong: dong
},
type: 'post',
dataType: 'json',
success: function(data) {
console.log('데이터 갯수 : ' + data.length);
//console.log(data[0].zipcode);
//console.log(data[0].sido);
output = '<table border="1" width="800">';
$.each(data, function(index, item) {
output += '<tr>';
output += ' <td>' + item.zipcode + '</td>';
output += ' <td>' + item.sido + '</td>';
output += ' <td>' + item.gugun + '</td>';
output += ' <td>' + item.dong + '</td>';
output += ' <td>' + item.ri + '</td>';
output += ' <td>' + item.bunji + '</td>';
output += '</tr>';
});
output += '</table>';
$('#result').html(output);
},
error: function() {
alert('연결 실패');
}
});
});
});
</script>
</head>
<body>
동이름 : <input type="text" id="dong" size="25" maxlength="5" placeholder="동이름입력">
<button id="btn">우편번호 검색</button>
<br /><hr /><br />
<div id="result"></div>
</body>
</html>
url: '/zipcodeproxy/proxy.jsp',
proxy로 받아오는 값을 ajax로 연결하여 값을 받아 오게 된다
zipcodeproxy.proxy
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import var="data" url="http://192.168.0.48:8080/ZipcodeSearch/zipcode_json.do">
<c:param name="dong" value="${ param.dong }" />
</c:import>
${ data }
MyBatis
<- iBatis
http://blog.mybatis.org
1. log4j(for java))
- 프로그램의 log를 출력하는 라이브러리
- log4j.xml
2. MyBatis 전체에 환경파일
- myBatisConfig.xml (개발자가 이름 정함)
3. SQL Mapper 파일
- SQL 저장
- mapper.xml
myBatisEx01.log4j
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<!-- log를 출력하는 format -->
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1}:%-3L) %m%n" />
</layout>
</appender>
<root>
<!--
OFF - 로그 사용 안함
ERROR - 일반적 오류 발생
-->
<level value="DEBUG"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
myBatisEx01.myBatisConfig
<?xml version= "1.0" encoding ="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development1">
<environment id="development1">
<transactionManager type="JDBC" />
<dataSource type="POOLED" >
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:this:@localhost:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</dataSource>
</environment>
</environments>
</configuration>
myBatisEx01.myBatisMainEx01
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xm";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
sqlSession = sqlSessionFactory.openSession();
System.out.println("데이터베이스 연결됨");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
</mapper>
myBatisEx01.DeptTO
public class DeptTO {
private String deptno;
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
private String dname;
private String loc;
}
myBatisEx01.MyBatisMainEx01
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
DeptTO to = new DeptTO();
to.setDeptno("89");
to.setDname("연구");
to.setLoc("제주");
int result = sqlSession.insert("insert1", to);
System.out.println("결과 : " + result);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.MyBatisMainEx02
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
DeptTO to = new DeptTO();
to.setDeptno("91");
to.setDname("기획");
int result = sqlSession.update("update1", to);
System.out.println("결과 : " + result);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
</mapper>
myBatisEx01.MyBatisMainEx03
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
DeptTO to = new DeptTO();
to.setDeptno("89");
int result = sqlSession.delete("delete1", to);
System.out.println("결과 : " + result);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.MyBatisMainEx04
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
DeptTO to = new DeptTO();
to.setDeptno("97");
to.setDname("품질");
to.setLoc("강릉");
int result = sqlSession.update("mybatis1.update1", to);
//int result = sqlSession.update("mybatis2.update1", to);
System.out.println("결과 : " + result);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper1
<?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="mybatis1">
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
</mapper>
myBatisEx01.mapper2
<?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="mybatis2">
<update id="update1" parameterType="DeptTO" >
update dept2
set loc = #{loc}
where deptno = #{deptno}
</update>
</mapper>
myBatisEx01.MyBatisMainEx05
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx05 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
DeptTO to1 = (DeptTO)sqlSession.selectOne("select1");
System.out.println(to1.getDeptno());
System.out.println(to1.getDname());
System.out.println(to1.getLoc());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
<!-- 한개행 리턴, 여러행 리턴 -->
<select id="select1" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = 10
</select>
</mapper>
myBatisEx01.MyBatisMainEx05
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx05 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to1 = (DeptTO)sqlSession.selectOne("select1");
DeptTO to1 = (DeptTO)sqlSession.selectOne("select2", "20");
System.out.println(to1.getDeptno());
System.out.println(to1.getDname());
System.out.println(to1.getLoc());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
<!-- 한개행 리턴, 여러행 리턴 -->
<select id="select1" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = 10
</select>
<select id="select2" parameterType="String" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
</mapper>
myBatisEx01.MyBatisMainEx05
import java.io.IOException;
import java.io.InputStream;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx05 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to1 = (DeptTO)sqlSession.selectOne("select1");
//DeptTO to1 = (DeptTO)sqlSession.selectOne("select2", "20");
DeptTO to1 = new DeptTO();
to1.setDeptno("30");
to1 = (DeptTO)sqlSession.selectOne("select3", to1);
System.out.println(to1.getDeptno());
System.out.println(to1.getDname());
System.out.println(to1.getLoc());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
<!-- 한개행 리턴, 여러행 리턴 -->
<select id="select1" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = 10
</select>
<select id="select2" parameterType="String" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
<select id="select3" parameterType="DeptTO" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
</mapper>
myBatisEx01.MyBatisMainEx06
가져올 수량은 많은데 selectOne으로는 가져올 수 없는 수량이 되어 에러남
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx06 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to = sqlSession.selectOne("select4");
List<DeptTO> deptLists = sqlSession.selectList("select4");
for(DeptTO to : deptLists) {
System.out.println(to.getDeptno());
System.out.println(to.getDname());
System.out.println(to.getLoc());
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.MyBatisMainEx07
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to = sqlSession.selectOne("select4");
//ZipcodeTO to = sqlSession.selectOne("select4", "대치");
List<ZipcodeTO> deptLists = sqlSession.selectList("select5", "대치");
for(ZipcodeTO to : deptLists) {
System.out.println(to.getZipcode());
System.out.println(to.getSido());
System.out.println(to.getGugun());
System.out.println(to.getDong());
System.out.println(to.getRi());
System.out.println(to.getBunji());
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
<!-- 한개행 리턴, 여러행 리턴 -->
<select id="select1" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = 10
</select>
<select id="select2" parameterType="String" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
<select id="select3" parameterType="DeptTO" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
<select id="select4" resultType="DeptTO">
select *
from dept2
</select>
<select id="select5" parameterType="String" resultType="ZipcodeTO">
select *
from zipcode
where dong like #{ dong } || '%'
</select>
</mapper>
MyBatisEx01.MyBatisEx08
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
// mybatis - ibatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisMainEx08 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
// transaction
// autocommit
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to = sqlSession.selectOne("select4");
//ZipcodeTO to = sqlSession.selectOne("select4", "대치");
//List<ZipcodeTO> deptLists = sqlSession.selectList("select5", "대치");
List<HashMap<String, Object>> dataList = sqlSession.selectList("select6");
for(int i=0; i<dataList.size(); i++) {
HashMap<String, Object> map = dataList.get(i);
System.out.println(map.get("EMPNO"));
System.out.println(map.get("GRADE"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
}
}
myBatisEx01.mapper
<?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="mybatis">
<insert id="insert1" parameterType="DeptTO">
insert into dept2 (deptno, dname, loc)
value (#{deptno}, #{dname}, #{loc})
</insert>
<update id="update1" parameterType="DeptTO" >
update dept2
set dname = #{dname}
where deptno = #{deptno}
</update>
<delete id="delete1" parameterType="DeptTO">
delete
from dept2
where deptno = #{deptno}
</delete>
<!-- 한개행 리턴, 여러행 리턴 -->
<select id="select1" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = 10
</select>
<select id="select2" parameterType="String" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
<select id="select3" parameterType="DeptTO" resultType="DeptTO">
select deptno, dname, loc
from dept2
where deptno = #{deptno}
</select>
<select id="select4" resultType="DeptTO">
select *
from dept2
</select>
<select id="select5" parameterType="String" resultType="ZipcodeTO">
select *
from zipcode
where dong like #{ dong } || '%'
</select>
<select id="select6" resultType="java.util.HashMap">
select empno, ename, sal, grade
from emp e, salgrade s
where e.sal between s.losal and s.hisal
</select>
</mapper>
MyBatisEx02
MyBatisEx02.mybatis
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.List" %>
<%@ page import="model1.DeptTO" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(is);
System.out.println("설정이 성공적으로 호출됨");
sqlSession = sqlSessionFactory.openSession(true);
System.out.println("데이터베이스 연결됨");
//DeptTO to = sqlSession.selectOne("select4");
//ZipcodeTO to = sqlSession.selectOne("select4", "대치");
List<DeptTO> deptLists = sqlSession.selectList("select1");
for(DeptTO to : deptLists) {
System.out.println(to.getDeptno());
System.out.println(to.getDname());
System.out.println(to.getLoc());
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("[에러] " + e.getMessage());
} finally {
if(sqlSession != null) sqlSession.close();
if(is != null) try { is.close();} catch(IOException e) {};
}
%>
MyBatisEx02.myBatisConfig
<?xml version= "1.0" encoding ="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development1">
<environment id="development1">
<transactionManager type="JDBC" />
<dataSource type="POOLED" >
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="model1/mapper.xml" />
</mappers>
</configuration>
MyBatisEx02.model1.DeptTO
package model1;
public class DeptTO {
private String deptno;
private String dname;
private String loc;
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
MyBatisEx02.model1.mapper
<?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="mybatis">
<select id="select1" resultType="model1.DeptTO">
select deptno, dname, loc
from dept2
where deptno=10
</select>
</mapper>
'Web & Mobile > JSP' 카테고리의 다른 글
Lecture 32 - JSP(1) JDBC API 사용법(Java와 SQL 연동) (0) | 2023.06.20 |
---|---|
Lecture 62 - JSP(20) MyBatis 이용한 게시판, 사진이 나오는 앨범 게시판 (0) | 2019.06.14 |
Lecture 60 - JSP(18) JSTL, 우편번호검색 (0) | 2019.06.12 |
Lecture 59 - JSP(17) EL, <%= %>, EL을 Model1 게시판에 적용, JSTL (0) | 2019.06.11 |
Lecture 58 - JSP(16) Mail, Authentication, MyAuth, MailSender (0) | 2019.06.10 |
댓글