최신 게시글(JAVA)
2022.05.02 / 15:28

JSP + MyBatis + MySql 샘플

코코로
추천 수 37

JSP + MyBatis + MySql 샘플

참고: http://www.mybatis.org/core/ko/index.html

아래 순서로 설명.
1. MySql DB 구축
2. 웹앱 생성
3. MyBatis 설정
  3.1. 필요한 라이브러리 설치
  3.2. 환경 설정
  3.3. 맵퍼 생성
  3.4. JSP 연동
4. 웹 페이지 생성
5. 테스트

최종 폴더 구조:



1. MySql DB 구축
- 테스트용 계정을 아래와 같이 설정했다.
User name : "username"
Password : "password"

1) test 스키마를 생성한다.
mysql> create schema test;

2) users 테이블을 생성한다.
mysql> use test;

mysql> create table users (
`username` varchar(255) not null,
`password` varchar(255) not null,
`email` varchar(255) not null,
primary key (`username`)
) default charset=utf8;

3) user 를 생성한다.
mysql> create user 'username'@'localhost' identified by 'password';

4) test 스키마에 대한 권한을 설정한다.
mysql> grant all privileges on test.* to 'username'@'locahost';

2. 웹앱 생성
- 폴더 구조
+ $WEB_APP/
  + WEB-INF/
    + libs/
    - web.xml
  + index.jsp

web.xml 소스:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 metadata-complete="true" version="3.0">
 
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 
</web-app>

3. MyBatis 설정
3.1. 필요한 라이브러리 설치
- 다운로드

- 위 파일들을 다운로드 받아 $WEB_APP/WEB-INF/libs/ 에 복사한다.
!) MyBatis 폴더에 lib 폴더에 있는 파일들도 복사한다.
  • asm-3.3.1.jar
  • cglib-2.2.2.jar
  • commons-dbcp-1.4.jar
  • commons-logging-1.1.1.jar
  • commons-pool-1.6.jar
  • log4j-1.2.16.jar
  • mybatis-3.1.1.jar
  • mysql-connector-java-5.1.20-bin.jar
  • slf4j-api-1.6.2.jar
  • slf4j-log4j12-1.6.2.jar

3.2. 환경 설정
- mybatis 설정 파일인 mybatis-config.xml 파일을 생성한다.(파일 이름은 중요하지 않다)
!) com.sample.mybatis.config 패키지에 생성하였다.
!) 파일 내용: JDBC 설정만 들어 있다.
<?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="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/test"/>
    <property name="username" value="username"/>
    <property name="password" value="password"/>
   </dataSource>
  </environment>
 </environments>

</configuration>

3.3. 맵퍼 생성
- 필요한 파일들
  • User.java - 레코드 아이템
  • UserMapper.java - SQL 문 수행을 위한 인터페이스
  • UserMap.xml - SQL 문 맵퍼

 - 소스 코드들
com.sample.mybatis.dto.User.java:
package com.sample.mybatis.dto;

public class User {
 private String username;
 private String password;
 private String email;
 
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}
com.sample.mybatis.dao.UserMapper.java:
package com.sample.mybatis.dao;

import java.util.List;

import com.sample.mybatis.dto.User;

public interface UserMapper {
 public List<User> selectAllUsers();
 public User selectUser(String username);
 public void insertUser(User user);
 public void updateUser(User user);
 public void deleteUser(String username);
}
com.sample.mybatis.sqlmap.UserMap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.sample.mybatis.dao.UserMapper">

<select id="selectAllUsers" resultType="User">
 select username as username,
  password as password,
  email as email
 from users;
</select>

<select id="selectUser" parameterType="string" resultType="User">
 select username as username,
  password as password,
  email as email
 from users
 where username=#{username};
</select>

<insert id="insertUser" parameterType="User">
 insert into users (username, password, email)
  values (#{username}, #{password}, #{email});
</insert>

<update id="updateUser" parameterType="User">
 update users set
  password=#{password},
  email=#{email}
 where username=#{username}
</update>

<delete id="deleteUser" parameterType="string">
 delete from users
  where username=#{username}
</delete>

</mapper>

- mybatis-config.xml 에 추가
<?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>

 <!-- Type alias -->
 <typeAliases>
  <typeAlias alias="User" type="com.sample.mybatis.dto.User"/>
 </typeAliases>
 
 <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/test"/>
    <property name="username" value="username"/>
    <property name="password" value="password"/>
   </dataSource>
  </environment>
 </environments>

 <!-- UserMap.xml 등록 -->
 <mappers>
  <mapper resource="com/sample/mybatis/sqlmap/UserMap.xml" />
 </mappers>
</configuration>

3.4. JSP 연동
- 서버 시작시에 SqlSessionFactory 를 생성해야 한다.
- SqlSessionFactory 를 생성하는 서블릿을 생성한다.

com.sample.mybatis.config.MyBatisConfig.java : 서버 시작시 init 함수가 실행된다.
package com.sample.mybatis.config;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServlet;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisConfig extends HttpServlet {
 
 private static SqlSessionFactory sqlSessionFactory;
 
 public void init() {
  
  try {
   InputStream inputStream = Resources.getResourceAsStream("com/sample/mybatis/config/mybatis-config.xml");
   sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 public static SqlSessionFactory getSqlSessionFactory() {
  return sqlSessionFactory;
 }

 public static void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
  MyBatisConfig.sqlSessionFactory = sqlSessionFactory;
 }
}


- web.xml 설정 : load-on-startup 을 설정해 줘야 한다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 metadata-complete="true" version="3.0">
 
 <!-- MyBatis initializer 등록 -->
 <servlet>
 <servlet-name>MyBatisInitializer</servlet-name>
 <servlet-class>com.sample.mybatis.config.MyBatisConfig</servlet-class>
 
 <load-on-startup>1</load-on-startup>
 </servlet>
 
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 
</web-app>

4. 웹 페이지 생성
- User 레코드 생성, 수정, 삭제 할 수 있는 페이지 (validation 미포함)

user_control.jsp :
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.sample.mybatis.config.MyBatisConfig" %>
<%@ page import="com.sample.mybatis.dao.*" %>
<%@ page import="com.sample.mybatis.dto.*" %>
<%@ page import="org.apache.ibatis.session.*" %>
<%@ page import="java.util.*" %>

<%

// handle operation

if (request.getMethod().equalsIgnoreCase("POST")) {
 
 SqlSession sqlSession = MyBatisConfig.getSqlSessionFactory().openSession(true);
 try {
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 
  String subtype = request.getParameter("subtype");
  if (subtype.equals("create-user")) {
   User user = new User();
   user.setUsername(request.getParameter("username"));
   user.setPassword(request.getParameter("password"));
   user.setEmail(request.getParameter("email"));
   userMapper.insertUser(user);
  } else if (subtype.equals("modify-user")) {
   User user = new User();
   user.setUsername(request.getParameter("username"));
   user.setPassword(request.getParameter("password"));
   user.setEmail(request.getParameter("email"));
   userMapper.updateUser(user);
  } else if (subtype.equals("delete-user")) {
   userMapper.deleteUser(request.getParameter("username"));
  }
 } finally {
  sqlSession.close();
 }
}

// select users
List<User> users = null;

SqlSession sqlSession = MyBatisConfig.getSqlSessionFactory().openSession(true);
try {
 UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 
 users = userMapper.selectAllUsers();
 
} finally {
 sqlSession.close();
}
%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Control</title>
</head>
<body>

<h2>Create User</h2>
<form name="create-form" method="post">
<input type="hidden" name="subtype" value="create-user" />
Username: <input type="text" name="username" value="" /><br />
Password: <input type="password" name="password" value="" /><br />
Email: <input type="email" name="email" value="" /><br />
<input type="submit" value="Create" />
</form>

<h2>User List</h2>
<ul>
<%
if (users == null || users.size() == 0) {
 %><li>no user</li><%
} else {
 for (User user : users) {
%>
 <li style="border:solid 1px black;padding:4px;margin-bottom:5px;">
 <form name="modify-form" method="post">
 <input type="hidden" name="subtype" value="modify-user" />
 <input type="hidden" name="username" value="<%= user.getUsername() %>" />
 Username: <%= user.getUsername() %><br />
 Password: <input type="password" name="password" value="" /><br />
 Email: <input type="text" name="email" value="<%= user.getEmail() %>" /><br />
 <input type="submit" value="Modify" />
 </form>
 <form name="delete-form" method="post">
 <input type="hidden" name="subtype" value="delete-user" />
 <input type="hidden" name="username" value="<%= user.getUsername() %>" />
 <input type="submit" value="Delete" />
 </form>
 </li>
<%
 }
}
%>
</ul>

</body>
</html>
!) SqlSessionFactory.openSession() 함수에 true 를 인자로 주면 작업이 끝나면 자동으로 commit 한다.

5. 테스트