본문 바로가기

Learning/JSP

Mybatis 연동하기 (주소록 만들기1)

 

  • DAO 대신 MyBatis 사용하기 (DB연결, sql문 처리)


  • New Dynamic Web Project로 0_AddressMybatis 생성

  • WebContent에 address_my 폴더 생성후 addressInsert.jsp 만들기

 

addressInsert.jsp 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script src="../js/jquery-3.5.1.min.js"></script>

<script>

$(function(){

    $("#btn").on("click",function(){

        if($("#name").val()==""){

            alert("이름을 입력하세요");

            return false;

        }

        if($("#zipcode").val()==""){

            alert("우편번호을 입력하세요");

            return false;

        }

        if($("#addr").val()==""){

            alert("주소를 입력하세요");

            return false;

        }

        if($("#tel").val()==""){

            alert("전화번호를 입력하세요");

            return false;

        }

        frm.submit();

    });

})

function zipfinder(){

    window.open("zipAction.amy","","width=700 height=400");   

}

</script>

</head>

<body>

<a href="list.jsp">전체보기</a> <br>

<form action="insertAction.amy" method="post" name="frm" id="frm">

<table>

    <tr>

        <td colspan="2">주소록 등록하기</td>

    </tr>

    <tr>

        <td>이름</td>

        <td><input type="text" name="name" id="name" size=15></td>

    </tr>

    <tr>

        <td>우편번호 </td>

        <td><input type="text" name="zipcode" id="zipcode" size=10>

        <input type="button" name="search" value="검색" onclick="zipfinder()"></td>

    <tr>

        <td>주소

        <td colspan="2"><input type="text" name="addr" id="addr" size=30>

        </td>

    </tr>

    </tr>

        <td>전화번호</td>

        <td colspan="2"><input type="text" name="tel" id="tel" size=15></td>

    <tr>

        <td colspan="2">

        <input type="submit" value="등록">

        <input type="reset" value="취소"></td>

    </tr>

</table>

</form>

</body>

</html>

 

  • src에 org.addrMy.action 패키지 생성 후 InsertAction.java 서블릿 만들기.

  • 이 서블릿에 Mybatis를 연결할 것이다.

  • AddressVO 클래스의 vo객체를 생성하고 파라미터로 넘어온 값들을 저장할 것이다.

 


  • org.addrMy.model 패키지. AddressVO.java 생성

AddressVO.java 

package org.addrMy.model;

public class AddressVO {

    private int num;

    private String name;

    private String addr;

    private String tel;

    private String zipcode;

    

    public int getNum() {

        return num;

    }

    public void setNum(int num) {

        this.num = num;

    }

    public String getName() {

        return name == null ? "" : name.trim();

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getAddr() {

        return addr == null ? "" : addr.trim();

    }

    public void setAddr(String addr) {

        this.addr = addr;

    }

    public String getTel() {

        return tel == null ? "" : tel.trim();

    }

    public void setTel(String tel) {

        this.tel = tel;

    }

    public String getZipcode() {

        return zipcode == null ? "" : zipcode.trim();

    }

    public void setZipcode(String zipcode) {

        this.zipcode = zipcode;

    }

}

 

 


  • 이번에는 DAO를 만들지 않고 Mybatis를 이용하여 sql문을 처리한다.

  • org.addrMy.config 패키지를 생성하고 Configuration.xml 만들기 (New File)

 

 

 

Configuration.xml

(MyBatis-3-User-Guide_ko.pdf 에서 복사 붙여넣기)

https://kldp.net/fwko/release/3410-MyBatis-3-User-Guide_ko.pdf

 

<?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>

 <properties resource="org/addrMy/config/jdbc.properties"/>

  <environments default="development">

     <environment id="development">

     <transactionManager type="JDBC"/>

     <dataSource type="POOLED">

         <property name="driver" value="${driver}"/>

         <property name="url" value="${url}"/>

         <property name="username" value="${username}"/>

         <property name="password" value="${password}"/>

     </dataSource>

     </environment>

  </environments>

  <mappers>

    <mapper resource="org/addrMy/config/ObjectMapper.xml"/>

  </mappers>

 </configuration>


${변수} 는 어딘가에서 내보낸 값들이 저장된다. 어디서 내보낸 걸까?

같은 패키지 경로에 jdbc.properties를 New File로 생성한다.

 

jdbc.properties

driver = oracle.jdbc.driver.OracleDriver

url = jdbc:oracle:thin:@localhost:1521:xe

username = scott

password = 1234

 


 

https://mvnrepository.com/artifact/org.mybatis/mybatis/3.4.6

 

Maven Repository: org.mybatis » mybatis » 3.4.6

 

mvnrepository.com

에서 MyBatis.jar 파일을 다운받는다. 3.4.6버전이다. WEB-INF의 lib 폴더에 붙여넣는다.

 

 


 

org.addrMy.config 안에 MybatisManager.java 클래스를 생성한다.

 

MybatisManager.java

package org.addrMy.config;

import java.io.IOException;

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 {

    public static SqlSessionFactory sqlMapper;

    static {

        String resource="org/addrMy/config/Configuration.xml";

        Reader reader;

        try {

            reader=Resources.getResourceAsReader(resource);

            sqlMapper=new SqlSessionFactoryBuilder().build(reader);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static SqlSessionFactory getSqlMapper() {

        return sqlMapper;

    }

}

여기서 Resources는 ibatis라 적힌것을 임포트 해야한다.

 


 

InsertAction.java

package org.addrMy.action;

import java.io.IOException;

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.addrMy.config.MybatisManager;

import org.addrMy.model.AddressVO;

import org.apache.ibatis.session.ExecutorType;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

/**

 * Servlet implementation class InsertAction

 */

@WebServlet("/address_my/insertAction.amy")

public class InsertAction extends HttpServlet {

    private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public InsertAction() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        RequestDispatcher rd=request.getRequestDispatcher("addressInsert.jsp");

        rd.forward(request, response);

    }

    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        AddressVO vo=new AddressVO();

        vo.setName(request.getParameter("name"));

        vo.setAddr(request.getParameter("addr"));

        vo.setNum(Integer.parseInt(request.getParameter("num")));

        vo.setTel(request.getParameter("tel"));

        vo.setZipcode(request.getParameter("zipcode"));

        SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();

        SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);

sqlSession.insert("insertData", vo);

        sqlSession.commit();

response.sendRedirect("listAction.amy");

    }

}

 


 

org.addrMy.config 패키지 내에 ObjectMapper.xml 생성

Mybatis 가이드북에서 mapper.dtd 복사 붙여넣기

 

ObjectMapper.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">

 

 <mapper namespace="org.addrMy.config.ObjectMapper">

 

 <insert id="insertData" parameterType="org.addrMy.model.AddressVO">

  insert into address(num, name, zipcode, addr, tel)

  values(address_seq.nextval,#{name},#{zipcode},#{addr},#{tel})

 </insert>

 <!-- all select -->

 <select id="listData" resultType="org.addrMy.model.AddressVO">

    select * from address

 </select>

 

 <!-- count -->

 <select id="countData" resultType="Integer">

    select count(*) from address

 </select>

 </mapper>

 

ListAction.java

 

package org.addrMy.action;

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 org.addrMy.config.MybatisManager;

import org.addrMy.model.AddressVO;

import org.apache.ibatis.session.ExecutorType;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import sun.rmi.server.Dispatcher;

/**

 * Servlet implementation class ListAction

 */

@WebServlet("/address_my/listAction.amy")

public class ListAction extends HttpServlet {

    private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public ListAction() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        SqlSessionFactory sqlMapper=MybatisManager.getSqlMapper();

        SqlSession sqlSession=sqlMapper.openSession(ExecutorType.REUSE);

        List<AddressVO> arr=sqlSession.selectList("listData");

        int count=(Integer)sqlSession.selectOne("countData");

        request.setAttribute("arr", arr);

        request.setAttribute("count", count);

        RequestDispatcher rd=request.getRequestDispatcher("addrList.jsp");

        rd.forward(request, response);

    }

    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        doGet(request, response);

    }

}

 

 

addrList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<table>

<div align="left">

    <a href="insertAction.amy">글쓰기 <a/>/ 개수 (${count}) </span>

</div>

    <thead>

        <tr>

            <td>번호</td>

            <td>이름</td>

            <td>주소</td>

            <td>전화번호</td>

        </tr>

    </thead>

    <tbody>

    <c:forEach items="${arr}" var="arr">

        <tr>

            <td>${arr.num}</td>

            <td><a href="detail.do?num=${arr.num}">${arr.name}</a></td>

            <td>${arr.addr}</td>

            <td>${arr.tel}</td>

        </tr>

    </c:forEach>

    </tbody>

</table>

    <select name="field" id="field">

    <option value="name">이름</option>

    <option value="tel">전화</option>

    </select>

    <input type="text" name="word" id="word">

    <input type="button" value="검색" id="searchBtn">

</body>

</html>

ListAction.java를 실행하면 목록이 보인다.