JSP 에서 Mybatis 설정
가. 다운로드
http://blog.mybatis.org/p/products.html
나. mybatis 설정 방법
1) mybatis-3.4.4.jar : lib 폴더에 복사
2) MybatisManager.java : mybatis framework을 실행할 수 있는 세션 생성
3) sqlMapConfig.xml : mybatis 기본설정 파일
4) mapper 파일 : 실제 sql query 문장
다. 한줄 메모장
web.xml(배치기술서)
Controller
MemoController.java
Model
MemoDTO.java
MemoDAO.java
View
memo.jsp :ajax 요청 페이지, 메모입력
memo_list.jsp : 메모목록
memo_view.jsp : 메모 보기, 수정, 삭제 기능
1)CRUD
Create : insert
Read : select
Update : update
Delete : delete
2) 메모장 목록
memo_list.do (web.xml 에 매핑)
Controller
MemoController.java
Model
MemoDAO.java
MemoDTO.java
View
memo_list.jsp
list.do => MemoController.java => MemoDAO.java
=> 메모리스트 리턴 => request 객체에 저장 => memo_list.jsp 로 포워딩
3) 메모 저장
insert.do (web.xml 에 매핑)
drop table memo;
create table memo (
idx number not null PRIMARY KEY ,
writer VARCHAR2(50) not null,
memo VARCHAR2(100) not null,
post_date date default sysdate
);
insert into MEMO (IDX, WRITER, MEMO ) VALUES (1, 'kim', '첫번째 메모');
insert into MEMO (IDX, WRITER, MEMO ) VALUES (2, 'park', '두번째 메모');
select * from memo;
commit;
delete from memo;
-- nvl(A, B) 가 null 이면 B
select nvl(max(idx)+1, 1) from memo;
insert into memo(idx, writer, memo) values
((select nvl(max(idx)+1, 1) from memo) , 'park', '메모');
select * from memo order by idx;
commit;
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 지시어, xml directive -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 알리아스 설정 -->
<typeAliases>
<!-- typeAlias type="전체경로" alias="별칭" -->
<!-- <typeAlias type="emp.dto.EmpDTO" alias="e" /> -->
</typeAliases>
<!-- db연결 참조코드 -->
<!-- <environments default="">
<environment id="">
<transactionManager type="JDBC" />
<dataSource type="JNDI">
<property name="data_source"
value="java:comp/env/jdbc/myoracle" />
</dataSource>
</environment>
</environments> -->
<!--
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="test" />
<property name="password" value="test12" />
</dataSource>
</environment>
</environments>
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe" />
<property name="username" value="java" />
<property name="password" value="1111" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="/memo/mapper/memo.xml"/>
</mappers>
<!-- 실제 sql query -->
<!-- <mappers>
<mapper resource="emp/mapper/emp.xml" />
<mapper resource=
"student/mapper/student.xml" />
<mapper resource=
"student/mapper/dept.xml" />
<mapper resource=
"student/mapper/prof.xml" />
<mapper resource=
"student/mapper/lecture.xml" />
<mapper resource=
"memo/mapper/memo.xml" />
<mapper resource=
"board/mapper/board.xml" />
</mappers> -->
</configuration>
memo.xml
<?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">
<!-- memo.xml -->
<!-- 저장 프로시저 호출 방법 { call 프로시저이름(매개변수) } -->
<mapper namespace="memo">
<resultMap type="memo.dto.MemoDTO" id="memoMap" />
<resultMap type="memo.dto.MemoDTO" id="memo_list"/>
<select id="list" resultType="memo.dto.MemoDTO" >
select * from memo order by idx desc
</select>
<!--
#{변수} 입력매개변수(따옴표 포함)
${변수} 따옴표 포함되지 않음
parameterType 입력매개변수의 자료형(생략가능)
-->
<insert id="insert" parameterType="memo.dto.MemoDTO">
insert into memo(idx, writer, memo) values
((select nvl(max(idx)+1, 1) from memo) , #{writer}, #{memo} )
</insert>
<!--
<insert id="insertMemo">
{ call memo_insert(#{writer},#{memo} ) }
</insert> -->
<!-- <select id="listMemo"
resultType="memo.dto.MemoDTO">
select * from
memo order by idx desc
</select> -->
<!-- statementType
CALLABLE(저장프로시저용),
PREPARED(PreparedStatement), STATEMENT(Statement)
mode=OUT 출력매개변수
jdbcType 오라클의 자료형
javaType 자바의 자료형
resultMap 해시맵의 자료형(리턴타입)
Map<String,Object> map=new HashMap<String,Object>();
map.put("result", new ArrayList.....);
-->
<!-- <delete id="deleteMemo">
{ call memo_del( #{idx} ) }
</delete>
-->
</mapper>
class MybatisManager
package sqlmap;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisManager {
//싱글톤 패턴으로 SqlSessionFactory 생성
//SqlSessionFactoryBuilder => SqlSessionFactory
//=>SqlSession
//(sql 실행 객체 : JDBC의 Statement + Result 객체 )
private static SqlSessionFactory instance;
private MybatisManager() {} //private 생성자
public static SqlSessionFactory getInstance(){
Reader reader=null;
try {
// Java Resources의 src
//mybatis 설정파일 정보를 읽음
reader = Resources.getResourceAsReader(
"sqlmap/sqlMapConfig.xml");
//SqlSessionFactory 생성기
instance = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(reader!=null)reader.close();
}catch(Exception e){
e.printStackTrace();
}
}
return instance;
}
}
class MemoDTO
package memo.dto;
import java.sql.Date;
public class MemoDTO {
private int idx;
private String writer;
private String memo;
private Date post_date;
public MemoDTO() {
}
public MemoDTO(String writer, String memo) {
super();
this.writer = writer;
this.memo = memo;
}
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public Date getPost_date() {
return post_date;
}
public void setPost_date(Date post_date) {
this.post_date = post_date;
}
@Override
public String toString() {
return "MemoDTO [idx=" + idx + ", writer=" + writer + ", memo=" + memo + ", post_date=" + post_date + "]";
}
}
class MemoDAO
package memo.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import memo.dto.MemoDTO;
import sqlmap.MybatisManager;
public class MemoDAO {
public List<MemoDTO> listMemo(){
List<MemoDTO> list=null; //ArrayList 사용 안됨
//SqlSessionFactory 생성
//SqlSessionFactory로 SqlSession 생성
SqlSession session
=MybatisManager.getInstance().openSession();
//selectList("네임스페이스.태그의id")목록이 리턴됨
//selectList(), selectOne()
list=session.selectList("memo.list");
session.close();
return list;
}
public void insertMemo(MemoDTO dto) {
//SqlSession 객체 생성
SqlSession session=null;
try{
session=MybatisManager.getInstance().openSession();
// memo 네임스페이스의 insert 태그 호출
session.insert("memo.insert", dto);
session.commit();//auto commit이 아님
}catch(Exception e){
e.printStackTrace();
}finally{
if(session!=null) session.close();//SqlSession 반납
}
}
}
class MemoController
package memo;
import java.io.IOException;
import java.util.List;
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 member.MemberDTO;
import memo.dao.MemoDAO;
import memo.dto.MemoDTO;
//url mapping(현재 클래스외 url 을 연결시킴)
@WebServlet("/memo_servlet/*")
public class MemoController extends HttpServlet {
private static final long serialVersionUID = 1L;
//get 방식 호출
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//사용자가 요청한 url 정보에 따라 분기
String url =request.getRequestURL().toString();
//dao 객체 생성
MemoDAO dao=new MemoDAO();
if(url.indexOf("insert.do")!=-1){
MemoDTO dto=new MemoDTO();
dto.setWriter(request.getParameter("writer"));
dto.setMemo(request.getParameter("memo"));
dao.insertMemo(dto);
}else if(url.indexOf("list.do")!=-1){
//메모 목록이 리턴됨
List<MemoDTO> list =dao.listMemo();
//출력 페이지에서 공유할 변수 저장
request.setAttribute("list", list);
//페이지 이동(포워딩)
String page="/memo/memo_list.jsp";
RequestDispatcher rd=
request.getRequestDispatcher(page);
rd.forward(request, response);
}else if(url.indexOf("view.do")!=-1){
}else if(url.indexOf("del.do")!=-1){
}else if(url.indexOf("delete_all.do")!=-1){
}else if(url.indexOf("update.do")!=-1){
}
}
//post 방식 호출
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
memo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function(){ //페이지 로딩이 완료되면 자동 실행
list();
//id가 btnSave 인 버튼을 누르면 insert() 가 호출됨
$("#btnSave").click(function(){
insert();
});
});
function list(){
$.ajax({
type:"post",
url:"${path}/memo_servlet/list.do",
success:function(result){//콜백함수
//memo_list.jsp 에 출력된 html이 result 에 리턴됨
// id 가 result 인 태그에 목록이 출력됨
$("#result").html(result);
}
});
}
function insert(){
var writer =$("#writer").val();
var memo=$("#memo").val();
$.ajax({
type:"post",
url:"${path}/memo_servlet/insert.do",
data:{
writer:writer,
memo:memo
},
success:function(){
list();//입력 완료되면 리스트 갱신
}
});
}
</script>
</head>
<body>
<h2>한줄 메모장</h2>
이름 :<input id="writer">
메모 : <input id="memo">
<input type="button" id="btnSave" value="확인">
<!-- 메모 목록이 출력될 영역 -->
<div id="result"></div>
</body>
</html>
memo_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<table border="1">
<tr>
<th>번호</th>
<th>이름</th>
<th>메모</th>
<th>날짜</th>
</tr>
<!-- forEach var="개별값" items="집합데이터" -->
<c:forEach var="row" items="${list }">
<tr>
<td>${row.idx}</td> <!-- getIdx() 가 호출됨 -->
<td>${row.writer}</td>
<td>${row.memo }</td>
<td><fmt:formatDate value="${row.post_date }" type="date"/></td>
</tr>
</c:forEach>
</table>
.
한줄 메모장이름 : 메모 :
|
댓글 ( 4)
댓글 남기기