board53.sql

--board53.sql
select * from tab;
select * from board53; 

create table board53(
    board_num number(38) primary key
  , board_name varchar2(50) not null
  , board_pass varchar2(30) not null
  , board_subject varchar2(100) not null
  , board_content varchar2(4000) not null
  , board_re_ref number 
  , board_re_lev number 
  , board_re_seq number 
  , board_readcount number 
  , board_date date 
);

create sequence board53_num_seq
                increment by 1 start with 1 nocache;

 

pom.xml - Maven configuration / Dependencies 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>sbboard</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>sbboard</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<!-- jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.4</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

application.properties

# port 
server.port=80

# view resolver
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

# oracle
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=spring
spring.datasource.password=spring123

# mybatis
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

# DTO Alias
#mybatis.type-aliases-package=com.example.demo.model

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>
	<!-- Alias is not applied in Spring Boot -->
	<!-- <typeAliases>
		<typeAlias type="com.example.demo.model.BoardBean" alias="board"></typeAlias>
	</typeAliases> -->	
</configuration>

DataAccessConfig.java

package com.example.demo.model;

import java.util.Date;

import org.apache.ibatis.type.Alias;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Alias("board")
public class BoardBean {

	private int board_num;
	private String board_name;
	private String board_pass;
	private String board_subject; 
	private String board_content; 
	private int board_re_ref; 
	private int board_re_lev; 
	private int board_re_seq; 
	private int board_readcount; 
	private String board_date; 
	
}

board.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="boardns">

	<!-- Save -->
	<insert id="board_insert" parameterType="board">
		insert into board53
		(board_num,board_name,board_pass,board_subject,
		board_content,board_re_ref,board_re_lev,board_re_seq,board_readcount,board_date)
		values
		(board53_num_seq.nextval,#{board_name},#{board_pass},#{board_subject},
		#{board_content},board53_num_seq.nextval,0,0,0,SYSDATE)
	</insert>

	<!-- Total posts -->
	<select id="board_count" resultType="int">
		select count(board_num) from board53
	</select>

	<!-- Post List -->
	<select id="board_list" parameterType="int" resultType="board">
	    <![CDATA[
		select * from (select rownum rnum, board.* from  
	  	(select * from board53 order by BOARD_RE_REF desc,BOARD_RE_SEQ asc) board) 
	    where rnum >= ((#{page}-1) * 10+1)  and rnum <= (#{page} * 10)
		]]>
	</select>

	<!-- Detail Page -->
	<select id="board_cont" parameterType="int" resultType="board">
		select * from board53 where board_num=#{board_num}
	</select>

	<!-- View count +1 -->
	<update id="board_hit" parameterType="int">
		update board53 set
		board_readcount=board_readcount+1
		where board_num=#{board_num}
	</update>

	<!-- 게시물 수정 -->
	<update id="board_edit" parameterType="board">
		update board53 set
		board_name=#{board_name},
		board_subject=#{board_subject},
		board_content=#{board_content}
		where board_num=#{board_num}
	</update>

	<!-- Delete -->
	<delete id="board_del" parameterType="int">
		delete from board53 where
		board_num=#{board_num}
	</delete>

	<!-- Reply Level -->
	<update id="board_Level" parameterType="board">
		update board53 set
		board_re_seq=board_re_seq+1
		where board_re_ref=#{board_re_ref} and
		board_re_seq > #{board_re_seq}
	</update>

	<!-- Save Reply -->
	<insert id="board_reply" parameterType="board">
		insert into board53
		(board_num,board_name,board_subject,board_content,
		board_pass,board_re_ref,board_re_lev,board_re_seq,board_readcount,board_date)
		values(board53_num_seq.nextval,#{board_name},#{board_subject},#{board_content},
		#{board_pass},#{board_re_ref},#{board_re_lev},#{board_re_seq},0,SYSDATE)
	</insert>

</mapper>

BoardController.java

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.demo.model.BoardBean;
import com.example.demo.service.BoardServiceImpl;

@Controller
public class BoardController {

	@Autowired
	private BoardServiceImpl boardService;
	
	@RequestMapping("test.do")
	public String test(){
		System.out.println("Controller");
		
		return "board/test";
	}
	
	
	/* New Post */
	@RequestMapping(value = "/board_write.do")
	public String board_write() {
		return "board/board_write";
	}

	/* Save Post */
	@RequestMapping(value = "/board_write_ok.do", method = RequestMethod.POST)
	public String board_write_ok(@ModelAttribute BoardBean board)
			throws Exception {
//	public String board_write_ok(@RequestParam HashMap board)
//			throws Exception {
	
		boardService.insert(board);

		return "redirect:/board_list.do";
	}

	
	/* Post List 게시판 목록 */
	@RequestMapping(value = "/board_list.do")
	public String list(Model model, 
			           HttpServletRequest request) throws Exception {

		List<BoardBean> boardlist = new ArrayList<BoardBean>();

		int page = 1;
		int limit = 10; 

		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		int listcount = boardService.getListCount();

		boardlist = boardService.getBoardList(page); 

		int maxpage = (int) ((double) listcount / limit + 0.95); 
																	
		int startpage = (((int) ((double) page / 10 + 0.9)) - 1) * 10 + 1;

		int endpage = maxpage;

		if (endpage > startpage + 10 - 1)
			endpage = startpage + 10 - 1;

		model.addAttribute("page", page);
		model.addAttribute("startpage", startpage);
		model.addAttribute("endpage", endpage);
		model.addAttribute("maxpage", maxpage);
		model.addAttribute("listcount", listcount);
		model.addAttribute("boardlist", boardlist);
		
		return "board/board_list";
	}

	
	@RequestMapping(value = "/board_cont.do")
	public String board_cont(@RequestParam("board_num") int board_num,
			@RequestParam("page") String page,
			@RequestParam("state") String state, 
			Model model) throws Exception {

		if (state.equals("cont")) { 
			boardService.hit(board_num); 
		}

		BoardBean board = boardService.board_cont(board_num);

		model.addAttribute("bcont", board);
		model.addAttribute("page", page);

		if (state.equals("cont")) {
			return "board/board_cont";
	
		} else if (state.equals("edit")) {// Edit Form
			return "board/board_edit";
		} else if (state.equals("del")) {// Delete Form
			return "board/board_del";
		} else if (state.equals("reply")) {// Reply Form
			return "board/board_reply";
		}
		return null;
	}

	
	/* Edit */
	@RequestMapping(value = "/board_edit_ok.do", method = RequestMethod.POST)
	public String board_edit_ok(@ModelAttribute BoardBean b,
								@RequestParam("page") String page,
								Model model) throws Exception {

		BoardBean board = boardService.board_cont(b.getBoard_num());
		int result = 0;
		
		if (!board.getBoard_pass().equals(b.getBoard_pass())) {// Correct password
			model.addAttribute("result", result);
			
			return "board/updateResult";

		} else {
			
			boardService.edit(b);			
		}	
		
		return "redirect:/board_cont.do?board_num=" + b.getBoard_num()
					+ "&page=" + page + "&state=cont";
	}

	
	/* Delete */
	@RequestMapping(value = "/board_del_ok.do", method = RequestMethod.POST)
	public String board_del_ok(@RequestParam("board_num") int board_num,
			@RequestParam("page") int page,
			@RequestParam("pwd") String board_pass,
			Model model) throws Exception {

		BoardBean board = boardService.board_cont(board_num);
		int result=0;
		
		if (!board.getBoard_pass().equals(board_pass)) {
			result = 1;
			model.addAttribute("result", result);

			return "board/deleteResult";

		} else {
			boardService.del_ok(board_num);		
		}
		
		return "redirect:/board_list.do?page=" + page;
	}

	
	/* Reply */
	@RequestMapping(value = "/board_reply_ok.do", method = RequestMethod.POST)
	public String board_reply_ok(@ModelAttribute BoardBean b,
								 @RequestParam("page") String page) throws Exception {

		boardService.reply_ok(b);

		return "redirect:/board_list.do?page=" + page;
	}
	
	
}

BoardService.java

package com.example.demo.service;

import java.util.List;

import com.example.demo.model.BoardBean;


public interface BoardService {

	public void insert(BoardBean b) throws Exception;
	
	public void hit(int board_num) throws Exception;

	public BoardBean board_cont(int board_num) throws Exception;

	public void edit(BoardBean b) throws Exception;

	public void del_ok(int board_num) throws Exception;

	public void reply_ok(BoardBean b) throws Exception;
	
	public int getListCount() throws Exception;
	
	public List getBoardList(int page) throws Exception;

}

BoardServiceImpl.java

package com.example.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.dao.BoardDAOImpl;
import com.example.demo.model.BoardBean;

@Service
public class BoardServiceImpl implements BoardService{

	@Autowired
	private BoardDAOImpl boardDao;
	

	public void insert(BoardBean b) throws Exception {
		boardDao.insertBoard(b);
	}
	
	// Total Post	
	@Override
	public int getListCount() throws Exception {		
		return boardDao.getListCount();
	}

	// Post List
	@Override
	public List getBoardList(int page) throws Exception {
		// TODO Auto-generated method stub
		return boardDao.getBoardList(page);
	}

	/* View count +1 */
	public void hit(int board_num) throws Exception {
		boardDao.boardHit(board_num); 
	}
	

	/* Detail */
	public BoardBean board_cont(int board_num) throws Exception {

		BoardBean board = boardDao.getBoardCont(board_num);

		return board;
	}

	
	/* Edit */
	public void edit(BoardBean b) throws Exception {			
		boardDao.boardEdit(b);
	}
	

	/* Delete */
	public void del_ok(int board_num) throws Exception{			
		boardDao.boardDelete(board_num);		
	}
	

	/* Reply */
	public void reply_ok(BoardBean b) throws Exception {

		boardDao.refEdit(b); 

		b.setBoard_re_lev(b.getBoard_re_lev() + 1); 
		b.setBoard_re_seq(b.getBoard_re_seq() + 1);

		boardDao.boardReplyOk(b);
	}

}

BoardDao.java

package com.example.demo.dao;

import java.util.List;
import com.example.demo.model.BoardBean;

public interface BoardDao {

	public void insertBoard(BoardBean b) throws Exception;

	public List<BoardBean> getBoardList(int page) throws Exception;

	public int getListCount() throws Exception;

	public BoardBean getBoardCont(int board_num) throws Exception;

	public void boardHit(int board_num) throws Exception;

	public void boardEdit(BoardBean b) throws Exception;

	public void boardDelete(int board_num) throws Exception;

	public void refEdit(BoardBean b) throws Exception;

	public void boardReplyOk(BoardBean b) throws Exception;
}

BoardDAOImpl.java

package com.example.demo.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.demo.model.BoardBean;

@Repository
public class BoardDAOImpl implements BoardDao{

	@Autowired
	private SqlSession session;

	
	public void insertBoard(BoardBean b) throws Exception {
		session.insert("boardns.board_insert", b);
	}

	
	/* Post List */
	public List<BoardBean> getBoardList(int page) throws Exception {
		List<BoardBean> list = session.selectList("boardns.board_list", page);

		return list;
	}

	
	/* Total Post */
	public int getListCount() throws Exception {
		int count = 0;	
		count = ((Integer) session.selectOne("boardns.board_count")).intValue();

		return count;
	}

	
	/* Detail  */
	public BoardBean getBoardCont(int board_num) throws Exception {
		return (BoardBean) session.selectOne("boardns.board_cont",board_num);
	}

	
	/* View Count + 1  */
	public void boardHit(int board_num) throws Exception {
		session.update("boardns.board_hit", board_num);		
	}

	
	/* Edit  */
	public void boardEdit(BoardBean b) throws Exception {
		session.update("boardns.board_edit", b);		
	}

	
	/* Delete  */
	public void boardDelete(int board_num) throws Exception {
		session.delete("boardns.board_del", board_num);				
	}

	
	/* Reply  */
	public void refEdit(BoardBean b) throws Exception {
		session.update("boardns.board_Level", b);		
	}

	
	/* Reply Save  */
	public void boardReplyOk(BoardBean b) throws Exception {
		session.insert("boardns.board_reply", b);		
	}

}

boad_list.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="com.example.demo.model.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>Post list</title>
    <link rel="stylesheet" href="./css/bbs.css" type="text/css">
</head>

<body>
	<!-- List -->
	<div id="bbslist_wrap">
		<h2 class="bbslist_title">List</h2>
		<div id="bbslist_c">Total Posts : ${listcount}</div>

		<table id="bbslist_t">
			<tr align="center" valign="middle" bordercolor="#333333">
				<td style="font-family: Tahoma; font-size: 11pt;" width="8%"
					height="26">
					<div align="center">Number</div>
				</td>
				<td style="font-family: Tahoma; font-size: 11pt;" width="47%">
					<div align="center">Title</div>
				</td>
				<td style="font-family: Tahoma; font-size: 11pt;" width="14%">
					<div align="center">Writer</div>
				</td>
				<td style="font-family: Tahoma; font-size: 11pt;" width="17%">
					<div align="center">Date</div>
				</td>
				<td style="font-family: Tahoma; font-size: 11pt;" width="14%">
					<div align="center">View</div>
				</td>
			</tr>

			<c:set var="num" value="${listcount-(page-1)*10}"/> 	
	
			<!-- forEach Tag -->
			<c:forEach var="b" items="${boardlist}">
			
			<tr align="center" valign="middle" bordercolor="#333333"
				onmouseover="this.style.backgroundColor='F8F8F8'"
				onmouseout="this.style.backgroundColor=''">
				<td height="23" style="font-family: Tahoma; font-size: 10pt;">					
 					<!-- Number -->	
 					<c:out value="${num}"/>			
					<c:set var="num" value="${num-1}"/>	 
				</td>
				
				<td style="font-family: Tahoma; font-size: 10pt;">
					<div align="left">						
						
					<c:if test="${b.board_re_lev != 0}"> 
						<c:forEach var="k" begin="1" end="${b.board_re_lev}">
							&nbsp;&nbsp;			
						</c:forEach>
						<img src="./images/AnswerLine.gif">	
					</c:if>					
						
					<!-- Title -->	
					<a href="board_cont.do?board_num=${b.board_num}&page=${page}&state=cont">
							${b.board_subject}
					</a>
					</div>
				</td>

				<td style="font-family: Tahoma; font-size: 10pt;">
					<div align="center">${b.board_name}</div>
				</td>
				<td style="font-family: Tahoma; font-size: 10pt;">
					<div align="center">${b.board_date}</div>
				</td>
				<td style="font-family: Tahoma; font-size: 10pt;">
					<div align="center">${b.board_readcount}</div>
				</td>
			</tr>
			
			</c:forEach>
		
		</table>
		

		<div id="bbslist_paging">			
			<c:if test="${page <=1 }">
				[Prev]&nbsp;
			</c:if>
			
			<c:if test="${page > 1 }">
				<a href="board_list.do?page=${page-1}">[Prev]</a>&nbsp;
			</c:if>			

			<c:forEach var="a" begin="${startpage}" end="${endpage}">
				<c:if test="${a == page }">
					[${a}]
				</c:if>
				<c:if test="${a != page }">
					<a href="board_list.do?page=${a}">[${a}]</a>&nbsp;
				</c:if>
			</c:forEach>			
			
			<c:if test="${page >= maxpage }">
				[Next] 
			</c:if>
			<c:if test="${page < maxpage }">
				<a href="board_list.do?page=${page+1}">[Next]</a>
			</c:if>			
			
		</div>
		<div id="bbslist_w">
			<input type="button" value="New Post" class="input_button"
				onclick="location='board_write.do?page=${page}'">
		</div>
		
	</div>
</body>
</html>

 

board_write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>    
    
<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>New Post</title>
	<link rel="stylesheet" type="text/css" href="./css/bbs.css" />
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="./js/board.js"></script>
</head>

<body>
 <div id="bbswrite_wrap">
  <h2 class="bbswrite_title">New Post</h2>
  <form method="post" action="board_write_ok.do" onSubmit="return board_check()">
   <table id="bbswrite_t">
    <tr>
     <th>Writer</th>
     <td>
     <input name="board_name" id="board_name" size="14" class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Password</th>
     <td>
      <input type="password" name="board_pass" id="board_pass" size="14"
      class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Title</th>
     <td>
      <input name="board_subject" id="board_subject" size="40" 
      class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Content</th>
     <td>
      <textarea name="board_content"  id="board_content" rows="8" cols="50"
      class="input_box"></textarea>
     </td>
    </tr> 
    
   </table>
   
   <div id="bbswrite_menu">
    <input type="submit" value="Submit" class="input_button" />
    <input type="reset" value="Cancel" class="input_button"
    onclick="$('#board_name').focus();" />
   </div>
  </form>
 </div>
</body>
</html>

board_cont.jsp

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

<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>Post</title>
	<link rel="stylesheet" type="text/css" href="./css/board.css" />
</head>

<body>
	<div id="boardcont_wrap">
		<h2 class="boardcont_title">Post</h2>
		<table id="boardcont_t">
			<tr>
				<th>Title</th>
				<td>${bcont.board_subject}</td>
			</tr>

			<tr>
				<th>Content</th>
				<td>
					<%--  ${board_cont} --%> 
					<pre>${bcont.board_content}</pre>
				</td>
			</tr>

			<tr>
				<th>View</th>
				<td>${bcont.board_readcount}</td>
			</tr>
		</table>

		<div id="boardcont_menu">
			<input type="button" value="Edit" class="input_button"
				onclick="location='board_cont.do?board_num=${bcont.board_num}&page=${page}&state=edit'" />
			<input type="button" value="Delete" class="input_button"
				onclick="location='board_cont.do?board_num=${bcont.board_num}&page=${page}&state=del'" />
			<input type="button" value="Reply" class="input_button"
				onclick="location='board_cont.do?board_num=${bcont.board_num}&page=${page}&state=reply'" />
			<input type="button" value="List" class="input_button"
				onclick="location='board_list.do?page=${page}'" />
		</div>
	</div>
</body>
</html>

board_reply.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>Reply</title>
	<link rel="stylesheet" type="text/css" href="./css/board.css" />
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="./js/board.js"></script>
</head>

<body>
 <div id="boardreply_wrap">
  <h2 class="boardreply_title">Reply</h2>
  <form method="post" action="board_reply_ok.do">  
  <input type="hidden" name="board_num" value="${bcont.board_num}" />
  <input type="hidden" name="board_re_ref" value="${bcont.board_re_ref}" />
  <input type="hidden" name="board_re_lev" value="${bcont.board_re_lev}" />
  <input type="hidden" name="board_re_seq" value="${bcont.board_re_seq}" />
  <input type="hidden" name="page" value="${page}" />
  
   <table id="boardreply_t">
    <tr>
     <th>Writer</th>
     <td>
      <input name="board_name" id="board_name" size="14" class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Password</th>
     <td>
      <input type="password" name="board_pass" id="board_pass"
      size="14" class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Title</th>
     <td>
      <input name="board_subject" id="board_subject" size="40"
      class="input_box" value="Re:${bcont.board_subject}" />
     </td>
    </tr>
    
    <tr>
     <th>Content</th>
     <td>
      <textarea name="board_content" id="board_content" rows="8" 
      cols="50" class="input_box" ></textarea>
     </td>
    </tr>
   </table>
   <div id="boardreply_menu">
    <input type="submit" value="Submit" class="input_button" />
    <input type="reset" value="Cancel" class="input_button"
    onclick="$('#board_name').focus();" />
   </div>
  </form>
 </div>
</body>
</html>

board_edit.jsp

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

<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>Edit</title>
	<link rel="stylesheet" type="text/css" href="./css/bbs.css" />
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="./js/board.js"></script>
</head>

<body>
 <div id="bbswrite_wrap">
  <h2 class="bbswrite_title">Edit Post</h2>
  <form method="post" action="board_edit_ok.do" onSubmit="return board_check()">
  <input type="hidden" name="board_num" value="${bcont.board_num}" />
  <input type="hidden" name="page" value="${page}" />
  
   <table id="bbswrite_t">
    <tr>
     <th>Writer</th>
     <td>
     <input name="board_name" id="board_name" size="14" class="input_box" 
     value="${bcont.board_name}" />
     </td>
    </tr>
    
    <tr>
     <th>Password</th>
     <td>
      <input type="password" name="board_pass" id="board_pass" size="14"
      class="input_box" />
     </td>
    </tr>
    
    <tr>
     <th>Title</th>
     <td>
      <input name="board_subject" id="board_subject" size="40" 
      class="input_box" value="${bcont.board_subject}" />
     </td>
    </tr>
    
    <tr>
     <th>Content</th>
     <td>
      <textarea name="board_content" id="board_content" rows="8" cols="50"
      class="input_box">${bcont.board_content}</textarea>
     </td>
    </tr> 
    
   </table>
   
   <div id="bbswrite_menu">
    <input type="submit" value="Edit" class="input_button" />
    <input type="reset" value="Cancel" class="input_button"
    onclick="$('#board_name').focus();" />
   </div>
  </form>
 </div>
</body>
</html>

 

board_del.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!doctype html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>Delete Post</title>
	<link rel="stylesheet" type="text/css" href="./css/board.css" />
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	
	<script>
 	 function del_check(){
		  if($.trim($("#pwd").val())==""){
			  alert("Enter the password!");
			  $("#pwd").val("").focus();
			  return false;
	 	 }
  	}
	</script>
</head>

<body>
 <div id="boarddel_wrap">
  <h2 class="boarddel_title">Delete</h2>
  <form method="post" action="board_del_ok.do" 
  onsubmit="return del_check()">
  <input type="hidden" name="board_num" value="${bcont.board_num}" />
  <input type="hidden" name="page" value="${page}" />
   <table id="boarddel_t">
    <tr>
     <th>Password</th>
     <td>
      <input type="password" name="pwd" id="pwd" size="14" 
      class="input_box" />
     </td>
    </tr>
   </table>
   <div id="boarddel_menu">
    <input type="submit" value="Delete" class="input_button" />
    <input type="reset" value="Cancel" class="input_button" 
    onclick="$('#pwd').focus();" />
   </div>
  </form>
 </div>
</body>
</html>

 

Configuration

1. pom.xml - libraries/dependencies

2. web.xml 

3. servlet-context.xml - prefix/suffix

4. mybatis-config.xml - MyBatis configuration file (Resources directory)

5. board.xml - mapper file (Resources directory), SQL

6. root-context.xml - beans

 

Database

board1.sql


select * from tab;
select * from board;

drop table board purge;

create table board (
	num number primary key, 
	writer varchar2(20) not null,
	subject varchar2(50) not null, -- Title
	topic varchar2(50) not null, -- Topic
	content varchar2(500) not null, 
	email varchar2(30) , 
	readcount number default 0, 
	passwd varchar2(12) not null, 
	ref number not null, 
	re_step number not null, 
	re_level number not null, 
	ip varchar2(20) not null, 
	reg_date date not null, 
	del char(1)
);

update board set readcount = 51 where num = 250;

 

In this project, service class and dao class will be divided into two files: interface and implementation class.

BoardService.java

package board1.service;

import java.util.List;
import board1.model.Board;

public interface BoardService {
	// List<Board> list(int startRow, int endRow);
	List<Board> list(Board board);

	int getTotal(Board board);

	int insert(Board board);

	Board select(int num);

	void selectUpdate(int num);

	int update(Board board);

	int delete(int num);

	int getMaxNum();

	void updateRe(Board board);

}

BoardDAO.java

package board1.dao;

import java.util.List;
import board1.model.Board;

public interface BoardDao {
	// List<Board> list(int startRow, int endRow);
	List<Board> list(Board board);

	int getTotal(Board board);

	int insert(Board board);

	Board select(int num);

	void selectUpdate(int num);

	int update(Board board);

	int delete(int num);

	int getMaxNum();

	void updateRe(Board board);
}

 

index.jsp

insertForm.jsp

BoardController.java(New post and Reply)

	@RequestMapping("insertForm.do")	// InsertForm
	public String insertForm(String nm, String pageNum, Model model) {
		int num = 0, ref = 0, re_level = 0, re_step = 0; 
		if (nm != null) {	// Reply
			num = Integer.parseInt(nm);
			Board board = bs.select(num);	
			ref = board.getRef();
			re_level = board.getRe_level();
			re_step = board.getRe_step();
		}
		model.addAttribute("num", num);
		model.addAttribute("ref", ref);
		model.addAttribute("re_level", re_level);
		model.addAttribute("re_step", re_step);
		model.addAttribute("pageNum", pageNum);
		
		return "insertForm";
	}

	@RequestMapping("insert.do")	// Insert
	public String insert(Board board, Model model, HttpServletRequest request) {
		int num = board.getNum();
		int number = bs.getMaxNum();
		if (num != 0) {		// Reply
			bs.updateRe(board);
			board.setRe_level(board.getRe_level() + 1);
			board.setRe_step(board.getRe_step() + 1);
		} else				// Original post
			board.setRef(number);
			board.setNum(number);
			String ip = request.getRemoteAddr();
			board.setIp(ip);
			int result = bs.insert(board);
			model.addAttribute("result", result);
			
		return "insert";
	}

BoardServiceImpl.java

public int insert(Board board) {
		return bd.insert(board);
	}

BoardDaoImpl.java

public int insert(Board board) {
		return sst.insert("boardns.insert",board);
	}

Board.xml

<insert id="insert" parameterType="board">
	<!--<selectKey keyProperty="num" 
			order="BEFORE" resultType="int">
			select nvl(max(num),0) + 1 from board
		</selectKey> -->
		insert into board values (#{num},#{writer},#{subject},#{topic},
			#{content},#{email},0,#{passwd},#{ref},
			#{re_step},#{re_level},#{ip},sysdate,'n')
	</insert>
    
    <!-- Reply -->
    <update id="update" parameterType="board">
		update board set writer=#{writer},topic=#{topic},subject=#{subject},
			content=#{content},email=#{email} where num=#{num}
	</update>

insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Successfully posted.");
			location.href = "list.do";
		</script>
	</c:if>
	<c:if test="${result <= 0 }">
		<script type="text/javascript">
			alert("Failed to post.");
			history.go(-1);
		</script>
	</c:if>
</body>
</html>

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Better Call Saul/ Breaking Bad/ El
			Camino universe Forum</h2>
		<table class="table table-striped">
			<tr>
				<td>No.</td>
				<td>Subject</td>
				<td>Title</td>
				<td>Writer</td>
				<td>Date</td>
				<td>View</td>
			</tr>

			<c:if test="${empty list}">
				<tr>
					<td colspan="5">No posts yet. Be the first writer!</td>
				</tr>
			</c:if>

			<c:if test="${not empty list}">
				<c:set var="no1" value="${no }"></c:set>
				<c:forEach var="board" items="${list }">
					<tr>
						<td>${no1}</td>
						<c:if test="${board.del =='y' }">
							<td colspan="4">This post is deleted.</td>
						</c:if>

						<c:if test="${board.del !='y' }">
							<td> <c:if test="${board.re_level >0 }">
										<img alt="" src="images/level.gif" height="2"
											width="${board.re_level *5 }">
										<img alt="" src="images/re.gif">
									</c:if> ${board.topic}
							</a></td>
							
							<td><a href="view.do?num=${board.num}&pageNum=${pp.currentPage}"
								class="btn btn-default"><c:if test="${board.readcount > 10 }">
									<img alt="" src="images/hot.gif">
								</c:if>${board.subject}</td>
								
							<td>${board.writer}</td>
							<td>${board.reg_date}</td>
							<td>${board.readcount}</td>
						</c:if>
					</tr>
					<c:set var="no1" value="${no1 - 1}" />
				</c:forEach>
			</c:if>
		</table>

		<form action="list.do">
			<input type="hidden" name="pageNum" value="1"> <select
				name="search">
				<option value="subject"
					<c:if test="${search=='subject'}">selected="selected" </c:if>>Title</option>
				<option value="content"
					<c:if test="${search=='content'}">selected="selected" </c:if>>Content</option>
				<option value="writer"
					<c:if test="${search=='writer'}">selected="selected" </c:if>>Writer</option>
				<option value="subcon"
					<c:if test="${search=='subcon'}">selected="selected" </c:if>>Title+Content</option>
			</select> <input type="text" name="keyword"> 
			<input type="submit" value="Submit">
		</form>

		<ul class="pagination">
			<!-- Pagination : Searched -->
			<c:if test="${not empty keyword}">
				<c:if test="${pp.startPage > pp.pagePerBlk }">
					<li><a
						href="list.do?pageNum=${pp.startPage - 1}&search=${search}&keyword=${keyword}">Prev</a></li>
				</c:if>
				<c:forEach var="i" begin="${pp.startPage}" end="${pp.endPage}">
					<li <c:if test="${pp.currentPage==i}">class="active"</c:if>><a
						href="list.do?pageNum=${i}&search=${search}&keyword=${keyword}">${i}</a></li>
				</c:forEach>
				<c:if test="${pp.endPage < pp.totalPage}">
					<li><a
						href="list.do?pageNum=${pp.endPage + 1}&search=${search}&keyword=${keyword}">Next</a></li>
				</c:if>
			</c:if>

			<!-- Pagination : List -->
			<c:if test="${empty keyword}">
				<c:if test="${pp.startPage > pp.pagePerBlk }">
					<li><a href="list.do?pageNum=${pp.startPage - 1}">Next</a></li>
				</c:if>
				<c:forEach var="i" begin="${pp.startPage}" end="${pp.endPage}">
					<li <c:if test="${pp.currentPage==i}">class="active"</c:if>><a
						href="list.do?pageNum=${i}">${i}</a></li>
				</c:forEach>
				<c:if test="${pp.endPage < pp.totalPage}">
					<li><a href="list.do?pageNum=${pp.endPage + 1}">Prev</a></li>
				</c:if>
			</c:if>
		</ul>
		<div align="center">
			<a href="insertForm.do" class="btn btn-info">New Post</a>
		</div>
	</div>
</body>
</html>

view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		$('#list').load('list.do?pageNum=${pageNum}');
	});
</script>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Post</h2>
		<table class="table table-bordered">
			<tr>
				<td>Subject</td>
				<td>${board.topic}</td>
			</tr>
			<tr>
				<td>Title</td>
				<td>${board.subject}</td>
			</tr>
			<tr>
				<td>Writer</td>
				<td>${board.writer}</td>
			</tr>
			<tr>
				<td>View</td>
				<td>${board.readcount}</td>
			</tr>
			<tr>
				<td>IP Address</td>
				<td>${board.ip}</td>
			</tr>
			<tr>
				<td>Email</td>
				<td>${board.email}</td>
			</tr>
			<tr>
				<td>Content</td>
				<td><pre>${board.content}</pre></td>
			</tr>
		</table>
		
		<a href="list.do?pageNum=${pageNum}" class="btn btn-info">List</a> 
		<a href="updateForm.do?num=${board.num}&pageNum=${pageNum}"
		   class="btn btn-info">Edit</a> 
		<a href="deleteForm.do?num=${board.num}&pageNum=${pageNum}"
		   class="btn btn-info">Delete</a> 
		<a href="insertForm.do?nm=${board.num}&pageNum=${pageNum}"
		   class="btn btn-info">Reply</a>
		<div id="list"></div>
	</div>
</body>
</html>

 

BoardController.java

@RequestMapping("view.do")	
	public String view(int num, String pageNum, Model model) {
		bs.selectUpdate(num);	// view +1
		Board board = bs.select(num);
		model.addAttribute("board", board);
		model.addAttribute("pageNum", pageNum);
		
		return "view";
	}

updateForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function chk() {
		if(frm.passwd.value != frm.passwd2.value) {
			alert("Incorrect password.");
			frm.passwd2.focus();
            frm.passwd2.value =""; // To erase the inserted password.

			return false;
		}
	}
</script>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Edit post</h2>
		<form action="update.do" method="post" name="frm"
			  onsubmit="return chk()">
			<input type="hidden" name="num" value="${board.num}"> 
			<input type="hidden" name="pageNum" value="${pageNum}"> 
			<input type="hidden" name="passwd" value="${board.passwd}">
			<table class="table table-striped">
				<tr>
					<td>No.</td>
					<td>${board.num}</td>
				</tr>
				<tr>
				<td>Subject
					<select name="topic" type="text">
						<option value="Breaking Bad" selected="selected">Breaking Bad</option>
						<option value="Better Call Saul" selected="selected">Better Call Saul</option>
						<option value="El Camino" selected="selected">El Camino</option>
					</select>
					</td>
				</tr>
				<tr>
					<td>Title</td>
					<td><input type="text" name="subject" required="required"
								value="${board.subject}"></td>
				</tr>
				<tr>
					<td>Writer</td>
					<td><input type="text" name="writer" required="required"
								value="${board.writer}"></td>
				</tr>
				<tr>
					<td>Email</td>
					<td><input type="email" name="email" required="required"
								value="${board.email}"></td>
				</tr>
				<tr>
					<td>Password</td>
					<td><input type="password" name="passwd2" required="required"></td>
				</tr>
				<tr>
					<td>Content</td>
					<td>
						<textarea rows="5" cols="30" name="content" required="required">${board.content}
						</textarea>
					</td>
				</tr>
				<tr>
					<td colspan="2" align="center"><input type="submit" value="Submit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

update.jsp

BoardController.java

@RequestMapping("updateForm.do")	// UpdateForm
	public String updateForm(int num, String pageNum, Model model) {
		Board board = bs.select(num);
		model.addAttribute("board", board);
		model.addAttribute("pageNum", pageNum);
		
		return "updateForm";
	}

	@RequestMapping("update.do")	// Update
	public String update(Board board, String pageNum, Model model) {
		int result = bs.update(board);
		model.addAttribute("result", result);
		model.addAttribute("pageNum", pageNum);
		
		return "update";
	}

BoardService.java

	public int update(Board board) {
		return bd.update(board);
	}

BoardDao.java

	public int update(Board board) {
		return sst.update("boardns.update",board);
	}

board.xml

	<update id="update" parameterType="board">
		update board set writer=#{writer},topic=#{topic},subject=#{subject},
			content=#{content},email=#{email} where num=#{num}
	</update>

deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function chk() {
		if (frm.passwd.value != frm.passwd2.value) {
			alert("Incorrect Password");
			frm.passwd2.focus();
			frm.passwd2.value =""; // To erase the inserted password.
			return false;
		}
	}
</script>
</head>
<body>
	<div class="container">
		<h2 class="text-primary">Delete Post</h2>
		<form action="delete.do" name="frm" onsubmit="return chk()"	method="post">
			<input type="hidden" name="pageNum" value="${pageNum}"> 
			<input	type="hidden" name="passwd" value="${board.passwd}"> 
			<input type="hidden" name="num" value="${board.num}">
			<table class="table">
				<tr>
					<td>Password</td>
					<td><input type="password" name="passwd2" required="required"></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="Submit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Successfully deleted.");
			location.href = "list.do?pageNum=${pageNum}";
		</script>
	</c:if>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Failed to delete.");
			history.go(-1);
		</script>
	</c:if>
</body>
</html>

BoardController.java

@RequestMapping("deleteForm.do")
	public String deleteForm(int num, String pageNum, Model model) {
		Board board = bs.select(num);
		model.addAttribute("board", board);
		model.addAttribute("pageNum", pageNum);
		
		return "deleteForm";
	}

	@RequestMapping("delete.do")
	public String delete(int num, String pageNum, Model model) {
		int result = bs.delete(num);
		model.addAttribute("result", result);
		model.addAttribute("pageNum", pageNum);
		
		return "delete";
	}

BoardService.java

	public int delete(int num) {
		return bd.delete(num);
	}

BoardDao.java

	public int delete(int num) {
		return sst.update("boardns.delete",num);
	}

 

Configuration files :

pom.xml, web.xml, root-context.xml. servlet-context.xml, contifuration.xml, Dept.xml

 

pom.xml

- dependencies

- encoding

 

servlet-context.xml

- prefix

- suffix

- base-package

 

root-context.xml

Spring controls DB, so we need : 

- dataSource bean instance

- SqlSessionFactoryBean instance

- property

- Database connection

- constructor DI 

 

configuration.xml

- typeAlias

 

Department and Employees Management System

Dept.java

Dept class has three columns. It is connected to the Dept table in the database. 

package myBatis2.model;

public class Dept {
	private int deptno;
	private String dname;
	private String loc;

	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int 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;
	}
}

Emp.java

Emp class has eight columns. It is connected to the Emp table in the database. 

package myBatis2.model;

import java.sql.Date;

public class Emp {
	private int empno;
	private String ename;
	private String job;
	private int mgr;
	private Date hiredate;
	private int sal;
	private int comm;
	private int deptno;
	private String dname;
	private String loc;

	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;
	}

	public int getEmpno() {
		return empno;
	}

	public void setEmpno(int empno) {
		this.empno = empno;
	}

	public String getEname() {
		return ename;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public int getMgr() {
		return mgr;
	}

	public void setMgr(int mgr) {
		this.mgr = mgr;
	}

	public Date getHiredate() {
		return hiredate;
	}

	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}

	public int getSal() {
		return sal;
	}

	public void setSal(int sal) {
		this.sal = sal;
	}

	public int getComm() {
		return comm;
	}

	public void setComm(int comm) {
		this.comm = comm;
	}

	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
}

configuration.xml

configuration file connects to the tables. 

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

	<typeAliases>
		<typeAlias alias="dept" type="myBatis2.model.Dept" />
		<typeAlias alias="emp"  type="myBatis2.model.Emp" />
	</typeAliases>	
	
</configuration>

In the service folder, there consist of interfaces. 

index.jsp

Once you run this file, the dispatcher servlet will be run right away and it is loaded to the controller classes. 

<%@ 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>
</head>
<body>
<script type="text/javascript">
	location.href="deptList.do";
</script>
</body>
</html>

deptList.do -> DeptController.java

 

DeptController.java

DeptController class receives the deptList.do with the @RequestMapping annotation. 

The name of the service is injected as ds.

package myBatis2.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import myBatis2.model.Dept;
import myBatis2.service.DeptService;

@Controller
public class DeptController {
	@Autowired
	private DeptService ds;
	// Dept List
	@RequestMapping("deptList.do")
	public String deptList(Model model) {
		List<Dept> list = ds.list();
		model.addAttribute("list", list);
		return "deptList";
	}

Control key + Click the second one -> you will be loaded to the DeptServiceImpl.java. 

Dept.xml (Mapper)

To avoid overlapped id values, you must use <mapper namespace="deptns">

Whenever we need to connect to the database, we will return to Dept.xml to execute the SQLs.

<?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="deptns">

	<!-- Use type aliases to avoid typing the full classname every time. -->
	<resultMap id="deptResult"    type="dept">
		<result property="deptno" column="deptno" />
		<result property="dname"  column="dname" />
		<result property="loc"	  column="loc" />
	</resultMap>
	
	<select id="list" resultMap="deptResult">
		select * from dept order by deptno
	</select>
	
	<select id="select" parameterType="int" resultType="dept">
		select * from dept where deptno=#{deptno}
	</select>
	
	<update id="update" parameterType="dept">
		update dept set dname=#{dname},loc=#{loc} where deptno=#{deptno}
	</update>
	
	<delete id="delete" parameterType="int">
		delete from dept where deptno=#{deptno}
	</delete>
	
	<insert id="insert" parameterType="dept">
		insert into dept values(#{deptno},#{dname},#{loc})
	</insert>
	
</mapper>

deptList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Dept List</h2>
		<table class="table table-hover">
			<tr>
				<th>Dept Code</th>
				<th>Dept Name</th>
				<th>Dept Location</th>
				<th></th>
				<th></th>
			</tr>
			<c:if test="${empty list}">
				<tr>
					<td colspan="5">There is no data.</td>
				</tr>
			</c:if>
			<c:if test="${not empty list }">
				<c:forEach var="dept" items="${list}">
					<tr>
						<td>${dept.deptno}</td>
						<td><a href="empList.do?deptno=${dept.deptno}"
							   class="btn btn-info">${dept.dname}</a></td>
						<td>${dept.loc }</td>
						<td><a href="deptUpdateForm.do?deptno=${dept.deptno }"
							   class="btn btn-success">Edit</a></td>
						<td><a href="deptDelete.do?deptno=${dept.deptno }"
							   class="btn btn-danger">Delete</a></td>
				</c:forEach>
			</c:if>
		</table>
		<a href="deptInsertForm.do" class="btn btn-info">New Dept</a> 
		<a href="empAllList.do" class="btn btn-default">Emp List</a>
	</div>
</body>
</html>

index.jsp leads to the Dept List. 

When you click the Emp List, it leads to the empAllList.do, EmpController.java.

 

EmpController.java

In this class, you need to use the @Autowired annotation separately, not like this : 

package myBatis2.controller;

import java.sql.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import myBatis2.model.Dept;
import myBatis2.model.Emp;
import myBatis2.service.DeptService;
import myBatis2.service.EmpService;

@Controller
public class EmpController {
	@Autowired
	private EmpService es;
	@Autowired
	private DeptService ds;

	@RequestMapping("empList.do")
	public String empList(int deptno, Model model) {
		Dept dept = ds.select(deptno);
		List<Emp> list = es.list(deptno);
		model.addAttribute("dept", dept);
		model.addAttribute("list", list);
		return "emp/empList";
	}

empAllList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container">
		<table class="table table-striped">
			<tr>
				<td>No.</td>
				<td>Name</td>
				<td>Position</td>
				<td>Salary</td>
				<td>Dept Code</td>
				<td>Dept Name</td>
				<td>Dept Location</td>
			</tr>
			<c:forEach var="emp" items="${list }">
				<tr>
					<td>${emp.empno }</td>
					<td>${emp.ename }</td>
					<td>${emp.job }</td>
					<td>${emp.sal }</td>
					<td>${emp.deptno }</td>
					<td>${emp.dname }</td>
					<td>${emp.loc }</td>
				</tr>
			</c:forEach>
		</table>
		<a href="deptList.do" class="btn btn-default">Dept List</a>
	</div>
</body>
</html>

When you click the Dept List, you will go back to the Dept List, and when you click the New Dept, it will load to the DeptController.java, and to the deptInsertForm.jsp.

 

deptInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">New Dept Data</h2>
		<form action="deptInsert.do" method="post">
			<table class="table table-hover">
				<tr>
					<td>Dept Code</td>
					<td><input type="number" maxlength="2" name="deptno"
						required="required" autofocus="autofocus"></td>
				</tr>
				<tr>
					<td>Dept Name</td>
					<td><input type="text" name="dname" required="required"></td>
				</tr>
				<tr>
					<td>Dept Location</td>
					<td><input type="text" name="loc" required="required"></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="Submit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

DeptController.java

By using the @ModelAttribute annotation, you can receive the values at once. 

//New Dept Insert
    @RequestMapping("deptInsertForm.do")
	public String deptInsertForm() {
		return "deptInsertForm";
	}

	@RequestMapping("deptInsert.do")
	public String deptInsert(@ModelAttribute Dept dept, 
			                 Model model) {
		Dept dt = ds.select(dept.getDeptno());
		if (dt == null) {
			int result = ds.insert(dept);
			model.addAttribute("result", result);
		} else {
			model.addAttribute("msg", "Overlapped Data");
			model.addAttribute("result", -1);
		}
		return "deptInsert";
	}

If you insert the overlapped Data, you will get this alert. 

Successfully updated. 

DeptDaoImpl.java

package myBatis2.dao;

import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import myBatis2.model.Dept;

@Repository
public class DeptDaoImpl implements DeptDao {
	@Autowired
	private SqlSessionTemplate st;

	public List<Dept> list() {
		return st.selectList("deptns.list");
	}

	public int insert(Dept dept) {
		return st.insert("deptns.insert", dept);
	}

	public Dept select(int deptno) {
		return st.selectOne("deptns.select", deptno);
	}

	public int update(Dept dept) {
		return st.update("deptns.update", dept);
	}

	public int delete(int deptno) {
		return st.delete("deptns.delete", deptno);
	}
}

To edit and delete, we will click these green and red buttons. 

deptUpdateForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Edit Dept Info</h2>
		<form action="deptUpdate.do" method="post">
			<input type="hidden" name="deptno" value="${dept.deptno }">
			<table class="table table-hover">
				<tr>
					<td>Dept Code</td>
					<td>${dept.deptno}</td>
				</tr>
				<tr>
					<td>Dept Name</td>
					<td><input type="text" name="dname" required="required"
							   value="${dept.dname}"></td>
				</tr>
				<tr>
					<td>Dept Location</td>
					<td><input type="text" name="loc" required="required"
							   value="${dept.loc}"></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="Submit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

deptUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Successfully edited.");
			location.href = "deptList.do";
		</script>
	</c:if>
	<c:if test="${result <= 0 }">
		<script type="text/javascript">
			alert("Failed to edit.");
			history.go(-1);
		</script>
	</c:if>
</body>
</html>

DeptController.java

// Update
	@RequestMapping("deptUpdateForm.do")
	public String deptUpdateForm(int deptno, Model model) {
		Dept dept = ds.select(deptno);
		model.addAttribute("dept", dept);
		return "deptUpdateForm";
	}

	@RequestMapping("deptUpdate.do")
	public String deptUpdate(@ModelAttribute Dept dept, Model model) {
		int result = ds.update(dept);
		model.addAttribute("result", result);
		return "deptUpdate";
	}

 

 

There is no delete form since we don't need any information to be inserted. 

deptDelete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Successfully Deleted.");
			location.href = "deptList.do";
		</script>
	</c:if>
	<c:if test="${result <= 0 }">
		<script type="text/javascript">
			alert("Failed to delete."");
			location.href = "deptList.do";
		</script>
	</c:if>
</body>
</html>

DeptController.java

//Delete
	@RequestMapping("deptDelete.do")
	public String deptDelete(@RequestParam ("deptno") int deptno, Model model) {
		int result = ds.delete(deptno);
		model.addAttribute("result", result);
		return "deptDelete";
	}

 

You can delete the things that have no foreign key references. 

deptList.jsp was for showing the list of departments. If you click the department's name, you will see the list of employees. 

EmpController.java controls the Emp List. 

EmpController.java

// Emp List
@RequestMapping("empList.do")
	public String empList(int deptno, Model model) {
		Dept dept = ds.select(deptno);
		List<Emp> list = es.list(deptno);
		model.addAttribute("dept", dept);
		model.addAttribute("list", list);
		return "emp/empList";
	}

Since we are dealing with two different tables, we 

EmpDaoImpl.java

package myBatis2.dao;

import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import myBatis2.model.Dept;

@Repository
public class DeptDaoImpl implements DeptDao {
	@Autowired
	private SqlSessionTemplate st;

	public List<Dept> list() {
		return st.selectList("deptns.list");
	}

	public int insert(Dept dept) {
		return st.insert("deptns.insert", dept);
	}

	public Dept select(int deptno) {
		return st.selectOne("deptns.select", deptno);
	}

	public int update(Dept dept) {
		return st.update("deptns.update", dept);
	}

	public int delete(int deptno) {
		return st.delete("deptns.delete", deptno);
	}
}

Emp.xml (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="empns">

	<!-- Use type aliases to avoid typing the full classname every time. -->
	<resultMap id="empResult"    	type="emp">
		<result property="empno" 	column="empno" />
		<result property="ename"  	column="ename" />
		<result property="job"		column="job" />
		<result property="mgr" 		column="mgr" />
		<result property="hiredate" column="hiredate" />
		<result property="sal"	  	column="sal" />
		<result property="comm"	   	column="comm" />
		<result property="deptno"   column="deptno" />
		<result property="dname"	column="dname" />
		<result property="loc"   	column="loc" />
	</resultMap>
	
	<select id="empList" resultMap="empResult">
		select * from emp order by empno
	</select>
	
	<select id="list" parameterType="int" resultMap="empResult">
		select * from emp where deptno=#{deptno} order by empno
	</select>
		
	<select id="select" parameterType="int" resultType="emp">
		select * from emp where empno=#{empno}
	</select>
	
	<insert id="insert" parameterType="emp">
		insert into emp values(#{empno},#{ename},#{job},#{mgr},
			#{hiredate},#{sal},#{comm},#{deptno})
	</insert>
	
	<delete id="delete" parameterType="int">
		delete from emp where empno=#{empno}
	</delete>
	
	<update id="update" parameterType="emp">
		update emp set ename=#{ename},job=#{job},sal=${sal},
			comm=#{comm},deptno=#{deptno} where empno=#{empno}
	</update>
	
	<select id="empAllList" resultMap="empResult">
		select e.*,dname,loc from emp e, dept d 
			where e.deptno=d.deptno order by empno
	</select>
</mapper>

empList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		$('#list').load('deptList.do');
	});
</script>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">${dept.dname} Emp List</h2>
		<table class="table table-striped">
			<tr>
				<td>No.</td>
				<td>Name</td>
				<td>Position</td>
				<td>Salary</td>
				<td>Dept Code</td>
			</tr>
			<tr>
				<c:if test="${empty list }">
					<tr>
						<td colspan="5">No Employees.</td>
					</tr>
				</c:if>
				<c:if test="${not empty list }">
					<c:forEach var="emp" items="${list }">
						<tr>
							<td>${emp.empno }</td>
							<td><a href="empView.do?empno=${emp.empno}"
								   class="btn btn-info">${emp.ename}</a></td>
							<td>${emp.job}</td>
							<td>${emp.sal}</td>
							<td>${emp.deptno}</td>
						</tr>
					</c:forEach>
				</c:if>
		</table>
		<a href="deptList.do" class="btn btn-success">Dept List</a> 
		<a href="empInsertForm.do" class="btn btn-success">New Emp</a>
		<div id="list"></div>
	</div>
</body>
</html>

To insert new employee data, click the New Emp button in the Emp List.

empInsertForm.java

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		$('#dupCheck').click(function() {
			var empno = $('#empno').val();
			if (!empno) {
				alert('Insert the Emp No first');
				$('#empno').focus();
				return false;
			}// $.post("요청이름","전달될 값","콜백함수");
			$.post('dupCheck.do', 'empno=' + empno, function(msg) {
				alert(msg);
			});
		});
	});
</script>
</head>
<body>
	<div class="container">
		<h2 class="text-primary">New Employee</h2>
		<form action="empInsert.do" method="post">
			<table class="table table-bordered">
				<tr>
					<td>Emp No</td>
					<td><input type="number" name="empno" required="required"
							   id="empno" autofocus="autofocus"> 
						<input type="button" value="Check" id="dupCheck"></td>
				</tr>
				<tr>
					<td>Name</td>
					<td><input type="text" name="ename" required="required"></td>
				</tr>
				<tr>
					<td>Position</td>
					<td><input type="text" name="job" required="required"></td>
				</tr>
				<tr>
					<td>Manager</td>
					<td><select name="mgr">
							<c:forEach var="emp" items="${empList }">
								<option value="${emp.empno}">${emp.ename}</option>
							</c:forEach>
					    </select>
					</td>
				</tr>
				<tr>
					<td>Hired date</td>
					<td><input type="date" name="hiredate" required="required"></td>
				</tr>
				<tr>
					<td>Salary</td>
					<td><input type="number" name="sal" required="required"></td>
				</tr>
				<tr>
					<td>Bonus</td>
					<td><input type="number" name="comm" required="required"></td>
				</tr>
				<tr>
					<td>Dept Code</td>
					<td><select name="deptno">
							<c:forEach var="dept" items="${deptList }">
								<option value="${dept.deptno}">${dept.dname}</option>
							</c:forEach>
						</select>
					</td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="Submit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

Once you get this alert box, you will see the emp number you inserted on the console. 

EmpController.java

// New Emp
@RequestMapping("empInsertForm.do")
	public String empInsertForm(Model model) {
		List<Dept> deptList = ds.list();
		List<Emp> empList = es.empList();
		model.addAttribute("deptList", deptList);
		model.addAttribute("empList", empList);
		return "emp/empInsertForm";
	}
// Emp Number Check
	@RequestMapping("dupCheck.do")
	public String dupCheck(int empno, Model model) {
		System.out.println("empno:"+empno);
		Emp emp = es.select(empno);
		String msg = "";
		if (emp != null)
			msg = "Overlapped Data";
		else
			msg = "Available emp Number";
		model.addAttribute("msg", msg);
		return "emp/dupCheck";
	}

	@RequestMapping("empInsert.do")
//	public String empInsert(Emp emp, String hiredate1, Model model) {
	public String empInsert(Emp emp, Model model) {
//		emp.setHiredate(Date.valueOf(hiredate1)); // String -> Date Type Conversion
		int result = es.insert(emp);
		model.addAttribute("result", result);
		model.addAttribute("deptno", emp.getDeptno());
		return "emp/empInsert";
	}

To Edit the emp click the name of the employees and see the detail page. 

empView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		$('#list').load('empList.do?deptno=${emp.deptno}');
	});
</script>
</head>
<body>
	<div class="container">
		<h2 class="text-primary">Employee Detail</h2>
		<table class="table table-bordered">
			<tr>
				<td>Emp No.</td>
				<td>${emp.empno }</td>
			</tr>
			<tr>
				<td>Name</td>
				<td>${emp.ename}</td>
			</tr>
			<tr>
				<td>Position</td>
				<td>${emp.job }</td>
			</tr>
			<tr>
				<td>Manager</td>
				<td>${emp.mgr }</td>
			</tr>
			<tr>
				<td>Hired Date</td>
				<td>${emp.hiredate }</td>
			</tr>
			<tr>
				<td>Salary</td>
				<td>${emp.sal }</td>
			</tr>
			<tr>
				<td>Bonus</td>
				<td>${emp.comm }</td>
			</tr>
			<tr>
				<td>Dept Code</td>
				<td>${emp.deptno }</td>
			</tr>
		</table>
		<a href="empUpdateForm.do?empno=${emp.empno}" class="btn btn-info">Edit</a>
		<a class="btn btn-danger" href="empDelete.do?empno=${emp.empno}">Delete</a>
		<a href="empList.do?deptno=${emp.deptno}" class="btn btn-default">List</a>
		<div id="list"></div>
	</div>
</body>
</html>

Click Edit or Delete to process.

empUpdateForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div class="container" align="center">
		<h2 class="text-primary">Edit Employee Information</h2>
		<form action="empUpdate.do" method="post">
			<table class="table table-bordered">
				<tr>
					<td>Emp No.</td>
					<td><input type="text" name="empno" readonly="readonly"
						value="${emp.empno}"></td>
				</tr>
				<tr>
					<td>Name</td>
					<td><input type="text" name="ename" required="required"
						value="${emp.ename }"></td>
				</tr>
				<tr>
					<td>Position</td>
					<td><input type="text" name="job" required="required"
						value="${emp.job }"></td>
				</tr>
				<tr>
					<td>Salary</td>
					<td><input type="text" name="sal" required="required"
						value="${emp.sal}"></td>
				</tr>
				<tr>
					<td>Bonus</td>
					<td><input type="text" name="comm" required="required"
						value="${emp.comm }"></td>
				</tr>
				<tr>
					<td>Dept Code.</td>
					<td><select name="deptno">
							<c:forEach var="dept" items="${deptList}">
								<c:if test="${emp.deptno==dept.deptno}">
									<option value="${dept.deptno}" selected="selected">
										${dept.dname}(${dept.deptno})</option>
								</c:if>
								<c:if test="${emp.deptno!=dept.deptno}">
									<option value="${dept.deptno}">${dept.dname}(${dept.deptno})</option>
								</c:if>
							</c:forEach>
					</select></td>
				</tr>
				<tr>
					<td colspan="2"><input type="submit" value="Edit"></td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

EmpController.java

// Update Emp Information
@RequestMapping("empUpdateForm.do")
	public String empUpdateForm(int empno, Model model) {
		Emp emp = es.select(empno);
		List<Dept> deptList = ds.list();
		model.addAttribute("emp", emp);
		model.addAttribute("deptList", deptList);
		return "emp/empUpdateForm";
	}

	@RequestMapping("empUpdate.do")
	public String empUpdate(Emp emp, Model model) {
		int result = es.update(emp);
		model.addAttribute("deptno", emp.getDeptno());
		model.addAttribute("result", result);
		return "emp/empUpdate";
	}

 

To delete,

empDelete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../header.jsp"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:if test="${result > 0 }">
		<script type="text/javascript">
			alert("Successfully deleted. ");
			location.href = "empList.do?deptno=${deptno}";
		</script>
	</c:if>
	<c:if test="${result <= 0 }">
		<script type="text/javascript">
			alert("Failed to delete.");
			history.go(-1);
		</script>
	</c:if>
</body>
</html>

EmpController.java

// Delete Emp
@RequestMapping("empDelete.do")
	public String empDelete(int empno, Model model) {
		Emp emp = es.select(empno);
		int result = es.delete(empno);
		model.addAttribute("result", result);
		model.addAttribute("deptno", emp.getDeptno());
		return "emp/empDelete";
	}

 

Matin Functions

1. Reply 

2. File upload/download - cos library

3. Request object

4. Controller Class : Java Servlet

5. Model = Service + DAO 

6. View UI Interface : EL, JSTL 

 

Structures

Model2
MyBatis

Action Interface inheritance

db.properties 

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=totoro
jdbc.password=totoro123

 

model2.sql

select * from tab;
select * from seq;
select * from model22;

create table model22(
	board_num number,
	board_name varchar2(20),
	board_pass varchar2(15),
	board_subject varchar2(50),
	board_content varchar2(2000),
	board_file varchar2(50),
	board_re_ref number,
	board_re_lev number,
	board_re_seq number,
	board_readcount number,
	board_date timestamp,
	primary key(board_num)
);

create sequence model22_seq
start with 1
increment by 1
nocache;

mybatis-config.xml 

<typeAlias> <properties> <mappers>

<?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="db.properties" />
	<typeAliases>
		<typeAlias type="model.BoardBean" alias="board"></typeAlias>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="board.xml" />
	</mappers>
</configuration>

index.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>
</head>
<body>

Bulletin Board
 
<%
	response.sendRedirect("./BoardListAction.do");
%> 

<script>
//	location.href="./BoardListAction.do";
</script>

</body>
</html>

qna_board_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
   

<a href="./BoardForm.do">New Post</a> <br>
Total Posts : ${listcount} 

<table border=1 width=700 align=center>
	<caption>Posts List</caption>
	<tr>
		<th>No.</th>
		<th>Title</th>
		<th>Writer</th>
		<th>Date</th>
		<th>View</th>
	</tr>
		
	<c:set var="num" value="${listcount - (page-1) * 10 }"/>	
	<c:forEach var="b" items="${boardlist}">
	<tr>
		<td>
			${num}
			<c:set var="num" value="${num-1}"/>
		</td>	
		<td>
		<c:if test="${b.board_re_lev > 0}">
			<c:forEach var="i" begin="0" end="${b.board_re_lev}">
				&nbsp;
			</c:forEach>
		</c:if>
		<c:if test="${b.board_re_lev > 0}">
			Re.
		</c:if>
		<a href="./BoardDetailAction.do?board_num=${b.board_num}&page=${page}">
			 ${b.board_subject}
		</a>
		
		</td>	
		<td>${b.board_name}</td>	
		<td>
		
		<fmt:formatDate value="${b.board_date}" pattern="yyyy-MM-dd H:mm"/>
		
		</td>	
		<td>${b.board_readcount}</td>	
	</tr>
	</c:forEach>

</table><br>


<center>
<c:if test="${listcount > 0}">

	<a href="./BoardListAction.do?page=1" style="text-decoration:none"> < </a>

	<c:if test="${startPage > 10}">
		<a href="./BoardListAction.do?page=${startPage - 10}">[Prev]</a>
	</c:if>

	<c:forEach var="i" begin="${startPage}" end="${endPage}">
		<c:if test="${i == page}">
			[${i}]
		</c:if>
		<c:if test="${i != page}">
			<a href="./BoardListAction.do?page=${i}">[${i}]</a>
		</c:if>
	</c:forEach>

	<c:if test="${endPage < pageCount}">
		<a href="./BoardListAction.do?page=${startPage + 10}">[Next]</a>
	</c:if>
	
	<a href="./BoardListAction.do?page=${pageCount}" style="text-decoration:none"> > </a>	

</c:if>
</center>

Controller Class(List)

//List
		}else if(command.equals("/BoardListAction.do")) {
			try {
				action = new BoardListAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

BoardListAction.java

Pagination

package service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;

public class BoardListAction implements Action{
	
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardListAction");
	
		int page=1;  
		int limit=10;  /
		
		if(request.getParameter("page")!=null) {
			page = Integer.parseInt(request.getParameter("page"));					
		}
		
		int startRow = (page-1) * limit + 1; 
		int endRow = page * limit;  
		
		List boardlist = null; 
		BoardDAO dao = BoardDAO.getInstance();		
		int listcount = dao.getCount(); 
//		boardlist = dao.getList(startRow, endRow);
//		boardlist = dao.getList(page);

//      Map	----------------------------------	
		Map map = new HashMap();
		map.put("start", startRow);
		map.put("end", endRow);
		
		boardlist = dao.getList(page);		
//		boardlist = dao.getList(map);
//-------------------------------------------------		
		System.out.println("listcount:"+listcount);
		System.out.println("boardlist:"+boardlist);		
		
		int pageCount = listcount/limit + ((listcount%limit==0) ? 0:1);
		
		int startPage = ((page-1)/10) * limit + 1;   
		int endPage = startPage + 10 - 1; 
		
		if(endPage > pageCount) endPage = pageCount;
		
		request.setAttribute("page", page);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", boardlist);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("startPage", startPage);
		request.setAttribute("endPage", endPage);		
		
		//<c:forEach items="${}"> </forEach>
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/board/qna_board_list.jsp");
		
		return forward;
	}

}

DAO Class(List)

// List
	public List getList(int page) throws Exception {
//	public List getList(Map map) throws Exception {
		List list = new ArrayList();
		SqlSession session=getSession();
		list = session.selectList("board_list", page); 
		
		return list;
	}
	
	
	// View +1
	public void updateCount(int board_num) throws Exception{
		SqlSession session = getSession();
		session.update("board_updatecount", board_num);
	}

Mapper Class(Main post)

<!-- page -->
	<select id="board_list" parameterType="int" resultType="board">
	 select * from (select rownum rnum, board.* from (
	  select * from model22 order by board_re_ref desc,board_re_seq asc) board )
	  where rnum &gt;= (#{page}-1) * 10 + 1   and rnum &lt;= #{page}*10
	</select>  
	
<!-- Map -->
<!-- 	<select id="board_list" parameterType="Map" resultType="board">
	 select * from (select rownum rnum, board.* from (
	  select * from model22 order by board_re_ref desc,board_re_seq asc) board )
	  where rnum &gt;= #{start} and rnum &lt;= #{end}
	</select>  -->

qna_board_write.jsp

For the file attachment function, you need to include enctype="multiypart/form-date" in the form tag.

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

<html>
<head>
	<title>MVC Bulletin board with MyBatis</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardAddAction.do" method="post" 
	  enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td colspan="5">Bulletin Boarc</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Writer</div>
		</td>
		<td>
			<input name="board_name" id="board_name" type="text" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Title</div>
		</td>
		<td>
			<input name="board_subject" id="board_subject" type="text" size="50" maxlength="100" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">Content</div>
		</td>
		<td>
			<textarea name="board_content" id="board_content" cols="67" rows="15"></textarea>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">Attach File</div>
		</td>
		<td>
			<input name="board_file" type="file"/>
		</td>
	</tr>
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Submit">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

Controller Class(New Post)

// New Post
		if(command.equals("/BoardAddAction.do")) {
			try {
				action = new BoardAddAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		
// New Post form
		}else if(command.equals("/BoardForm.do")) {	
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/board/qna_board_write.jsp");

BoardAddAction.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import dao.BoardDAO;
import model.BoardBean;

public class BoardAddAction implements Action{
	
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardAddAction");
		
		String path = request.getRealPath("boardupload");
		System.out.println("path:"+path);
		
		int size = 1024 * 1024; // 1MB
		
		MultipartRequest multi = 
			new MultipartRequest(request,
								 path,
					             size,
					             "utf-8",
						         new DefaultFileRenamePolicy());
		
		BoardBean board = new BoardBean();
		board.setBoard_name(multi.getParameter("board_name"));
		board.setBoard_pass(multi.getParameter("board_pass"));
		board.setBoard_subject(multi.getParameter("board_subject"));
		board.setBoard_content(multi.getParameter("board_content"));
		board.setBoard_file(multi.getFilesystemName("board_file"));
		
		BoardDAO dao = BoardDAO.getInstance();
		int result = dao.insert(board);
		if(result==1) {
			System.out.println("insert");
		}
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(true);
		forward.setPath("./BoardListAction.do");
		
		return forward;
	}

}

DAO Class (Main Post)

//Main Post(New post)
	public int insert(BoardBean board) throws Exception {
		int result=0;
		SqlSession session = getSession();
		result = session.insert("board_insert", board);		
		System.out.println("result:"+result);
		
		return result;
	}

Mapper Class(New Post)

<!-- New Post -->
	<insert id="board_insert" parameterType="board">
	 insert into model22 values(model22_seq.nextval,#{board_name},
	 #{board_pass},#{board_subject},#{board_content},
	 #{board_file,jdbcType=VARCHAR},model22_seq.nextval,0,0,0,sysdate)
	</insert>

qna_board_view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 
    
<table border=1 width=600 align=center>
	<caption>Detail</caption>
	<tr>
		<td>Writer</td>
		<td>${board.board_name}</td>
	</tr>
	<tr>
		<td>View</td>
		<td>${board.board_readcount}</td>
	</tr>
	<tr>
		<td>Date</td>
		<td>
			<fmt:formatDate value="${board.board_date}"
							pattern="MM/dd/yyyy H:mm"/>		
		</td>
	</tr>
	<tr>
		<td>Title</td>
		<td>${board.board_subject}</td>
	</tr>
	<tr>
		<td>Content</td>
		<td><pre>${board.board_content}</pre></td>
	</tr>
	<tr>
		<td>Attached File</td>
		<td>
			<c:if test="${board.board_file !=  null }">
				<a href="./board/file_down.jsp?file_name=${board.board_file}">${board.board_file}</a>
			</c:if>
		</td>
	</tr>
	<tr>
		<td colspan=2 align=center>
			<input type="button" value="Reply" 
				   onClick="location.href='./BoardReplyAction.do?board_num=${board.board_num}&page=${page}&board_re_ref=${board.board_re_ref}&board_re_lev=${board.board_re_lev}&board_re_seq=${board.board_re_seq}'">
			<input type="button" value="Edit" 
				   onClick="location.href='./BoardModifyAction.do?board_num=${board.board_num}&page=${page}'">
			<input type="button" value="Delete" 
				   onClick="location.href='./BoardDeleteAction.do?board_num=${board.board_num}&page=${page}'">
			<input type="button" value="List" 
			       onClick="location.href='./BoardListAction.do?page=${page}'">
		</td>
	</tr>
</table>

Controller Class(Detail Page)

// Detail Page	
		}else if(command.equals("/BoardDetailAction.do")) {
			try {
				action = new BoardDetailAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

BoardDetailAction.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardDetailAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardDetailAction");
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		
		BoardDAO dao = BoardDAO.getInstance();
//		BoardBean board = dao.updateContent(board_num);
		
		//Viewcount +1
		dao.updateCount(board_num);
		BoardBean board = dao.getContent(board_num);
		
		request.setAttribute("board", board);
		request.setAttribute("page", page);
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/board/qna_board_view.jsp");
		
		return forward;
	}

}

DAO Class(Detail)

// Detail Page
	public BoardBean getContent(int board_num) throws Exception {
		BoardBean board = new BoardBean();

		SqlSession session=getSession();
		board  = (BoardBean)session.selectOne("board_content", board_num);
		
		return board;
	}

Mapper Class(Detail)

<!-- Detail Page -->
	<select id="board_content" parameterType="int" resultType="board">
	 select * from model22 where board_num = #{board_num}
	</select>

qna_board_reply.jsp

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

<html>
<head>
	<title>Bulletin Board</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardReply.do" method="post">
<input type="hidden" name="board_num" value="${param.board_num}">
<input type="hidden" name="page" value="${param.page}">
<input type="hidden" name="board_re_ref" value="${param.board_re_ref}">
<input type="hidden" name="board_re_lev" value="${param.board_re_lev}">
<input type="hidden" name="board_re_seq" value="${param.board_re_seq}">

<table cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td colspan="5">Reply</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Writer</div>
		</td>
		<td>
			<input name="board_name" id="board_name" type="text" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Title</div>
		</td>
		<td>
			<input name="board_subject" id="board_subject" type="text" size="50" maxlength="100" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">Content</div>
		</td>
		<td>
			<textarea name="board_content" id="board_content" cols="67" rows="15"></textarea>
		</td>
	</tr>	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Submit">
			<input type=reset value="Canel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

Controller Class(Reply)

// Reply form
		}else if(command.equals("/BoardReplyAction.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/board/qna_board_reply.jsp");
			
// Reply	
		}else if(command.equals("/BoardReply.do")) {
			try {
				action = new BoardReply();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

 

BoardReply.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardReply implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardReply");
		
		request.setCharacterEncoding("utf-8");
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		int board_re_ref = Integer.parseInt(request.getParameter("board_re_ref"));
		int board_re_lev = Integer.parseInt(request.getParameter("board_re_lev"));
		int board_re_seq = Integer.parseInt(request.getParameter("board_re_seq"));
		String page = request.getParameter("page");
		
		BoardBean board = new BoardBean();
		board.setBoard_re_ref(board_re_ref);
		board.setBoard_re_seq(board_re_seq);
		
		BoardDAO dao = BoardDAO.getInstance();
		dao.updateSeq(board); 			
		
		board.setBoard_re_seq(board_re_seq+1);
		board.setBoard_re_lev(board_re_lev+1);		
		board.setBoard_name(request.getParameter("board_name"));
		board.setBoard_pass(request.getParameter("board_pass"));
		board.setBoard_subject(request.getParameter("board_subject"));
		board.setBoard_content(request.getParameter("board_content"));
					
		dao.boardReply(board);		
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/BoardDetailAction.do?board_num="+board_num+"&page="+page);
		
		return forward;
	}

}

DAO Class(Reply)

// Reply Print Order (board_re_seq value +1)
	public void updateSeq(BoardBean board) {
		SqlSession session = getSession();
		session.update("board_updateseq", board);
	}
		
// Write Reply
	public void boardReply(BoardBean board) {
		SqlSession session = getSession();
		session.insert("board_reply", board);
	}

Mapper Class(Reply)

<!-- Reply Print Order -->
	<update id="board_updateseq" parameterType="board">
	 update model22 set board_re_seq=board_re_seq+1 
	  where board_re_ref = #{board_re_ref} and board_re_seq &gt; #{board_re_seq}
	</update>
	
	<!-- Write Reply -->
	<insert id="board_reply" parameterType="board">
	 insert into model22 values(model22_seq.nextval,#{board_name},
	 #{board_pass},#{board_subject},#{board_content},
	 #{board_file,jdbcType=VARCHAR},#{board_re_ref},#{board_re_lev},#{board_re_seq},0,sysdate)
	</insert>

qna_board_modify.jsp

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

<html>
<head>
	<title>Edit</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardModify.do" method="post">
<input type="hidden" name="board_num" value="${board.board_num}">
<input type="hidden" name="page" value="${page}">

<table cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td colspan="5">Edit</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Writer</div>
		</td>
		<td>
			<input name="board_name" id="board_name" type="text" size="10" maxlength="10" 
				value="${board.board_name }"/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">제 목</div>
		</td>
		<td>
			<input name="board_subject" id="board_subject" type="text" size="50" maxlength="100" 
				value="${board.board_subject}"/>
		</td>
	</tr>
	<tr>
		<td style="font-family:돋음; font-size:12">
			<div align="center">Content</div>
		</td>
		<td>
			<textarea name="board_content" id="board_content" cols="67" rows="15">${board.board_content}</textarea>
		</td>
	</tr>	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Edit">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

Controller Class 

// Edit form
		}else if(command.equals("/BoardModifyAction.do")) {
			try {
				action = new BoardModifyAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

// Edit
		}else if(command.equals("/BoardModify.do")) {
			try {
				action = new BoardModify();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

BoardModifyAction.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardModifyAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardModifyAction");
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		
		BoardDAO dao = BoardDAO.getInstance();
		BoardBean board = dao.getContent(board_num);
				
		request.setAttribute("board", board);
		request.setAttribute("page", page);
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/board/qna_board_modify.jsp");
		
		return forward;
	}

}

BoardModify.java

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardModify implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardModify");
		
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String page = request.getParameter("page");
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String board_pass = request.getParameter("board_pass");
		
		BoardBean board = new BoardBean();
		board.setBoard_num(board_num);
		board.setBoard_name(request.getParameter("board_name"));
		board.setBoard_subject(request.getParameter("board_subject"));
		board.setBoard_content(request.getParameter("board_content"));
		
		BoardDAO dao = BoardDAO.getInstance();
		BoardBean old = dao.getContent(board_num);
		
		if(old.getBoard_pass().equals(board_pass)) {// Correct Password
			dao.update(board);
			
		}else {	// Incorrect Password
			
			out.println("<script>");
			out.println("alert('Incorrect Password.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();
			
			return null;
		}		
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/BoardDetailAction.do?board_num="+board_num+"&page="+page);
		
		return forward;
	}

}

DAO Class(Edit)

// Edit
	public void update(BoardBean board) throws Exception {
		SqlSession session=getSession();
		session.update("board_update", board);
	}

Mapper Class(Edit)

<!-- Edit -->
	<update id="board_update" parameterType="board">
	 update model22 set board_name=#{board_name}, board_subject=#{board_subject},
	 board_content=#{board_content} where board_num=#{board_num}
	</update>

qna_board_delete.jsp

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

<html>
<head>
	<title>Delete</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardDelete.do" method="post">
<input type="hidden" name="board_num" value="${param.board_num}">
<input type="hidden" name="page" value="${param.page}">

<table width=300 cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td colspan="5">Delete</td>
	</tr>	
	<tr>
		<td style="font-family:돋음; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>	
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Delete">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

Controller Class(Delete)

// Delete form
		}else if(command.equals("/BoardDeleteAction.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/board/qna_board_delete.jsp");
			
// Delete
		}else if(command.equals("/BoardDelete.do")) {
			try {
				action = new BoardDelete();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

BoardDeleteAction.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BoardDeleteAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardDeleteAction");
		ActionForward forward = new ActionForward();
		
		return forward;
	}

}

BoardDelete.java

package service;

import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardDelete implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardDelete");
		
		response.setContentType("text/html; charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String path = request.getRealPath("boardupload");
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		String board_pass  = request.getParameter("board_pass");
				
		BoardDAO dao = BoardDAO.getInstance();
		BoardBean old = dao.getContent(board_num);
		
		if(old.getBoard_pass().equals(board_pass)) { //Correct Password
			dao.delete(board_num);
			
			if(old.getBoard_file() != null) {
				
				File file = new File(path);
				file.mkdirs();
				
				File[] f = file.listFiles();
				for(int i=0; i<f.length; i++) {
					if(f[i].getName().equals(old.getBoard_file())) {
						f[i].delete();
					}
				}				
			}
			
		}else {	// Incorrect Password
	
			out.println("<script>");
			out.println("alert('Incorrect Password.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();

			return null;			
		}
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/BoardListAction.do?page="+page);
		
		return forward;
	}

}

DAO Class(Delete)

// Delete
	public void delete(int board_num) {
		SqlSession session=getSession();
		session.delete("board_delete", board_num);
	}

Mapper Class(Delete)

<!-- Delete -->
	<delete id="board_delete" parameterType="int">
	 delete from model22 where board_num=#{board_num}
	</delete>

Sequence : View -> Controller class -> Service class -> DAO -> Mapper class

Please refer to the last post if you want to see the project structure, Sign up, and the Log in part.

2022.10.01 - [Codes & Projects] - MyBatis / Maven / JavaScript / JSP /MVC) Model2 MyBatis Costumer Management System(Korean) 회원관리 [1]- Sign up / Log in

 

Structure

 

Model2
MyBatis

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> --%> <!-- 안됨 -->


<!--  세션이 있으면 -->
<%-- <c:if test="${not empty sessionScope.id}"> --%>	<!-- 2개 모두 잘됨 -->
<c:if test="${sessionScope.id != null }">
	${sessionScope.id} 님 환영 합니다. <br><br>
	
	<a href="<%=request.getContextPath() %>/UpdateMember.do">회원정보 수정</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/Logout.do">로그아웃</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/DeleteMember.do">회원탈퇴</a> <br><br>
</c:if>

<!-- 세션이 없으면 -->
<%-- <c:if test="${empty sessionScope.id}"> --%>
<c:if test="${sessionScope.id == null}">
	<a href="<%=request.getContextPath() %>/MemberForm.do">회원가입</a> <br><br>
	<a href="<%=request.getContextPath() %>/LoginForm.do">로그인</a> <br><br>
</c:if>

logout.jsp

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

<%	// 세션 삭제
	session.invalidate();
%>

<script>
	alert("로그아웃");
	location.href="./LoginForm.do";
</script>

updateform.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>회원 수정 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
//				document.getElementById('join_zip1').value = data.postcode1;
//				document.getElementById('join_zip2').value = data.postcode2;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>


<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="<%=request.getContextPath() %>/member/member.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/Update.do"> 
<input type="hidden" name="id" value="${member.id}">
<table border=1 width=500 align=center>
	<caption>회원 수정</caption>
	<tr><td>ID</td>
		<td>${member.id}</td>
	</tr>
	<tr><td>비밀번호</td>
		<td><input type=password id="passwd" name="passwd"></td>
	</tr>
	<tr><td>성명</td>
		<td><input type=text id="name" name="name" value="${member.name}"></td>
	</tr>
	<tr><td>주민번호</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1" value="${member.jumin1}">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2" value="${member.jumin2}">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid" value="${member.mailid}">@
		    <input type=text size=10 id="domain" name="domain" value="${member.domain}">
		    <select id="email">
		    	<option value="">직접입력</option>
		    	<option value="naver.com">네이버</option>
		    	<option value="daum.net">다음</option>
		    	<option value="nate.com">네이트</option>
		    	<option value="gmail.com">gmail</option>
		    </select>		    
		 </td>
	</tr>
	<tr><td>전화번호</td>
		<td><input type=text size=4 id="tel1" name="tel1" maxlength=4 value="${member.tel1 }">-
			<input type=text size=4 id="tel2" name="tel2" maxlength=4 value="${member.tel2 }">-
			<input type=text size=4 id="tel3" name="tel3" maxlength=4 value="${member.tel3 }">
		</td>
	</tr>
	<tr><td>핸드폰</td>
		<td><select id="phone1" name="phone1">
				<option value="">번호선택</option>
				<option value="010" <c:if test="${member.phone1 == '010' }">${'selected'}</c:if> >010</option>
				<option value="011" <c:if test="${member.phone1 == '011' }">${'selected'}</c:if> >011</option>
				<option value="016" <c:if test="${member.phone1 == '016' }">${'selected'}</c:if> >016</option>
				<option value="018" <c:if test="${member.phone1 == '018' }">${'selected'}</c:if> >018</option>
				<option value="019" <c:if test="${member.phone1 == '019' }">${'selected'}</c:if> >019</option>
			</select>-
			<input type=text size=4 id="phone2" name="phone2" maxlength=4 value="${member.phone2 }">-
			<input type=text size=4 id="phone3" name="phone3" maxlength=4 value="${member.phone3 }">
		</td>
	</tr>
	<tr><td>우편번호</td>
		<td><input type=text size=5 id="post" name="post" value="${member.post }">
			<input type=button value="우편번호검색" 
			       onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>주소</td>
		<td><input type=text size=45 id="address" name="address" value="${member.address }"></td>
	</tr>
	<tr><td>성별</td>
		<td>
		
		<c:if test="${member.gender == '남자' }">
			<input type=radio id="male" name="gender" value="남자" checked="checked">남자
			<input type=radio id="female" name="gender" value="여자">여자
			<input type=radio id="others" name="gender" value="기타">기타
		</c:if>
		<c:if test="${member.gender == '여자' }">
			<input type=radio id="male" name="gender" value="남자">남자
			<input type=radio id="female" name="gender" value="여자" checked="checked">여자
			<input type=radio id="others" name="gender" value="기타">기타
		</c:if>			
			
		</td>
	</tr>
	<tr><td>취미</td>
		<td>
			<input type="checkbox" id="h1" name="hobby" value="공부"
		<c:forEach var="i" items="${h}">
			<c:if test="${i=='공부'}">${'checked'}</c:if>
		</c:forEach> >공부
		
			<input type="checkbox" id="h2" name="hobby" value="게임"
		<c:forEach var="i" items="${h}">	
			<c:if test="${i=='게임'}">${'checked'}</c:if>
		</c:forEach> >게임
			
			<input type="checkbox" id="h3" name="hobby" value="등산"
		<c:forEach var="i" items="${h}">	
			<c:if test="${i=='등산'}">${'checked'}</c:if>
		</c:forEach> >등산
			
			<input type="checkbox" id="h4" name="hobby" value="낚시"
		<c:forEach var="i" items="${h}">	
			<c:if test="${i=='낚시'}">${'checked'}</c:if>
		</c:forEach> >낚시
			
			<input type="checkbox" id="h5" name="hobby" value="쇼핑"
		<c:forEach var="i" items="${h}">	
			<c:if test="${i=='쇼핑'}">${'checked'}</c:if>
		</c:forEach> >쇼핑
			
		</td>
	</tr>	
	<tr><td>자기소개</td>
		<td>
			<textarea id="intro" name="intro" rows="5" cols="50" placeholder="자기소개를 100자 이내로 입력하세요">${member.intro }</textarea>
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="회원수정">
			<input type=reset value="취소">
		</td>
	</tr>		
</table>
</form>


</body>
</html>

 

Update.java

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MemberDAO;
import model.MemberDTO;

public class Update implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Update");
		
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		MemberDTO member = new MemberDTO();
		member.setId(request.getParameter("id"));
		member.setPasswd(request.getParameter("passwd"));
		member.setName(request.getParameter("name"));
		member.setJumin1(request.getParameter("jumin1"));
		member.setJumin2(request.getParameter("jumin2"));
		member.setMailid(request.getParameter("mailid"));
		member.setDomain(request.getParameter("domain"));
		member.setTel1(request.getParameter("tel1"));
		member.setTel2(request.getParameter("tel2"));
		member.setTel3(request.getParameter("tel3"));
		member.setPhone1(request.getParameter("phone1"));
		member.setPhone2(request.getParameter("phone2"));
		member.setPhone3(request.getParameter("phone3"));
		member.setPost(request.getParameter("post"));
		member.setAddress(request.getParameter("address"));
		member.setGender(request.getParameter("gender"));
		
		String h="";
		String[] h1 = request.getParameterValues("hobby");
		for(String h2 : h1) {
			h += h2+"-";			// h = "공부-게임-등산-"
		}
		member.setHobby(h);
		member.setIntro(request.getParameter("intro"));
		
		MemberDAO dao = MemberDAO.getInstance();
		MemberDTO old = dao.getMember(member.getId());
		
		// 비번 비교
		if(old.getPasswd().equals(member.getPasswd())) { //비번 일치시
			int result = dao.update(member);
			if(result==1) System.out.println("회원수정 성공");
			
		}else {											 //비번 불일치시
			out.println("<script>");
			out.println("alert('비번이 일치하지 않습니다.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();
			
			return null;
		}	
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/member/main.jsp");
		
		return forward;
	}

}

UpdateMember.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.MemberDAO;
import model.MemberDTO;

public class UpdateMember implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("UpdateMember");
		
		HttpSession session = request.getSession();
		String id = (String)session.getAttribute("id");
		System.out.println("id:"+id);
		
		MemberDAO dao = MemberDAO.getInstance();
		MemberDTO member = dao.getMember(id);
		System.out.println("member:"+member);
		
		String hobby = member.getHobby();	// "공부-게임-등산-"
		String[] h = hobby.split("-");
		
		request.setAttribute("member", member);				
		request.setAttribute("h", h);				
		
		ActionForward forward = new ActionForward();	
		forward.setRedirect(false);        // dispatcher 방식으로 포워딩
		forward.setPath("/member/updateform.jsp");
		
		return forward;
	}

}

Update part in DAO Class

// 회원 1명 정보 구하기 : 수정폼, 수정, 삭제
	public MemberDTO getMember(String id) throws Exception{
		SqlSession session = getSession();
		MemberDTO member = session.selectOne("idcheck", id);
		
		return member;
	}
	
	
	// 회원정보 수정
	public int update(MemberDTO member) throws Exception{
		int result = 0;
		SqlSession session = getSession();
		result = session.update("update", member);

		return result;
	}

Update part in MemberController Class

// 회원정보 수정폼	
		}else if(command.equals("/UpdateMember.do")) {
			try {
				action = new UpdateMember();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
// 회원정보 수정	
		}else if(command.equals("/Update.do")) {
			try {
				action = new Update();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> --%> <!-- 안됨 -->


<!--  세션이 있으면 -->
<%-- <c:if test="${not empty sessionScope.id}"> --%>	<!-- 2개 모두 잘됨 -->
<c:if test="${sessionScope.id != null }">
	${sessionScope.id} 님 환영 합니다. <br><br>
	
	<a href="<%=request.getContextPath() %>/UpdateMember.do">회원정보 수정</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/Logout.do">로그아웃</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/DeleteMember.do">회원탈퇴</a> <br><br>
</c:if>

<!-- 세션이 없으면 -->
<%-- <c:if test="${empty sessionScope.id}"> --%>
<c:if test="${sessionScope.id == null}">
	<a href="<%=request.getContextPath() %>/MemberForm.do">회원가입</a> <br><br>
	<a href="<%=request.getContextPath() %>/LoginForm.do">로그인</a> <br><br>
</c:if>

 

deleteform.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>회원 탈퇴</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="<%=request.getContextPath() %>/member/member.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/Delete.do"> 
<input type="hidden" name="id" value="${sessionScope.id}">
<table border=1 width=500 align=center>
	<caption>회원 탈퇴</caption>	
	<tr><td>비밀번호</td>
		<td><input type=password id="passwd" name="passwd"></td>
	</tr>	
	<tr><td colspan=2 align=center>
			<input type=submit value="회원탈퇴">
			<input type=reset value="취소">
		</td>
	</tr>		
</table>
</form>


</body>
</html>

MemberController.java

// 회원탈퇴 폼	
		}else if(command.equals("/DeleteMember.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/member/deleteform.jsp");
			
// 회원탈퇴	
		}else if(command.equals("/Delete.do")) {
			try {
				action = new Delete();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}

Delete.java

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.MemberDAO;
import model.MemberDTO;

public class Delete implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Delete");
		
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");
		
		MemberDAO dao = MemberDAO.getInstance();
		MemberDTO old = dao.getMember(id);
		
		// 비번 비교
		if(old.getPasswd().equals(passwd)) {	// 비번 일치시
			int result = dao.delete(id);
			if(result == 1) System.out.println("회원삭제 성공");
			
			session.invalidate();               // 세션 삭제
			
		}else {									// 비번 불일치시
			out.println("<script>");	
			out.println("alert('비번이 일치하지 않습니다.');");	
			out.println("history.go(-1);");	
			out.println("</script>");	
			out.close();
			
			return null;			
		}
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/LoginForm.do");
		
		return forward;
	}

}

MemberDAO.java

// 회원 1명 정보 구하기 : 수정폼, 수정, 삭제
	public MemberDTO getMember(String id) throws Exception{
		SqlSession session = getSession();
		MemberDTO member = session.selectOne("idcheck", id);
		
		return member;
	}
	
// 회원 탈퇴
	public int delete(String id) throws Exception{
		int result = 0;
		SqlSession session = getSession();
		result = session.delete("delete", id);		
		
		return result;
	}

 

Structures

Model2
MyBatis

This will be the structure of the mybatismember maven project after we complete them.

model2member.sql

-- 회원관리
select * from tab;
select * from member0609;

create table member0609(
	id varchar2(20) primary key,
	passwd  varchar2(20) not null,
	name varchar2(20) not null,
	jumin1 varchar2(6) not null,
	jumin2 varchar2(7) not null,
	mailid varchar2(30), 
	domain varchar2(30), 
	tel1 varchar2(5),
	tel2 varchar2(5),
	tel3 varchar2(5),
	phone1 varchar2(5),
	phone2 varchar2(5),
	phone3 varchar2(5),
	post varchar2(10),
	address varchar2(200),
	gender varchar2(20),
	hobby varchar2(50),
	intro varchar2(2000),
	register timestamp );

MemberDTO.java

The properties and the column names have to be the same, not to map them in the mapper file. 

// DTO(Data Transfer Object)

package model;

import java.sql.Timestamp;

public class MemberDTO {
	private String id;
	private String passwd;
	private String name;
	private String jumin1;
	private String jumin2;
	private String mailid;
	private String domain;
	private String tel1;
	private String tel2;
	private String tel3;
	private String phone1;
	private String phone2;
	private String phone3;
	private String post;
	private String address;
	private String gender;
	private String hobby;
	private String intro;
	private Timestamp register;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJumin1() {
		return jumin1;
	}
	public void setJumin1(String jumin1) {
		this.jumin1 = jumin1;
	}
	public String getJumin2() {
		return jumin2;
	}
	public void setJumin2(String jumin2) {
		this.jumin2 = jumin2;
	}
	public String getMailid() {
		return mailid;
	}
	public void setMailid(String mailid) {
		this.mailid = mailid;
	}
	public String getDomain() {
		return domain;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}
	public String getTel1() {
		return tel1;
	}
	public void setTel1(String tel1) {
		this.tel1 = tel1;
	}
	public String getTel2() {
		return tel2;
	}
	public void setTel2(String tel2) {
		this.tel2 = tel2;
	}
	public String getTel3() {
		return tel3;
	}
	public void setTel3(String tel3) {
		this.tel3 = tel3;
	}
	public String getPhone1() {
		return phone1;
	}
	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}
	public String getPhone2() {
		return phone2;
	}
	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}
	public String getPhone3() {
		return phone3;
	}
	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}
	public String getPost() {
		return post;
	}
	public void setPost(String post) {
		this.post = post;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getIntro() {
		return intro;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}

}

mybatis-cofig.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>
	<properties resource="db.properties" />
	<typeAliases>
		<typeAlias type="model.MemberDTO" alias="member"></typeAlias>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="member.xml" />
	</mappers>
</configuration>

 

MemberController.java

package controller;

import java.io.IOException;

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 service.Action;
import service.ActionForward;
import service.Delete;
import service.Idcheck;
import service.Login;
import service.MemberInsert;
import service.Update;
import service.UpdateMember;

/**
 * Servlet implementation class MemberController
 */
@WebServlet("*.do")
public class MemberController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();               
		String command = requestURI.substring(contextPath.length());  
		
		System.out.println("requestURI:"+requestURI);    // requestURI: /model2member/MemberInsert.do
		System.out.println("contextPath:"+contextPath);  // contextPath: /model2member
		System.out.println("command:"+command);          // command: /MemberInsert.do
		
		Action action = null;
		ActionForward forward = null;
		
		// 회원 가입
		if(command.equals("/MemberInsert.do")) {
			try {
				action = new MemberInsert();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		// 회원가입 폼	
		}else if(command.equals("/MemberForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(true);
			forward.setPath("./member/memberform.jsp");
			
		// ID중복 검사(ajax)	
		}else if(command.equals("/Idcheck.do")) {
			try {
				action = new Idcheck();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		// 로그인(회원인증)	
		}else if(command.equals("/Login.do")) {
			try {
				action = new Login();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		// 로그인 폼	
		}else if(command.equals("/LoginForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/member/loginform.jsp");	
			
		// 로그 아웃	
		}else if(command.equals("/Logout.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/member/logout.jsp");
			
		// 회원정보 수정폼	
		}else if(command.equals("/UpdateMember.do")) {
			try {
				action = new UpdateMember();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		// 회원정보 수정	
		}else if(command.equals("/Update.do")) {
			try {
				action = new Update();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		
		// 회원탈퇴 폼	
		}else if(command.equals("/DeleteMember.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("/member/deleteform.jsp");
			
		// 회원탈퇴	
		}else if(command.equals("/Delete.do")) {
			try {
				action = new Delete();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		// 포워딩 처리
		if(forward != null) {
			if(forward.isRedirect()) {		// redirect 방식으로 포워딩
				response.sendRedirect(forward.getPath());
			}else {							// dispatcher 방식으로 포워딩
				RequestDispatcher dispatcher = 
						request.getRequestDispatcher(forward.getPath());
				dispatcher.forward(request, response);
			}
		}		
		
	}// doProcess() end	
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("get");
	
		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
		System.out.println("post");
		
		doProcess(request, response);		
	}

}

member.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="mymember">

	<!-- 회원가입 -->
	<insert id="insert" parameterType="member">
	  insert into member0609 values(#{id},#{passwd},#{name},#{jumin1},#{jumin2},
	  #{mailid},#{domain},#{tel1},#{tel2},#{tel3},#{phone1},#{phone2},#{phone3},
	  #{post},#{address},#{gender},#{hobby},#{intro},sysdate)
	</insert>
	
	<!-- ID중복검사, 회원인증 -->
	<select id="idcheck" parameterType="String" resultType="member">
	 select * from member0609 where id = #{id}
	</select>
	
	<!-- 회원정보 수정 -->
	<update id="update" parameterType="member">
	  update member0609 set name=#{name}, jumin1=#{jumin1}, jumin2=#{jumin2}, 
	  mailid=#{mailid}, domain=#{domain}, tel1=#{tel1}, tel2=#{tel2}, tel3=#{tel3},
	  phone1=#{phone1}, phone2=#{phone2}, phone3=#{phone3}, post=#{post}, address=#{address},
	  gender=#{gender}, hobby=#{hobby}, intro=#{intro} where id = #{id}
	</update>

	<!-- 회원 삭제 -->
	<delete id="delete" parameterType="String">
	  delete from member0609 where id = #{id}
	</delete> 

</mapper>

index.jsp 

This file is connected to the loginForm.

<%@ 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>
</head>
<body>

<!-- 모델2 회원관리 -->

<script>
	location.href="./LoginForm.do";
</script>

</body>
</html>

loginform.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="<%=request.getContextPath() %>/member/login.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/Login.do">
<table border=1 width=350 align=center>
	<caption>로그인</caption>
	<tr>
		<td>ID</td>	
		<td><input type=text size=30 id="id" name="id" autofocus="autofocus"></td>	
	</tr>
	<tr>
		<td>비밀번호</td>
		<td><input type="password" size=30 id="passwd" name="passwd"></td>
	</tr>
	<tr>
		<td colspan=2 align=center>
			<input type="button" value="회원가입" 
			       onClick="location.href='<%=request.getContextPath()%>/MemberForm.do' ">
			<input type="submit" value="로그인">
			<input type="reset" value="취소">
		</td>
	</tr>
	
</table>
</form>


</body>
</html>

login.js

$(document).ready(function(){
	$("form").submit(function(){
		
		if($.trim($("#id").val())==""){
			alert("ID를 입력하세요");
			$("#id").focus();
			return false;
		}
		
		if($.trim($("#passwd").val())==""){
			alert("비밀번호를 입력하세요");
			$("#passwd").focus();
			return false;
		}
		
	});
});

Login.java

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.MemberDAO;

public class Login implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Login");
		
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");	
		
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");
		
		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.memberAuth(id, passwd);
		if(result == 1) System.out.println("회원인증 성공");
		
		if(result == 1) {			// 회원인증 성공
			session.setAttribute("id", id);
		}else {						// 회원인증 실패
			out.println("<script>");
			out.println("alert('로그인 실패');");
			out.println("history.go(-1)");
			out.println("</script>");
			out.close();	
			
			return null;
		}
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/member/main.jsp");
		
		return forward;
	}

}

DAO Class login part

// 로그인(회원인증)
	public int memberAuth(String id, String passwd) throws Exception {
		int result = 0;
		SqlSession session = getSession();
		MemberDTO member = session.selectOne("idcheck", id);
		if(member != null) {		// 중복 ID	
			if(member.getPasswd().equals(passwd)) {
				result = 1;			// 회원인증 성공
			}else {
				result = -1;		// 회원인증 실패
			}
		}

		return result;
	}

memberform.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 가입 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
//				document.getElementById('join_zip1').value = data.postcode1;
//				document.getElementById('join_zip2').value = data.postcode2;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>


<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="<%=request.getContextPath() %>/member/member.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/MemberInsert.do"> 
<table border=1 width=500 align=center>
	<caption>회원 가입</caption>
	<tr><td>ID</td>
		<td><input type=text autofocus="autofocus" id="id" name="id">
			<input type=button value="ID중복검사" id="idcheck">
			<div id="myid"></div>
		</td>
	</tr>
	<tr><td>비밀번호</td>
		<td><input type=password id="passwd" name="passwd"></td>
	</tr>
	<tr><td>성명</td>
		<td><input type=text id="name" name="name"></td>
	</tr>
	<tr><td>주민번호</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid">@
		    <input type=text size=10 id="domain" name="domain">
		    <select id="email">
		    	<option value="">직접입력</option>
		    	<option value="naver.com">네이버</option>
		    	<option value="daum.net">다음</option>
		    	<option value="nate.com">네이트</option>
		    	<option value="gmail.com">gmail</option>
		    </select>		    
		 </td>
	</tr>
	<tr><td>전화번호</td>
		<td><input type=text size=4 id="tel1" name="tel1" maxlength=4>-
			<input type=text size=4 id="tel2" name="tel2" maxlength=4>-
			<input type=text size=4 id="tel3" name="tel3" maxlength=4>
		</td>
	</tr>
	<tr><td>핸드폰</td>
		<td><select id="phone1" name="phone1">
				<option value="">번호선택</option>
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="018">018</option>
				<option value="019">019</option>
			</select>-
			<input type=text size=4 id="phone2" name="phone2" maxlength=4>-
			<input type=text size=4 id="phone3" name="phone3" maxlength=4>
		</td>
	</tr>
	<tr><td>우편번호</td>
		<td><input type=text size=5 id="post" name="post">
			<input type=button value="우편번호검색" 
			       onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>주소</td>
		<td><input type=text size=45 id="address" name="address"></td>
	</tr>
	<tr><td>성별</td>
		<td>
			<input type=radio id="male" name="gender" value="남자">남자
			<input type=radio id="female" name="gender" value="여자">여자
			<input type=radio id="others" name="gender" value="기타">기타
		</td>
	</tr>
	<tr><td>취미</td>
		<td>
			<input type="checkbox" id="h1" name="hobby" value="공부" checked>공부
			<input type="checkbox" id="h2" name="hobby" value="게임">게임
			<input type="checkbox" id="h3" name="hobby" value="등산">등산
			<input type="checkbox" id="h4" name="hobby" value="낚시">낚시
			<input type="checkbox" id="h5" name="hobby" value="쇼핑">쇼핑
		</td>
	</tr>	
	<tr><td>자기소개</td>
		<td>
			<textarea id="intro" name="intro" rows="5" cols="50" placeholder="자기소개를 100자 이내로 입력하세요"></textarea>
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="회원가입">
			<input type=reset value="취소">
		</td>
	</tr>		
</table>
</form>


</body>
</html>

MemberInsert.java

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MemberDAO;
import model.MemberDTO;

public class MemberInsert implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("MemberInsert");
		
		request.setCharacterEncoding("utf-8");
		
		MemberDTO member = new MemberDTO();
		member.setId(request.getParameter("id"));
		member.setPasswd(request.getParameter("passwd"));
		member.setName(request.getParameter("name"));
		member.setJumin1(request.getParameter("jumin1"));
		member.setJumin2(request.getParameter("jumin2"));
		member.setMailid(request.getParameter("mailid"));
		member.setDomain(request.getParameter("domain"));
		member.setTel1(request.getParameter("tel1"));
		member.setTel2(request.getParameter("tel2"));
		member.setTel3(request.getParameter("tel3"));
		member.setPhone1(request.getParameter("phone1"));
		member.setPhone2(request.getParameter("phone2"));
		member.setPhone3(request.getParameter("phone3"));
		member.setPost(request.getParameter("post"));
		member.setAddress(request.getParameter("address"));
		member.setGender(request.getParameter("gender"));
		
		String h = "";
		String[] h1 = request.getParameterValues("hobby");
		for(String h2 : h1) {
			h += h2+"-";			// 공부-게임-
		}
		member.setHobby(h);
		
		member.setIntro(request.getParameter("intro"));
		
		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.insert(member);
		if(result == 1) {
			System.out.println("회원가입 성공");
		}
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/member/loginform.jsp");
		
		return forward;
	}

}

Idcheck.java

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MemberDAO;

public class Idcheck implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Idcheck");
		
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("id");
		System.out.println("id:"+ id);
		
		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.idcheck(id);
		System.out.println("result:"+ result);	// 1 :  중복ID
												// -1 : 사용가능한 ID
		out.println(result);	// 브라우저에 출력되는 값이 callback함수로 리턴된다.
		
		return null;
	}

}

DAO Class Sign up / Id Check parts

// 회원가입
	public int insert(MemberDTO member) throws Exception{
		int result=0;
		SqlSession session = getSession();
		result = session.insert("insert", member);		
		System.out.println("result:"+result);
		
		return result;
	}
	
	// ID중복검사
	public int idcheck(String id) throws Exception{
		int result = 0;
		SqlSession session = getSession();
		MemberDTO member = session.selectOne("idcheck", id);
		if(member != null) {	// 중복 ID	
			result = 1;			
		}else {					// 사용가능한 ID
			result = -1;
		}
		
		return result;
	}

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> --%> <!-- 안됨 -->


<!--  세션이 있으면 -->
<%-- <c:if test="${not empty sessionScope.id}"> --%>	<!-- 2개 모두 잘됨 -->
<c:if test="${sessionScope.id != null }">
	${sessionScope.id} 님 환영 합니다. <br><br>
	
	<a href="<%=request.getContextPath() %>/UpdateMember.do">회원정보 수정</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/Logout.do">로그아웃</a>  <br><br>
	
	<a href="<%=request.getContextPath() %>/DeleteMember.do">회원탈퇴</a> <br><br>
</c:if>

<!-- 세션이 없으면 -->
<%-- <c:if test="${empty sessionScope.id}"> --%>
<c:if test="${sessionScope.id == null}">
	<a href="<%=request.getContextPath() %>/MemberForm.do">회원가입</a> <br><br>
	<a href="<%=request.getContextPath() %>/LoginForm.do">로그인</a> <br><br>
</c:if>

With session

Without session

The next steps will be demonstrated in the next post.

Please refer to my last post to learn what we did the last time. 

2022.09.26 - [Codes & Projects] - JSP / EL / JSTL / HTML / JavaScript / Oracle) Model2 Bulletin Board(1)

 

Before we start the following process, we will take a quick look at BoardListAction.java.

package service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardListAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardListAction");
		
		int page = 1;			// Current Page
		int limit = 10;			// How many pages will be printed? 10
		
		if(request.getParameter("page") != null) {
			 page = Integer.parseInt(request.getParameter("page"));
		}

		// ex) page = 1 : startRow = 1, endRow : 10
		int startRow = (page -1) * limit + 1;
		int endRow = page * limit;

		BoardDAO dao = BoardDAO.getInstance();
		int listcount = dao.getCount();	// Total data volume
		System.out.println("listcount: "+listcount);
		
		//To get List 
		List<BoardBean> boardlist = dao.getList(startRow, endRow);
		System.out.println("boardlist: "+boardlist);

		//Total pages number
		int pageCount = listcount / limit + (( listcount%limit == 0 )? 0 : 1); //if the result of listcount%limit is 0, increase 0, otherwise increase 1.

		int startPage = ((page-1)/ 10) * limit + 1; // 1, 11, 22...
		int endPage = startPage + 10 - 1; 	// 10, 20, 30...

		if(endPage > pageCount) endPage = pageCount;
		
		request.setAttribute("page", page);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", boardlist);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("startPage", startPage);
		request.setAttribute("endPage", endPage);
		
			ActionForward forward = new ActionForward();
			forward.setRedirect(false);  // Dispatcher method 
			forward.setPath("./board/qna_board_list.jsp");
			
			
		
		return forward;
	}
	
}

There are six variables: startRow, endRow, listcount, page count, startPage, endPage, and post number.

In terms of the listing, these variables are necessary. 

 

Now, let us get started on the next steps. So far, we are here, we can write posts, and we can see the list. 

Now, let us get started on the next steps.

 

1. Add pagination function in qna_board_list.jsp.

<!-- Pagination -->
<center>
	<c:if test="${listcount > 0 }">
		<!-- To move to the page 1 -->
		<a href="./BoardListAction.do?page=1" style="text-decoration: none">
			<< </a>
		<!--  Previous page -->
		<c:if test="${startPage > 10 }">
			<a href="./BoardListAction.do?page=${startPage-10}">[Prev]</a>
		</c:if>
		<!-- every block : 10 posts -->
		<c:forEach var="i" begin="${startPage}" end="${endPage}">
			<c:if test="${i == page}">
				<!-- current page -->
			[${i}]
			</c:if>
			<c:if test="${i != page}">
				<!-- Not a current page -->
				<a href="./BoardListAction.do?page=${i }"> [${i }]</a>
			</c:if>

		</c:forEach>

		<!-- Next page -->
		<c:if test="${endPage < pageCount }">
			<a href="./BoardListAction.do?page=${startPage+10}">[Next]</a>
		</c:if>
		<!-- To move to the last page -->
		<a href="./BoardListAction.do?page=${pageCount}"> >> </a>
	</c:if>
</center>

2. Create BoardDeatilAction service class in src - service.

3. Add a detail page part in the controller class.

//Detail page
		}else if(command.equals("/BoardDetailAction.do")) {
			try {
				action = new BoardDetailAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}

3. Add a readCountUpdate and getDetail methods in the DAO class.

// View count + 1
	public void readcountUpdate(int board_num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="update model2 set board_readcount=board_readcount+1 ";
				   sql+=" where board_num = ?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, board_num);
			pstmt.executeUpdate(); // To execute SQL
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
	}
	
// Detail page 
	public BoardBean getDetail(int board_num) {
		BoardBean board = new BoardBean();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from model2 where board_num=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, board_num);
			rs= pstmt.executeQuery();		// To execute SQL
			
			if(rs.next()) {

				   board.setBoard_num(rs.getInt("board_num"));
				   board.setBoard_name(rs.getString("board_name"));
				   board.setBoard_pass(rs.getString("board_pass"));
				   board.setBoard_subject(rs.getString("board_subject"));
				   board.setBoard_content(rs.getString("board_content"));
				   board.setBoard_file(rs.getString("board_file"));
				   board.setBoard_re_ref(rs.getInt("board_re_ref"));
				   board.setBoard_re_lev(rs.getInt("board_re_lev"));
				   board.setBoard_re_seq(rs.getInt("board_re_seq"));
				   board.setBoard_readcount(rs.getInt("board_readcount"));
				   board.setBoard_date(rs.getTimestamp("board_date"));
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		return board;
	}

4. Create a qna_board_view.jsp.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Detail page</title>
</head>
<body>
	<table border=1 width=400 align=center>
		<caption>Detail page</caption>
		<tr>
			<td>Title</td>
			<td>${board.board_subject }</td>
		</tr>
		<tr>
			<td>Content</td>
			<td><pre>${board.board_content }</pre> <!-- Method 1 -->
				${content } <!-- Method 2 --></td>
		</tr>
		<tr>
			<td>Attached File</td>
			<!-- If there is an attached file -->
			<c:if test="${board.board_file != null }">
				<a href="./board/file_down.jsp?file_name=${board.board_file }">
					${board.board_file} </a>
			</c:if>
		</tr>
		<tr>
			<td colspan=2 align=center>
				<input type="button" value="Reply"
				onClick="location.href='./BoardReplyAction.do?board_num=${board.board_num}&page=${page}'">
				
				<input type="button" value="Edit"
				onClick="location.href='./BoardModifyAction.do?board_num=${board.board_num}&page=${page}'"> 
				
				<input type="button" value="Delete"
				onClick="location.href='./BoardDeleteAction.do?board_num=${board.board_num}&page=${page}'"> 
				
				<input type="button" value="Go back to list"
				onClick="location.href='./BoardListAction.do?page=${page}'">

			</td>
		</tr>
	</table>


</body>
</html>

5.Create BoardReplyAction.jsp for processing Replies.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardReplyAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardReplyAction");

		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");

		BoardDAO dao = BoardDAO.getInstance();

		// To get the detail of the main post
		BoardBean board = dao.getDetail(board_num);

		// Share
		request.setAttribute("board", board);
		request.setAttribute("page", page);

		ActionForward forward = new ActionForward();
		forward.setRedirect(false); // dispatcher method
		forward.setPath("./board/qna_board_reply.jsp");

		return forward;
	}

}

6. Add the reply part in the controller class.

// Reply form
		} else if (command.equals("/BoardReplyAction.do")) {
			try {
				action = new BoardReplyAction();
				forward = action.execute(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

7. Create qna_board_reply.jsp.

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

<html>
<head>
<title>MVC Bulletin Board</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="<%=request.getContextPath()%>/board/script.js"></script>
<style>
@import
	url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap')
	;
</style>
</head>
<body>

	<form action="<%=request.getContextPath()%>/BoardReply.do"
		method="post">
		<input type="hidden" name="board_num" value="${board.board_num}">
		<input type="hidden" name="page" value="${page}"> <input
			type="hidden" name="board_re_ref" value="${board.board_re_ref}"> <input
			type="hidden" name="board_re_lev" value="${board.board_re_lev}"> <input
			type="hidden" name="board_re_seq" value="${board.board_re_seq}">

		<table cellpadding="0" cellspacing="0" align=center border=1>
			<tr align="center" valign="middle">
				<td style="font-family: 'Abril Fatface', cursive;" colspan="5">MVC
					Bulletin Board</td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Writer</div>
				</td>
				<td><input name="board_name" id="board_name" type="text"
					size="10" maxlength="10" value="" /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Password</div>
				</td>
				<td><input name="board_pass" id="board_pass" type="password"
					size="10" maxlength="10" value="" /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Title</div>
				</td>
				<td><input name="board_subject" id="board_subject" type="text"
					size="50" maxlength="100" value="re." /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12">
					<div align="center">Content</div>
				</td>
				<td><textarea name="board_content" id="board_content" cols="67"
						rows="15"></textarea></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12">
					<div align="center">Attach File</div>
				</td>
				<td><input name="board_file" type="file" /></td>
			</tr>
			<tr bgcolor="cccccc">
				<td colspan="2" style="height: 1px;"></td>
			</tr>
			<tr>
				<td colspan="2">&nbsp;</td>
			</tr>
			<tr align="center" valign="middle">
				<td colspan="5"><input type=submit value="Reply"> <input
					type=reset value="Cancel"></td>
			</tr>
		</table>
	</form>

</body>
</html>

8. Create BoardReply service class.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardReply implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardReply");
		
		request.setCharacterEncoding("utf-8");

		int board_num = Integer.parseInt(request.getParameter("board_num"));
		int board_re_ref = Integer.parseInt(request.getParameter("board_re_ref"));
		int board_re_lev = Integer.parseInt(request.getParameter("board_re_lev"));
		int board_re_seq = Integer.parseInt(request.getParameter("board_re_seq"));
		String page = request.getParameter("page");
		
		BoardBean board = new BoardBean();
		board.setBoard_num(board_num);
		board.setBoard_re_ref(board_re_ref);
		board.setBoard_re_lev(board_re_lev);
		board.setBoard_re_seq(board_re_seq);
		board.setBoard_name(request.getParameter("board_name"));
		board.setBoard_pass(request.getParameter("board_pass"));
		board.setBoard_subject(request.getParameter("board_subject"));
		board.setBoard_content(request.getParameter("board_content"));
		
		BoardDAO dao = BoardDAO.getInstance();
		int result = dao.boardReply(board);
		if(result == 1) System.out.println("Successfully replied.");
		
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("./BoardListAction.do?page="+page);
		
		return forward;
	}

}

9. In the controller class, add the reply part. 

// Writing replies
		}else if(command.equals("/BoardReply.do")){
			try {
				action = new BoardReply();
				forward = action.execute(request, response);
			}catch(Exception e) {
				
			}
		}

10. In the DAO class, add boardReply method.

// Reply 
	public int boardReply(BoardBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		// Detail about the main post
		int re_ref = board.getBoard_re_ref();	// Post group number	
		int re_lev = board.getBoard_re_lev();	// Depth of reply
		int re_seq = board.getBoard_re_seq(); 	// Print sequence
		
		try {
			con = getConnection();
			
			String sql="update model2 set board_re_seq=board_re_seq+1 ";
				   sql+=" where board_re_ref=? and board_re_seq > ?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, re_ref);
			pstmt.setInt(2, re_seq);
			pstmt.executeUpdate();
			
			sql="insert into model2 values(model2_seq.nextval, ";
			sql+=" ?,?,?,?,?,?,?,?,?,sysdate)";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getBoard_name());
			pstmt.setString(2, board.getBoard_pass());
			pstmt.setString(3, board.getBoard_subject());
			pstmt.setString(4, board.getBoard_content());
			pstmt.setString(5, "");				// board_file : null
			pstmt.setInt(6, re_ref);	   
			pstmt.setInt(7, re_lev+1);	   
			pstmt.setInt(8, re_seq+1);	   
			pstmt.setInt(9, 0);					// board_readcount
			
			result = pstmt.executeUpdate(); 	// To execute SQL
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}

11. Create BoardModifyAction service class for Editing the post.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardModifyAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardModifyAction");
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		
		BoardDAO dao = BoardDAO.getInstance();
		
		// Detail info
		BoardBean board = dao.getDetail(board_num);
		
		//Share
		request.setAttribute("board", board);
		request.setAttribute("page", page);
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false); 		//dispatcher method
		forward.setPath("./board/qna_board_modify.jsp");
		
		return forward;
	}

}

12. Add the part in the Controller class.

// Edit form
		}else if(command.equals("/BoardModifyAction.do")) {
			try {
				action = new BoardModifyAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}

 

It is like factory manufacturing. 

 

13. Create qna_board_modify.jsp.

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

<html>
<head>
<title>Edit My post</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="<%=request.getContextPath()%>/board/script.js"></script>
<style>
@import
	url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap')
	;
</style>
</head>
<body>

	<form action="<%=request.getContextPath()%>/BoardModify.do"
		method="post">
		<input type="hidden" name="board_num" value="${board.board_num}">
		<input type="hidden" name="page" value="${page}"> 
		<input
			type="hidden" name="board_re_ref" value="${board.board_re_ref}">
		<input type="hidden" name="board_re_lev" value="${board.board_re_lev}">
		<input type="hidden" name="board_re_seq" value="${board.board_re_seq}">

		<table cellpadding="0" cellspacing="0" align=center border=1>
			<tr align="center" valign="middle">
				<td style="font-family: 'Abril Fatface', cursive;" colspan="5">Edit MVC
					Bulletin Board</td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Writer</div>
				</td>
				<td><input name="board_name" id="board_name" type="text"
					size="10" maxlength="10" value="${board.board_name}" /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Password</div>
				</td>
				<td><input name="board_pass" id="board_pass" type="password"
					size="10" maxlength="10" value="" /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Title</div>
				</td>
				<td><input name="board_subject" id="board_subject" type="text"
					size="50" maxlength="100" value="${board.board_subject}" /></td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12">
					<div align="center">Content</div>
				</td>
				<td><textarea name="board_content" id="board_content" cols="67"
						rows="15">${board.board_content}</textarea></td>
			</tr>
			
			<tr align="center" valign="middle">
				<td colspan="5"><input type=submit value="Edit"> <input
					type=reset value="Cancel"></td>
			</tr>
		</table>
	</form>

</body>
</html>

14. Create BoardModify service class and updateresult.jsp.

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardModify implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardModify");
		
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();   //출력스트림 생성
		
		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		String board_pass = request.getParameter("board_pass");
		
		BoardBean board = new BoardBean();
		board.setBoard_num(board_num);
		board.setBoard_name(request.getParameter("board_name"));
		board.setBoard_subject(request.getParameter("board_subject"));
		board.setBoard_content(request.getParameter("board_content"));
		
		//To bring the saved password
		BoardDAO dao = BoardDAO.getInstance();
		BoardBean old = dao.getDetail(board_num);
		
		//To compare the password
		if(old.getBoard_pass().equals(board_pass)) {	// Correct password
			int result = dao.update(board); 
			if(result ==1) System.out.println("Successfully edited.");
			/*
			 * out.println("<script>");
			 * out.println("location.href='./board/updateresult.jsp?'");
			 * out.println("</script>"); out.close();
			 */
			
			response.sendRedirect("./board/updateresult.jsp?page="+page);
			
			return null;
			
		}else {											// Incorrect password
			out.println("<script>");
			out.println("alert('Incorrect password.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();
			
			return null;
		}

	//	ActionForward forward = new ActionForward();
	//	forward.setRedirect(false);
	//	forward.setPath("/BoardListAction.do?page="+page);	//To load to the list
	//	forward.setPath("/BoardDetailAction.do?board_num="+board_num+"&page="+page);	//To load to the detail page
		
	//	return forward;
	}

}

updateresult.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<script>
		//alert(${param.page});	
		alert("Your post is successfully edited.");
		location.href="<%=request.getContextPath()%>/BoardListAction.do?page=${param.page}";
	</script>
</body>
</html>

15.  Add the part in the Controller class.

// Edit 
		}else if(command.equals("/BoardModify.do")){
			try {
				action = new BoardModify();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
        
// update.do
		}else if(command.equals("/update.do")) {
				forward = new ActionForward();
				forward.setRedirect(false);
				forward.setPath("./board/updateresult.jsp");
			try {
				
			}catch(Exception e) {
				e.printStackTrace();
			}

16. Add the update method in the DAO class.

//Update 
	public int update(BoardBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection(); 		//Connect to the Database
			
			String sql="update model2 set board_name=?, board_subject=?,";
				   sql+="board_content=? where board_num=?";
				   
				   pstmt = con.prepareStatement(sql);
				   pstmt.setString(1, board.getBoard_name());
				   pstmt.setString(2, board.getBoard_subject());
				   pstmt.setString(3, board.getBoard_content());
				   pstmt.setInt(4, board.getBoard_num());
				   result = pstmt.executeUpdate();		//To execute SQL 
					
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
	}
	return result;
}

Now, let us create a delete part.

17. Create BoardDelectAction service class to load the link when you click the "Delete" button.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BoardDeleteAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardDeleteAction");
		ActionForward forward = new ActionForward();
		
		return forward;
	}

}

18. Go to the controller class, and add the delete form part.

// Delete form 
		}else if(command.equals("/BoardDeleteAction.do")){
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("./board/qna_board_delete.jsp");
		}
// Delete.do
		else if(command.equals("/BoardDelete.do)")){
			try{
				action = new BoardDelete();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}

19. Create qna_board_delete.jsp.

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

<html>
<head>
<title>Edit My post</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="<%=request.getContextPath()%>/board/script.js"></script>
<style>
@import
	url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap')
	;
</style>
</head>
<body>

board_num1 : <%=request.getParameter("board_num") %><br>
page1 : <%=request.getParameter("page") %><br>

board_num2 : ${param.board_num }<br>
page2 : ${param.page }<br>

	<form action="<%=request.getContextPath()%>/BoardDelete.do"
		method="post">
		<input type="hidden" name="board_num" value="${param.board_num}">
		<input type="hidden" name="page" value="${param.page}">

		<table cellpadding="0" cellspacing="0" align=center border=1>
			<tr align="center" valign="middle">
				<td style="font-family: 'Abril Fatface', cursive;" colspan="5">Delete
					MVC Bulletin Board</td>
			</tr>
			<tr>
				<td style="font-family: 'Abril Fatface', cursive; font-size: 12"
					height="16">
					<div align="center">Password</div>
				</td>
				<td><input name="board_pass" id="board_pass" type="password"
					size="10" maxlength="10" value="" /></td>
			</tr>
			
			<tr align="center" valign="middle">
				<td colspan="5"><input type=submit value="Delete"> <input
					type=reset value="Cancel"></td>
			</tr>
		</table>
	</form>

</body>
</html>

20. Create BoardDelete service class.

package service;

import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;
import model.BoardBean;

public class BoardDelete implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardDelete");

		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();

		int board_num = Integer.parseInt(request.getParameter("board_num"));
		String page = request.getParameter("page");
		String board_pass = request.getParameter("board_pass");

		String path = request.getRealPath("boardupload");
		System.out.println("path:" + path);

		BoardDAO dao = BoardDAO.getInstance();
		BoardBean old = dao.getDetail(board_num); // To get detail

		// To compare passwords
		if (old.getBoard_pass().equals(board_pass)) { // Correct password
			int result = dao.delete(board_num); // Delete SQL

			// If there is an attached file -> delete
			if (old.getBoard_file() != null) {

				File file = new File(path);
				file.mkdir(); // makedirectory

				// To bring boardupload directory
				File[] f = file.listFiles();
				for (int i = 0; i < f.length; i++) {
					if (f[i].getName().equals(old.getBoard_file())) {
						f[i].delete(); // To delete the attached file
					}
				}
			}

		} else { // Incorrect password
			out.println("<script>");
			out.println("alert('Incorrect password.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();

			return null;
		}

		ActionForward forward = new ActionForward();
		forward.setRedirect(false);
		forward.setPath("/BoardListAction.do?page=" + page);

		return forward;
	}

}

21. In the DAO class, add the delete method.

// Delete method
	public int delete(int board_num) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();					
			
			String sql="delete from model2 where board_num=?";
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}

So far, we have made an MVC pattern bulletin board with a reply and file upload function. 

To remind you, this figure and my last post compare model1 and 2.

2022.09.15 - [JSP] - JSP) Model1 vs Model2

Main funtions 

1. Connection Pool

2.  Action tags : <jsp:useBean...> / <jsp:setProperty...>

3. DTO, DAO class 

4. Session

 

Log in to Oracle, and create a new account(totoro) for a new project. 

create user totoro identified by totoro123;
grant connect, resource to totoro;

Create a new table with the new account.

create table member(
			id varchar2(20) primary key,
			passwd varchar2(20) not null,
			name varchar2(20) not null,
			jumin1 varchar2(6) not null,
			jumin2 varchar2(7) not null,
			mailid varchar2(30), 
			domain varchar2(30), 
			tel1 varchar2(5),
			tel2 varchar2(5),
			tel3 varchar2(5),
			phone1 varchar2(5),
			phone2 varchar2(5),
			phone3 varchar2(5),
			post varchar2(10),
			address varchar2(200),
			gender varchar2(20),
			hobby varchar2(50),
			intro varchar2(2000),
			register timestamp );

DTO Class

// DTO(Data Transfer Object)

package member;

import java.sql.Timestamp;

public class MemberDTO {
	private String id;
	private String passwd;
	private String name;
	private String jumin1;
	private String jumin2;
	private String mailid;
	private String domain;
	private String tel1;
	private String tel2;
	private String tel3;
	private String phone1;
	private String phone2;
	private String phone3;
	private String post;
	private String address;
	private String gender;
	private String hobby;
	private String intro;
	private Timestamp register;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJumin1() {
		return jumin1;
	}
	public void setJumin1(String jumin1) {
		this.jumin1 = jumin1;
	}
	public String getJumin2() {
		return jumin2;
	}
	public void setJumin2(String jumin2) {
		this.jumin2 = jumin2;
	}
	public String getMailid() {
		return mailid;
	}
	public void setMailid(String mailid) {
		this.mailid = mailid;
	}
	public String getDomain() {
		return domain;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}
	public String getTel1() {
		return tel1;
	}
	public void setTel1(String tel1) {
		this.tel1 = tel1;
	}
	public String getTel2() {
		return tel2;
	}
	public void setTel2(String tel2) {
		this.tel2 = tel2;
	}
	public String getTel3() {
		return tel3;
	}
	public void setTel3(String tel3) {
		this.tel3 = tel3;
	}
	public String getPhone1() {
		return phone1;
	}
	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}
	public String getPhone2() {
		return phone2;
	}
	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}
	public String getPhone3() {
		return phone3;
	}
	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}
	public String getPost() {
		return post;
	}
	public void setPost(String post) {
		this.post = post;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getIntro() {
		return intro;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}
}

memberform.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"> 
<title>회원 가입 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
//				document.getElementById('join_zip1').value = data.postcode1;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>

</head>
<body>

<form method="post" action="member.jsp"> 
<table border=1 width=450 align="center">
	<caption>회원 가입 폼</caption>
	<tr><td>ID</td>
		<td><input type=text autofocus="autofocus" id="id" name="id">
			<input type=button value="ID중복검사" id="idcheck">
			<div id="myid"></div>
		</td>
	</tr>
	<tr><td>비밀번호</td>
		<td><input type=password id="passwd" name="passwd">
		</td>
	</tr>
	<tr><td>성명</td>
		<td><input type=text id="name" name="name"></td>
	</tr>
	<tr><td>주민번호</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid">@
			<input type=text size=10 id="domain" name="domain">
			<select id="email">
				<option value="">직접입력</option>
				<option value="naver.com">네이버</option>
				<option value="daum.net">다음</option>
				<option value="nate.com">네이트</option>
				<option value="gmail.com">gmail</option>
			</select>	
		</td>
	</tr>
	<tr><td>전화번호</td>
		<td><input type=text size=4 maxlength=4 id="tel1" name="tel1">-
		    <input type=text size=4 maxlength=4 id="tel2" name="tel2">-
		    <input type=text size=4 maxlength=4 id="tel3" name="tel3">-
		</td>
	</tr>
	<tr><td>핸드폰</td>
		<td><select id="phone1" name="phone1">
				<option value="">번호선택</option>
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="018">018</option>
				<option value="019">019</option>
			</select>-
			<input type=text size=4 maxlength=4 id="phone2" name="phone2">-
		    <input type=text size=4 maxlength=4 id="phone3" name="phone3">		
		</td>	
	</tr>
	<tr><td>우편번호</td>
		<td><input type=text size=5 maxlength=5 id="post" name="post">
			<input type=button value="우편검색" onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>주소</td>
		<td><input type=text size=45 id="address" name="address"></td>
	</tr>
	<tr><td>성별</td>
		<td><input type=radio id="male" name="gender" value="남자">남자
			<input type=radio id="female" name="gender" value="여자">여자
		</td>
	</tr>
	<tr><td>취미</td>
		<td><input type=checkbox id="h1" name="hobby" value="공부">공부
			<input type=checkbox id="h2" name="hobby" value="게임">게임
			<input type=checkbox id="h3" name="hobby" value="등산">등산
			<input type=checkbox id="h4" name="hobby" value="낚시">낚시
			<input type=checkbox id="h5" name="hobby" value="쇼핑">쇼핑
		</td>
	</tr>
	<tr><td>자기소개</td>
		<td><textarea rows=5 cols=50 id="intro" name="intro"
		     placeholder="자기소개를 100자 이내로 입력하세요"></textarea>		
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="회원가입">
			<input type=reset value="취소">
		</td>
	</tr>		
</table>
</form>

</body>
</html>

member.js (Validation Check 유효성검사)

$(document).ready(function(){
		
		// ID중복검사 (popup 창으로 처리)
//		$("#idcheck").click(function(){
//			if($("#id").val()==""){
//				alert("ID를 입력하세요.");
//				$("#id").focus();
//				return false;
//			}else{
//				// open("팝업창에 실행될 문서명","윈도우이름","옵션")
//				var ref="idcheck.jsp?id="+$("#id").val();
//				window.open(ref,"mywin","width=250,height=150");
//			}			
//		});

		// ajax로  ID중복 검사
		$("#idcheck").click(function(){
			if($("#id").val() == ""){
				alert("ID를 입력 하세요.");
				$("#id").focus();
				return false;
			}else{
				
				var id = $("#id").val();	   // 사용자가 입력한 ID
				
				$.ajax({
					type : "post",   	       // get, post, put, delete
					url : "idcheck1.jsp",
					data : {"id" : id},	      // json
					success : function(data){ // callback함수로 결과를 돌려 받는다.
						alert(data);
						if(data == 1){        // 중복 ID
							$("#myid").html("<font color=red>중복 ID입니다.</font>");
							$("#id").val("").focus();
						}else{				  // 사용 가능한  ID
							$("#myid").html("<font color=red>사용 가능한 ID입니다.</font>");
							$("#passwd").focus();
						}
					}
				}); // $.ajax() end
				
			} // else end			
			
		}); // click end
		
		// 주민번호  뒷자리로 포커스 이동
		$("#jumin1").keyup(function(){
			
			if($("#jumin1").val().length == 6)
				$("#jumin2").focus();
		});
		
		// 도메인 선택
		$("#email").change(function(){
			if($("#email").val()==""){		// 직접 입력 선택
				$("#domain").attr("readOnly", false);
				$("#domain").val("").focus();
			}else{							// 도메인을 선택
				$("#domain").val($("#email").val());
				$("#domain").attr("readOnly","readOnly");				
			}
		});
		
		// 유효성 검사
		$("form").submit(function(){
			
			if($("#id").val() == ""){
				alert("ID를 입력하세요.");
				$("#id").focus();
				return false;
			}
			if($("#passwd").val()==""){
				alert("비밀번호를 입력하세요.");
				$("#passwd").focus();
				return false;
			}
			if($("#name").val()==""){
				alert("이름을 입력하세요.");
				$("#name").focus();
				return false;
			}
			if($("#jumin1").val()==""){
				alert("주민번호 앞자리를 입력하세요.");
				$("#jumin1").focus();
				return false;
			}
			if($("#jumin1").val().length != 6){
				alert("주민번호 앞자리 6자리를 입력하세요.");
				$("#jumin1").val("").focus();
				return false;
			}
			// isNaN() : 문자가 포함되면 true를 리턴하는 함수
			if(isNaN($("#jumin1").val())){
				alert("숫자만 입력하세요.");
				$("#jumin1").val("").focus();
				return false;
		    }
			if($("#jumin2").val()==""){
				alert("주민번호 뒷자리를 입력하세요.");
				$("#jumin2").focus();
				return false;
			}
			if($("#jumin2").val().length != 7){
				alert("주민번호 뒷자리 7자리를 입력하세요.");
				$("#jumin2").val("").focus();
				return false;
			}
			// isNaN() : 문자가 포함되면 true를 리턴하는 함수
			if(isNaN($("#jumin2").val())){
				alert("숫자만 입력하세요.");
				$("#jumin2").val("").focus();
				return false;
		    }
			if($("#mailid").val()==""){
				alert("EMail주소를 입력하세요.");
				$("#mailid").focus();
				return false;
			}
			if($("#domain").val()==""){
				alert("도메인을 입력하세요.");
				$("#domain").focus();
				return false;
			}
			if($("#tel1").val()==""){
				alert("전화번호 앞자리를 입력하세요.");
				$("#tel1").focus();
				return false;
			}
			if(isNaN($("#tel1").val())){
				alert("숫자만 입력하세요.");
				$("#tel1").val("").focus();
				return false;
			}
			if($("#tel2").val()==""){
				alert("전화번호 중간자리를 입력하세요.");
				$("#tel2").focus();
				return false;
			}
			if(isNaN($("#tel2").val())){
				alert("숫자만 입력하세요.");
				$("#tel2").val("").focus();
				return false;
			}
			if($("#tel3").val()==""){
				alert("전화번호 끝자리를 입력하세요.");
				$("#tel3").focus();
				return false;
			}
			if(isNaN($("#tel3").val())){
				alert("숫자만 입력하세요.");
				$("#tel3").val("").focus();
				return false;
			}
			if($("#phone1").val()==""){
				alert("핸드폰 앞자리를 선택 하세요.");
				return false;
			}
			if($("#phone2").val()==""){
				alert("핸드폰 중간자리를 입력하세요.");
				$("#phone2").focus();
				return false;
			}
			if(isNaN($("#phone2").val())){
				alert("숫자만 입력하세요.");
				$("#phone2").val("").focus();
				return false;
			}
			if($("#phone3").val()==""){
				alert("핸드폰 끝자리를 입력하세요.");
				$("#phone3").focus();
				return false;
			}
			if(isNaN($("#phone3").val())){
				alert("숫자만 입력하세요.");
				$("#phone3").val("").focus();
				return false;
			}
			if($("#post").val()==""){
				alert("우편번호를 입력하세요.");
				$("#post").focus();
				return false;
			}
			if($("#address").val()==""){
				alert("주소를 입력하세요.");
				$("#address").focus();
				return false;
			}
			if($("#male").is(":checked")==false &&
			   $("#female").is(":checked")==false){
				alert("남.여 중에서 1개를 선택 하세요");
				return false;
			}
			
			/* var cnt=0;
			if($("#h1").is(":checked")) cnt++;
			if($("#h2").is(":checked")) cnt++;
			if($("#h3").is(":checked")) cnt++;
			if($("#h4").is(":checked")) cnt++;
			if($("#h5").is(":checked")) cnt++;
			
			if(cnt < 2){
				alert("취미를 2개 이상 선택 하세요.");
				return false;
			} */
			
		if($("input:checkbox[name='hobby']:checked").length < 2){
			alert("취미를 2개 이상 선택 하세요.");
			return false;
		}
			
		if($("#intro").val()==""){
			alert("자기소개를 입력하세요.");
			$("#intro").focus();
			return false;
		}		
		if($("#intro").val().length > 100){
			alert("자기소개를 100자 이내로 입력하세요.");
			$("#intro").focus();
			return false;
		}	
			
	});	// submit() end	
		
}); // ready() end

member.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="member.MemberDAO"%>

<%
	request.setCharacterEncoding("utf-8");
%>    
  
<jsp:useBean id="member" class="member.MemberDTO" />   
<jsp:setProperty property="*" name="member"/> 

<%
	String[] hobby = request.getParameterValues("hobby");
	String h = "";        // h = "공부-게임-등산-"
	for(String h1 : hobby){
		h += h1 + "-";		
	}
	
	member.setHobby(h);
	
	// DAO 객체 생성
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.insert(member); //insert SQL문을 실행할 메소드 호출
	
	if(result == 1){      // 회원가입 성공	
%>
		<script>
			alert("회원가입 성공");
			location.href="login.html";
		</script>

<%  }else{   //회원가입 실패        %>
		<script>
			alert("회원가입 실패");
			history.go(-1);
		</script>
<%	}%>

idcheck.jsp

<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
	$(document).ready(function(){
		$("#close1").click(function(){ // 중복 ID인 경우의 닫기 버튼 클릭
			opener.$("#id").val("").focus();
			window.close();
		});
		
	$("#close2").click(function(){	// 사용 가능한 ID 인 경우의 닫기 버튼 클릭 
		opener.$("#passwd").focus();
		window.close();
		});
	});
</script>

<%
	String id = request.getParameter("id");

MemberDAO dao = MemberDAO.getInstance();

// id 중복검사 메소드 호출
int result = dao.memberAuth(id);

if (result == 1) { // 중복 ID : 1
%>
<%=id%>는 중복 ID 입니다.
<br>
<br>
<br>
<input type="button" value="Close" id="close1">
<%
	} else { // 사용 가능한 ID : -1
%>
<%=id%>는 사용가능한 ID 입니다.
<br>
<br>
<br>
<input type="button" value="Close" id="close2">
<%
	}
%>

idcheck1.jsp

<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<% 
	String id = request.getParameter("id");
	System.out.println("id="+id);  // Console 창에 출력 
	
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.memberAuth(id);
	System.out.println("result="+result);
	//result : 1(중복 ID)
	//result : -1(사용가능한 ID)
	
	// 웹브라우저에 출력되는 값이 callback함수로 리턴된다. 
	out.println(result);
%>

login.jsp

<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.memberCheck(member); // 회원인증 처리 
	
if (result == 1) { // 로그인 성공
	session.setAttribute("id", member.getId());
%>
		<script>
			alert("로그인 성공");
			location.href = "main.jsp";
		</script>
<%
	} else {
%>
		<script>
			alert("로그인 실패");
			hisroty.go(-1);
		</script>
<%
	}
%>

main.jsp(세션값이 있냐 없냐에 따라서 값이 달라짐)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	String id = (String) session.getAttribute("id");

if (id != null) { //세션이 있는 경우(정상적으로 로그인)
%>
<%=id %>님 환영합니다. <br><br><br>

<a href="updateform.jsp">정보수정</a><br>
<a href="logout.jsp">로그아웃 </a><br>
<a href="deleteform.jsp">회원탈퇴</a><br>
<!-- <a href="list.jsp">글목록</a><br> -->

<%
	} else {  // 세션이 없는 경우(비정상적인 접속))
%>
<a href="memberform.html">회원가입</a><br>
<a href="loginform.html">로그인</a><br>
<%
	}
%>

세션이 없을 때 When there is no session:

세션이 있을 때 Where there is session: 

logout.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%	//세션 삭제: 서버와 클라이언트의 연결이 끊어짐
 session.invalidate();
%>

<script>
	alert("Log out");
	location.href="loginform.html";
</script>

updateform.jsp (memberform.html과 양식은 동일하지만 가입 시 등록한 정보가 입력되어있음)

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String id = (String) session.getAttribute("id");

MemberDAO dao = MemberDAO.getInstance();

// 한 사람의 상세정보 구해오기 
MemberDTO member = dao.getMember(id);

// h[0] = "공부", h[1] ="게임",...
String[] h = member.getHobby().split("-");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 수정 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
				//				document.getElementById('join_zip1').value = data.postcode1;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;

			}
		}).open();
	}
</script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>
<script>
$(document).ready(function(){	
	<%for (String s : h) {%>  // value 값이 s인 값을 구해와라 
$("input:checkbox[name='hobby'][value='<%=s%>']").attr("checked", true);
	<%}%>
});
</script>

</head>
<body>

	<form method="post" action="update.jsp">
	<input type="hidden" name="id" value="<%=member.getId() %>">
		<table border=1 width=450 align="center">
			<caption>회원 수정 폼</caption>
			<tr>
				<td>ID</td>
				<td><%=member.getId()%></td>
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type=password id="passwd" name="passwd"></td>
			</tr>
			<tr>
				<td>성명</td>
				<td><input type=text id="name" name="name"
					value="<%=member.getName()%>"></td>
			</tr>
			<tr>
				<td>주민번호</td>
				<td><input type=text size=6 maxlength=6 id="jumin1"
					name="jumin1" value="<%=member.getJumin1()%>">- <input
					type=text size=7 maxlength=7 id="jumin2" name="jumin2"
					value="<%=member.getJumin2()%>"></td>
			</tr>
			<tr>
				<td>E-Mail</td>
				<td><input type=text size=10 id="mailid" name="mailid"
					value="<%=member.getMailid()%>">@ <input type=text size=10
					id="domain" name="domain" value="<%=member.getDomain()%>">
					<select id="email">
						<option value="">직접입력</option>
						<option value="naver.com">네이버</option>
						<option value="daum.net">다음</option>
						<option value="nate.com">네이트</option>
						<option value="gmail.com">gmail</option>
				</select></td>
			</tr>
			<tr>
				<td>전화번호</td>
				<td><input type=text size=4 maxlength=4 id="tel1" name="tel1"
					value="<%=member.getTel1()%>">- <input type=text size=4
					maxlength=4 id="tel2" name="tel2" value="<%=member.getTel2()%>">-
					<input type=text size=4 maxlength=4 id="tel3" name="tel3"
					value="<%=member.getTel3()%>"></td>
			</tr>
			<tr>
				<td>핸드폰</td>
				<td><select id="phone1" name="phone1">
						<option value="">번호선택</option>
						<option value="010" <%if (member.getPhone1().equals("010")) {%>
							<%="selected"%> <%}%>>010</option>
						<option value="011" <%if (member.getPhone1().equals("011")) {%>
							<%="selected"%> <%}%>>011</option>
						<option value="016" <%if (member.getPhone1().equals("016")) {%>
							<%="selected"%> <%}%>>016</option>
						<option value="018" <%if (member.getPhone1().equals("018")) {%>
							<%="selected"%> <%}%>>018</option>
						<option value="019" <%if (member.getPhone1().equals("019")) {%>
							<%="selected"%> <%}%>>019</option>
				</select>- <input type=text size=4 maxlength=4 id="phone2" name="phone2"
					value="<%=member.getPhone2()%>">- <input type=text size=4
					maxlength=4 id="phone3" name="phone3"
					value="<%=member.getPhone3()%>"></td>
			</tr>
			<tr>
				<td>우편번호</td>
				<td><input type=text size=5 maxlength=5 id="post" name="post"
					value="<%=member.getPost()%>"> <input type=button
					value="우편검색" onClick="openDaumPostcode()"></td>
			</tr>
			<tr>
				<td>주소</td>
				<td><input type=text size=45 id="address" name="address"
					value="<%=member.getAddress()%>"></td>
			</tr>
			<tr>
				<td>성별</td>
				<td><input type=radio id="male" name="gender" value="남자"
					<%if (member.getGender().equals("남자")) {%> <%="checked"%> <%}%>>남자
					<input type=radio id="female" name="gender" value="여자"
					<%if (member.getGender().equals("여자")) {%> <%="checked"%> <%}%>>여자</td>
			</tr>
			<tr>
				<td>취미</td>
				<td><input type=checkbox id="h1" name="hobby" value="공부">공부
					<input type=checkbox id="h2" name="hobby" value="게임">게임 <input
					type=checkbox id="h3" name="hobby" value="등산">등산 <input
					type=checkbox id="h4" name="hobby" value="낚시">낚시 <input
					type=checkbox id="h5" name="hobby" value="쇼핑">쇼핑</td>
			</tr>
			<tr>
				<td>자기소개</td>
				<td><textarea rows=5 cols=50 id="intro" name="intro"
						placeholder="자기소개를 100자 이내로 입력하세요"><%=member.getIntro()%>"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan=2 align=center><input type=submit value="회원수정">
					<input type=reset value="취소"></td>
			</tr>
		</table>
	</form>

</body>
</html>

update.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%
	String[] hobby = request.getParameterValues("hobby");

// 취미를 하이픈(-)을 붙여서 저장: ex) 공부-게임-등산.. 
String h = "";
for (String h1 : hobby) {
	h += h1 + "=";
}
member.setHobby(h);

MemberDAO dao = MemberDAO.getInstance();

//한 사람의 상세 정보 구하기
MemberDTO old = dao.getMember(member.getId());

// 비번 비교
if (old.getPasswd().equals(member.getPasswd())){ // 비번 일치시
int result = dao.update(member);

if(result == 1){
%>
	<script>
		alert("회원정보 수정 성공");
		location.href="main.jsp";
	</script>
<% }
	} else {// 비번 불일치시
%>
<script>
	alert("비밀번호 불일치");
	history.go(-1);
</script>

<%
	}
%>

deleteform.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String id = (String) session.getAttribute("id");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 삭제 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>

</head>
<body>

	<form method="post" action="delete.jsp">
		<input type="hidden" name="id" value="<%=id%>">
		<table border=1 width=450 align="center">
			<caption>회원 삭제 폼</caption>
			<td>비밀번호</td>
			<td><input type=password id="passwd" name="passwd"></td>
			</tr>

			<tr>
				<td colspan=2 align=center><input type=submit value="회원삭제">
					<input type=reset value="취소"></td>
			</tr>
		</table>
	</form>

</body>
</html>

delete.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%

MemberDAO dao = MemberDAO.getInstance();

//한 사람의 상세 정보 구하기
MemberDTO old = dao.getMember(member.getId());

// 비번 비교
if (old.getPasswd().equals(member.getPasswd())){ // 비번 일치시
int result = dao.delete(member.getId());		// delete SQL문 싷ㄹ행

if(result == 1){
	session.invalidate(); 	// 세션 삭제 
%>
	<script>
		alert("회원 탈퇴 성공");
		location.href="main.jsp";
	</script>
<% }
	} else {// 비번 불일치시
%>
<script>
	alert("비밀번호 불일치");
	history.go(-1);
</script>

<%
	}
%>

memberDAO.java

// DAO(Data Access Object)

package member;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemberDAO {

	// 싱글톤 : 객체 생성을 한번만 수행하는 것.
	private static MemberDAO instance = new MemberDAO();

	public static MemberDAO getInstance() { // 정적 메소드
		return instance;
	}

	// 컨넥션풀에서 컨넥션을 구해오는 메소드
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}

	// ID 중복 검사
	public int memberAuth(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);

			rs = pstmt.executeQuery(); // SQL문 실행

			if (rs.next()) { // 조건식을 만족하는 데이터를 구구해옴
				result = 1;
			} else {
				result = -1; // 사용 가능한 ID
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 회원 가입
	public int insert(MemberDTO member) {
		int result = 0;

		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection(); // 컨넥션풀에서 컨넥션을 구해온다.

			String sql = "insert into member ";
			sql += " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			pstmt.setString(2, member.getPasswd());
			pstmt.setString(3, member.getName());
			pstmt.setString(4, member.getJumin1());
			pstmt.setString(5, member.getJumin2());
			pstmt.setString(6, member.getMailid());
			pstmt.setString(7, member.getDomain());
			pstmt.setString(8, member.getTel1());
			pstmt.setString(9, member.getTel2());
			pstmt.setString(10, member.getTel3());
			pstmt.setString(11, member.getPhone1());
			pstmt.setString(12, member.getPhone2());
			pstmt.setString(13, member.getPhone3());
			pstmt.setString(14, member.getPost());
			pstmt.setString(15, member.getAddress());
			pstmt.setString(16, member.getGender());
			pstmt.setString(17, member.getHobby());
			pstmt.setString(18, member.getIntro());

			result = pstmt.executeUpdate(); // SQL문 실행

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 로그인(회원인증 처리)
	public int memberCheck(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			rs = pstmt.executeQuery(); // SQL문 실행

			if (rs.next()) { // ID 일치
				if (rs.getString("passwd").equals(member.getPasswd())) {
					result = 1; // ID, 비번 일치 (회원 인증 성공)
				} else {
					result = -1; // 비번 불일치
				}
			} else {
				result = -2; // ID 불일치
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 회원 수정폼 : 한 사람의 상세정보 구하기
	public MemberDTO getMember(String id) {
		MemberDTO member = new MemberDTO();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				// member.id = "test; 접근안됨 private 접근제어자
				member.setId(rs.getString("id"));
				member.setPasswd(rs.getString("passwd"));
				member.setName(rs.getString("name"));
				member.setJumin1(rs.getString("jumin1"));
				member.setJumin2(rs.getString("jumin2"));
				member.setMailid(rs.getString("mailid"));
				member.setDomain(rs.getString("domain"));
				member.setTel1(rs.getString("tel1"));
				member.setTel2(rs.getString("tel2"));
				member.setTel3(rs.getString("tel3"));
				member.setPhone1(rs.getString("phone1"));
				member.setPhone2(rs.getString("phone2"));
				member.setPhone3(rs.getString("phone3"));
				member.setPost(rs.getString("post"));
				member.setAddress(rs.getString("address"));
				member.setGender(rs.getString("gender"));
				member.setHobby(rs.getString("hobby"));
				member.setIntro(rs.getString("intro"));
				member.setRegister(rs.getTimestamp("register"));

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}

		return member;
	}

	// 회원정보 수정
	public int update(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection();

			String sql = "update member set name=?, jumin1=?, jumin2=?, mailid=?,";
			sql += "domain=?, tel1=?, tel2=?, tel3=?, phone1=?, phone2=?, phone3=?,";
			sql += "post=?, address=?, gender=?, hobby=?, intro=? where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getName());
			pstmt.setString(2, member.getJumin1());
			pstmt.setString(3, member.getJumin2());
			pstmt.setString(4, member.getMailid());
			pstmt.setString(5, member.getDomain());
			pstmt.setString(6, member.getTel1());
			pstmt.setString(7, member.getTel2());
			pstmt.setString(8, member.getTel3());
			pstmt.setString(9, member.getPhone1());
			pstmt.setString(10, member.getPhone2());
			pstmt.setString(11, member.getPhone3());
			pstmt.setString(12, member.getPost());
			pstmt.setString(13, member.getAddress());
			pstmt.setString(14, member.getGender());
			pstmt.setString(15, member.getHobby());
			pstmt.setString(16, member.getIntro());
			pstmt.setString(17, member.getId());
			
			result = pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}

		return result;
	}

		// 회원 탈퇴
	public int delete(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="delete from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			result = pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		
		return result;
	}
}

Main functions

1. Connection Pool 

2. Reply function

3. File attachment and download function by using cos library

4. request object

5. Controller Class: Java Servlet

6. Model = Service + DAO (Service, DTO, DAO class) 

7. View(User Interface) : EL, JSLT 

 

Please refer to the figures for a better understanding of the structure of this project.

 

1. Create a Dynamic Web Project model2board.

2. Test the Connection Pool

3. Create a folder(boardupload) to save uploaded files.

4. Create a sql folder and create board.sql.

5. Create a table and a sequence.

--Model2 Bulletin Board

select * from tab;
select * from seq;
select * from model2;

create table model2(
			board_num number primary key,
			board_name varchar2(20),
			board_pass varchar2(15),
			board_subject varchar2(50),
			board_content varchar2(2000),
			board_file varchar2(50),
			board_re_ref number,
			board_re_lev number, 
			board_re_seq number, 
			board_readcount number,
			board_date timestamp );

create sequence model2_seq
			start with 1
			increment by 1
			nocache;

6. Create a BoardBean(DTO) Class in src-model.

// DTO(Data Transfer Object)

package model;

import java.sql.Timestamp;

public class BoardBean {
	private int board_num;
	private String board_name;
	private String board_pass;
	private String board_subject;
	private String board_content;
	private String board_file;
	private int board_re_ref;
	private int board_re_lev;
	private int board_re_seq;
	private int board_readcount;
	private Timestamp board_date;
	
	public int getBoard_num() {
		return board_num;
	}
	public String getBoard_name() {
		return board_name;
	}
	public String getBoard_pass() {
		return board_pass;
	}
	public String getBoard_subject() {
		return board_subject;
	}
	public String getBoard_content() {
		return board_content;
	}
	public String getBoard_file() {
		return board_file;
	}
	public int getBoard_re_ref() {
		return board_re_ref;
	}
	public int getBoard_re_lev() {
		return board_re_lev;
	}
	public int getBoard_re_seq() {
		return board_re_seq;
	}
	public int getBoard_readcount() {
		return board_readcount;
	}
	public Timestamp getBoard_date() {
		return board_date;
	}
	public void setBoard_num(int board_num) {
		this.board_num = board_num;
	}
	public void setBoard_name(String board_name) {
		this.board_name = board_name;
	}
	public void setBoard_pass(String board_pass) {
		this.board_pass = board_pass;
	}
	public void setBoard_subject(String board_subject) {
		this.board_subject = board_subject;
	}
	public void setBoard_content(String board_content) {
		this.board_content = board_content;
	}
	public void setBoard_file(String board_file) {
		this.board_file = board_file;
	}
	public void setBoard_re_ref(int board_re_ref) {
		this.board_re_ref = board_re_ref;
	}
	public void setBoard_re_lev(int board_re_lev) {
		this.board_re_lev = board_re_lev;
	}
	public void setBoard_re_seq(int board_re_seq) {
		this.board_re_seq = board_re_seq;
	}
	public void setBoard_readcount(int board_readcount) {
		this.board_readcount = board_readcount;
	}
	public void setBoard_date(Timestamp board_date) {
		this.board_date = board_date;
	}
	
}

7. Create a BoardDAO Class in src-dao and create a Singleton and Connection instance. 

//DAO(Data Access Object)

package dao;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BoardDAO {
	
	// Singleton
	private static BoardDAO instance = new BoardDAO();
	
	public static BoardDAO getInstance() {		// Static method
		return instance;
	}
	
	// Connection from Connection Pool
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}
}

8. Create BoardFrontController class in src-controller. The controller class has to be made as a Java Servlet Class.

.do is the general extension of actions using Apache Struts.

package controller;

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;

/**
 * Servlet implementation class BoardFrontController
 */
@WebServlet("*.do")	// Do extension 
public class BoardFrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		
		System.out.println("requestURI: "+requestURI);
		System.out.println("contextPath: "+contextPath);
		System.out.println("command: "+command);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("get");
		
		doProcess(request, response);	// To call doProcess method
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("post");
		
		doProcess(request, response);	// To call doProcess method
	}

}

9. Create an Action interface in src-service.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface Action {

	// Abstract method
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception; 
}

10. Create an ActionForward Class in src-service.

package service;

public class ActionForward {
	private boolean redirect;		// To set the forwarding method
	private String path; 			// To save the file name to forward
	
	public boolean isRedirect() {
		return redirect;
	}
	public String getPath() {
		return path;
	}
	public void setRedirect(boolean redirect) {
		this.redirect = redirect;
	}
	public void setPath(String path) {
		this.path = path;
	}
	
}

11. Add action and forward part in the controller class.

Action action = null;
		ActionForward forward = null;
		
		// Writng a content
		if(command.equals("/BoardAddAction.do")) {
			try {
				action = new BoardAddAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		// Forwarding process
		if(forward != null) {
			if(forward.isRedirect()) {	//true -> Redirect method
				response.sendRedirect(forward.getPath());
			}else {						//not true -> Dispatcher method 
				RequestDispatcher dispatcher = 
						request.getRequestDispatcher(forward.getPath());
						dispatcher.forward(request, response);
			}
		}
	}

12. Create a BoardAddAction Class in src-service. This class is for file upload/download.

 

13. Create a qna_board_write.jsp.

Here,  enctype="multipart/form-data" is essential for the file attachment function.

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

<html>
<head>
	<title>MVC Bulletin Board</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
	<style>
@import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap');
</style>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardAddAction.do" method="post" 
	  enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td style="font-family: 'Abril Fatface', cursive;" colspan="5">MVC Bulletin Board</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Writer</div>
		</td>
		<td>
			<input name="board_name" id="board_name" type="text" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Title</div>
		</td>
		<td>
			<input name="board_subject" id="board_subject" type="text" size="50" maxlength="100" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12">
			<div align="center">Content</div>
		</td>
		<td>
			<textarea name="board_content" id="board_content" cols="67" rows="15"></textarea>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12">
			<div align="center">Attach File</div>
		</td>
		<td>
			<input name="board_file" type="file"/>
		</td>
	</tr>
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Post">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

14. In the DAO class, add the insert method. 

// Insert method : Post
	public int insert(BoardBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection();

			String sql = "insert into model2 values(model2_seq.nextval,?,?,?,?,?,";
			sql += " model2_seq.nextval,?,?,?,sysdate)";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getBoard_name());
			pstmt.setString(2, board.getBoard_pass());
			pstmt.setString(3, board.getBoard_subject());
			pstmt.setString(4, board.getBoard_content());
			pstmt.setString(5, board.getBoard_file());
			pstmt.setInt(6, 0); // board_re_lev
			pstmt.setInt(7, 0); // board_re_seq
			pstmt.setInt(8, 0); // board_readcount
			result = pstmt.executeUpdate(); // To execute SQL

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}

		return result;
	}

When you upload the file, you will check the file by copying and pasting the path from the console.

15. Create BoardListAction.java in src-service.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BoardDAO;

public class BoardListAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardListAction");
		
		int page = 1;			// Current Page
		int limit = 10;			// How many pages will be printed? 10
		
		if(request.getParameter("page") != null) {
			 page = Integer.parseInt(request.getParameter("page"));
		}
		
		// ex) page = 1 : startRow = 1, endRow : 10
		int startRow = (page -1) * limit + 1;
		int endRow = page * limit;
		
		BoardDAO dao = BoardDAO.getInstance();
		int listcount = dao.getCount();	// Total data volume
		System.out.println("listcount: "+listcount);
		
			ActionForward forward = new ActionForward();
			forward.setRedirect(false);  // Dispatcher method 
			forward.setPath("./board/qna_board_list.jsp");
		
		return forward;
	}
	
}

16. In the Controller class, add the Post list part.

// Posts list
		}else if(command.equals("/BoardListAction.do")){
			try {
				action = new BoardListAction();
				forward = action.execute(request, response);
		}catch(Exception e){
			e.printStackTrace();
		}

17. In the DAO class, add the total data volume part.

	// Total data volum
	public int getCount() {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select count(*) from model2";
			
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
//				result = rs.getInt(1);
				result = rs.getInt("count(*)");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		return result;
	}

18. Add the get list method in BoardListAction.java and DAO class.

BoardListAction.java

//To get List 
		List<BoardBean> boardlist = dao.getList(startRow, endRow);
		System.out.println("boardlist: "+boardlist);
        
//Total pages number
		int pageCount = listcount / limit + (( listcount%limit == 0 )? 0 : 1); //if the result of listcount%limit is 0, increase 0, otherwise increase 1.
		
		int startPage = ((page-1)/ 10) * limit + 1; // 1, 11, 22...
		int endPage = startPage + 10 - 1; 	// 10, 20, 30...
		
		if(endPage > pageCount) endPage = pageCount;
		
		request.setAttribute("page", page);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", boardlist);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("startPage", startPage);
		request.setAttribute("endPage", endPage);

BoardDAO.java

	// Posts List ( 10 data)
	public List<BoardBean> getList(int start, int end){
		List<BoardBean> list = new ArrayList<BoardBean>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
	String sql="select * from (select rownum rnum, board.* from ";
		   sql+=" (select * from model2 order by board_re_ref desc, ";
		   sql+=" board_re_seq asc) board ) ";
		   sql+=" where rnum >= ? and rnum <= ?";
		   
		   pstmt = con.prepareStatement(sql);
		   pstmt.setInt(1, start);
		   pstmt.setInt(2, end);
		   rs = pstmt.executeQuery();  	//SQL
		   
		   while(rs.next()) {
			   BoardBean board = new BoardBean();
			   board.setBoard_num(rs.getInt("board_num"));
			   board.setBoard_name(rs.getString("board_name"));
			   board.setBoard_pass(rs.getString("board_pass"));
			   board.setBoard_subject(rs.getString("board_subject"));
			   board.setBoard_content(rs.getString("board_content"));
			   board.setBoard_file(rs.getString("board_file"));
			   board.setBoard_re_ref(rs.getInt("board_re_ref"));
			   board.setBoard_re_lev(rs.getInt("board_re_lev"));
			   board.setBoard_re_seq(rs.getInt("board_re_seq"));
			   board.setBoard_readcount(rs.getInt("board_readcount"));
			   board.setBoard_date(rs.getTimestamp("board_date"));
			   
			   list.add(board);
		   }
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		
		return list;
	}

19. Create qna_board_list.jsp and print out the posts list.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<a href="./BoardForm.do">Write my post</a>
<br>
Posts : ${listcount}
<br>
<%
	int count = ((Integer) request.getAttribute("listcount")).intValue();
%>

Total posts :<%=count%>
<br>
<table border=1 width=700 align=center>
	<caption>Posts List</caption>
	<tr>
		<th>No.</th>
		<th>Title</th>
		<th>Writer</th>
		<th>Date</th>
		<th>View</th>
	</tr>
	<c:set var="num" value="${listcount - (page-1) * 10}" />
	<c:forEach var="b" items="${boardlist}">
		<tr>
			<td>${num}<c:set var="num" value="${num-1}" />
			</td>
			<td>
				<!-- Space before reply --> 
				<c:if test="${b.board_re_lev > 0}">
					<c:forEach var="i" begin="0" end="${b.board_re_lev}">
					&nbsp;
				</c:forEach>

				</c:if> 
				<a href="./BoardDetailAction.do?board_num=${b.board_num}&page=${page}">
				${b.board_subject}</a>
			</td>
			<td>${b.board_name}</td>
			<td><fmt:formatDate value="${b.board_date}"
					pattern="dd.MM.yyyy HH:mm:ss EEEE" /></td>
			<td>${b.board_readcount }</td>
		</tr>
	</c:forEach>
</table>

When you run the index.jsp, you will see the posts list.

We will keep putting more functions into this project in the following posts. 

Main Funtions

1. Connection Pool

2. request, session object

3. Controller Class : Java Servlet

4. Model = Service + DAO

    Service, DTO, DAO Class

5. View: EL, JSTL 

 

In Model2, we need to separate the files into each package by function.

Here is how I planned to structure the program based on the MVC Architecture.

Controller Class : controller - MemberController.java

DTO Class: model - MemberDTO.java

DAO Class : dao - MemberDAO.java

Action Interface: service - Action.java

ActionForward Class: service - ActionForward.java

Service Class: service - MemberInsert.java

                                      - IdCheck.java(Id Validation check)

                                      - Login.java

                                      - Logout.java

                                      - UpdateMember.java

                                      - Update.java

                                      - DeleteMember.java

                                      - Delete.java

 

As this is my first time creating a Model2 project, so, I will write how I did it in detail. 

1. Create a Dynamic Web Project named model2member.

2. In the WebContent folder, create index.jsp.

3. In the lib folder, save three libraries: cos.jar, jstl-1.2jar, and ojdbc.jar.

4. In the WebContent folder, create member folder.

5. In the META-INF, create context.html for configuration.

<Context> 
  <Resource name="jdbc/orcl" 
   auth="Container"
   type="javax.sql.DataSource" 
   username="totoro" 
   password="totoro123"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
   url="jdbc:oracle:thin:@localhost:1521:xe"
   maxActive="500"  
   maxIdle="100"/>  
</Context>

6. Test with dbcpAPITest.jsp in WebContent - member folder.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
 	Connection conn = null; 
	
	try {
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		conn = ds.getConnection();
  		
  		out.println("<h3>Connected.</h3>");
	}catch(Exception e){
		out.println("<h3>Failed to connect.</h3>");
		e.printStackTrace();
 	}
%>

7. Create member.sql in WebContent - member - sql - member.sql and connect totoro account. 

8. Create a table named member2, block + Alt + X to create.

-- Model2 Customer Management Program

select * from tab;
select * from member2;

create table member2(
		id varchar2(20) primary key,
		passwd varchar2(20) not null,
		name varchar2(20) not null,
		jumin1 varchar2(6) not null,
		jumin2 varchar2(7) not null,
		mailid varchar2(30), 
		domain varchar2(30), 
		tel1 varchar2(5),
		tel2 varchar2(5),
		tel3 varchar2(5),
		phone1 varchar2(5),
		phone2 varchar2(5),
		phone3 varchar2(5),
		post varchar2(10),
		address varchar2(200),
		gender varchar2(20),
		hobby varchar2(50),
		intro varchar2(2000),
		register timestamp );

9. In the src folder, create a package named model, inside, create DTO Class namedMemberDTO.java.

10. Refer to the member table on sql, create properties. 

11. Mouse right click - Source - Generate Getters and Setters to create the getters and setters.

// DTO(Data Transfer Object)

package model;

import java.sql.Timestamp;

public class MemberDTO {
	private String id;		// Properties
	private String passwd;
	private String name;
	private String jumin1;
	private String jumin2;
	private String mailid;
	private String domain;
	private String tel1;
	private String tel2;
	private String tel3;
	private String phone1;
	private String phone2;
	private String phone3; 
	private String post; 
	private String address; 
	private String gender; 
	private String hobby; 
	private String intro; 
	private Timestamp register;
	public String getId() {
		return id;
	}
	public String getPasswd() {
		return passwd;
	}
	public String getName() {
		return name;
	}
	public String getJumin1() {
		return jumin1;
	}
	public String getJumin2() {
		return jumin2;
	}
	public String getMailid() {
		return mailid;
	}
	public String getDomain() {
		return domain;
	}
	public String getTel1() {
		return tel1;
	}
	public String getTel2() {
		return tel2;
	}
	public String getTel3() {
		return tel3;
	}
	public String getPhone1() {
		return phone1;
	}
	public String getPhone2() {
		return phone2;
	}
	public String getPhone3() {
		return phone3;
	}
	public String getPost() {
		return post;
	}
	public String getAddress() {
		return address;
	}
	public String getGender() {
		return gender;
	}
	public String getHobby() {
		return hobby;
	}
	public String getIntro() {
		return intro;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setId(String id) {
		this.id = id;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setJumin1(String jumin1) {
		this.jumin1 = jumin1;
	}
	public void setJumin2(String jumin2) {
		this.jumin2 = jumin2;
	}
	public void setMailid(String mailid) {
		this.mailid = mailid;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}
	public void setTel1(String tel1) {
		this.tel1 = tel1;
	}
	public void setTel2(String tel2) {
		this.tel2 = tel2;
	}
	public void setTel3(String tel3) {
		this.tel3 = tel3;
	}
	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}
	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}
	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}
	public void setPost(String post) {
		this.post = post;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}

}

12. In the src folder,create package named dao, inside, create DAO ClassnamedMemberDAO.java.

// DAO(Data Access Object)
package dao;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemberDAO {
	// Singleton : a design pattern that ensures that a class can only have one
	// object.
	private static MemberDAO instance = new MemberDAO();

	public static MemberDAO getInstance() { // static method
		return instance;
	}

	// Connection Pool
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}
	
	
}

13. Create a Servlet named controller, class name MemberController.

Since we don't need constructors, tick out the Contructors from superclass box.

14. In MemberController, change the WebServlet annotation to this : 

@WebServlet("*.do")
package controller; // 중간에 흐름을 제어하는 역할 

import java.io.IOException;

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 service.Action;
import service.ActionForward;
import service.MemberInsert;

/**
 * Servlet implementation class MemberController
 */
@WebServlet("*.do")
public class MemberController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// For processing common works of doGet() and doPost()
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		
		System.out.println("requestURI:" + requestURI);      // /model2member/Login.do
		System.out.println("contextPath:" + contextPath);	 // /model2member
		System.out.println("command:" + command); 			// /Login.do 
		
		Action action = null;
		ActionForward forward = null;
		
		// Sign up 
		if(command.equals("/MemberInsert.do")) {
			try {
				action = new MemberInsert();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		
		// Forward process
		if(forward != null) {
			if(forward != null) {	// redirect method
				response.sendRedirect(forward.getPath());
			}else {					// dispatcher method
				RequestDispatcher dispatcher = 
					request.getRequestDispatcher(forward.getPath());
				dispatcher.forward(request, response);
			}
		}
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("get");
		
		doProcess(request, response);		// call doProcess() method
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("post");
		
		doProcess(request, response);
	}
	
	

}

15. Create Action.java interface and ActionForward.java class in service package - src folder.

16. Go to MemberController, and update the forward process.

17. Create memberform.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>

<script src="<%=request.getContextPath() %>/member/member.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/memberInsert.do"> 
<table border=1 width=450 align="center">
	<caption>Sign Up</caption>
	<tr><td>ID</td>
		<td><input type=text autofocus="autofocus" id="id" name="id">
			<input type=button value="IDcheck" id="idcheck">
		</td>
	</tr>
	<tr><td>Password</td>
		<td><input type=password id="passwd" name="passwd">
		</td>
	</tr>
	<tr><td>Name</td>
		<td><input type=text id="name" name="name"></td>
	</tr>
	<tr><td>Resident Registration Number</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid">@
			<input type=text size=10 id="domain" name="domain">
			<select id="email">
				<option value="">Other</option>
				<option value="gmail.com">gmail</option>
				<option value="naver.com">Naver</option>
			</select>	
		</td>
	</tr>
	<tr><td>Office/Home Phone</td>
		<td><input type=text size=4 maxlength=4 id="tel1" name="tel1">-
		    <input type=text size=4 maxlength=4 id="tel2" name="tel2">-
		    <input type=text size=4 maxlength=4 id="tel3" name="tel3">-
		</td>
	</tr>
	<tr><td>Mobile</td>
		<td><select id="phone1" name="phone1">
				<option value="">Select Number</option>
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="018">018</option>
				<option value="019">019</option>
			</select>-
			<input type=text size=4 maxlength=4 id="phone2" name="phone2">-
		    <input type=text size=4 maxlength=4 id="phone3" name="phone3">		
		</td>	
	</tr>
	<tr><td>Post Code</td>
		<td><input type=text size=5 maxlength=5 id="post" name="post">
			<input type=button value="Search" onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>Address</td>
		<td><input type=text size=45 id="address" name="address"></td>
	</tr>
	<tr><td>Sex</td>
		<td><input type=radio id="male" name="gender" value="Male">Male
			<input type=radio id="female" name="gender" value="Female">Female
			<input type=radio id="Prefer not to say" name="gender" value="Prefer Not to say">Prefer Not to say
		</td>
	</tr>
	<tr><td>Hobby</td>
		<td><input type=checkbox id="h1" name="hobby" value="Studying">Studying
			<input type=checkbox id="h2" name="hobby" value="Programming">Programming
			<input type=checkbox id="h3" name="hobby" value="Hiking">Hiking
			<input type=checkbox id="h4" name="hobby" value="Reading">Reading
			<input type=checkbox id="h5" name="hobby" value="Cooking">Cooking
		</td>
	</tr>
	<tr><td>About Me</td>
		<td><textarea rows=5 cols=50 id="intro" name="intro"
		     placeholder="Please write about you in up to 100 words."></textarea>		
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="Sign Up">
			<input type=reset value="Cancel">
		</td>
	</tr>		
</table>
</form>

</body>
</html>

 

18. Create member.js for validation check.

$(document).ready(function(){	
	
	// ID Check
	$("#idcheck").click(function(){
		if($("#id").val()==""){
			alert("Insert ID.");
			$("#id").focus();
			return false;
		}else{
			
			var id = $("#id").val();	
			
			$.ajax({
				type:"post",
				url:"/model2member/Idcheck.do",
				data:{"id":id},
				datatype:"text",
				success:function(data){
//					alert(data);
					
					if(data==1){	
						$("#myid").text("Unavailable ID");
						$("#id").val("").focus();
					}else{			
						$("#myid").text("Available ID");
						$("#passwd").focus();
					}					
				}
			});			
		}		
	});
	
	// Move mouse cursor
	$("#jumin1").keyup(function(){
		
		if($("#jumin1").val().length == 6)
			$("#jumin2").focus();
	});
	
	
	// Domain
	$("#email").change(function(){
		if($("#email").val() == ""){	
			$("#domain").removeAttr("readonly");
			$("#domain").val("").focus();			
		}else{							
			$("#domain").val($("#email").val());
		    $("#domain").attr("readonly","readonly");
		}
	});
	
	// Validation Check
	$("form").submit(function(){
		
		if($("#id").val() == ""){
			alert("Insert ID.");
			$("#id").focus();
			return false;
		}		
		if($("#passwd").val()==""){
			alert("Insert Password.");
			$("#passwd").focus();
			return false;
		}		
		if($("#name").val()==""){
			alert("Insert Name.");
			$("#name").focus();
			return false;
		}
		if($("#jumin1").val()==""){
			alert("Insert Resident Registration Number1");
			$("#jumin1").focus();
			return false;
		}
		if($("#jumin1").val().length != 6){
			alert("Resident Registration Number1 has to be 6 digits.");
			$("#jumin1").val("").focus();
			return false;
		}
		if(isNaN($("#jumin1").val())){
			alert("Resident Registration Number has to be numbers only.");
			$("#jumin1").val("").focus();
			return false;
		}
		if($("#jumin2").val()==""){
			alert("Insert Resident Registration Number2.");
			$("#jumin2").focus();
			return false;
		}
		if($("#jumin2").val().length != 7){
			alert("Resident Registration Number2 has to be 7 digits.");
			$("#jumin2").val("").focus();
			return false;
		}
		if(isNaN($("#jumin2").val())){
			alert("Resident Registration Number has to be numbers only.");
			$("#jumin2").val("").focus();
			return false;
		}
		if($("#mailid").val()==""){
			alert("Insert Mailid.");
			$("#mailid").focus();
			return false;
		}
		if($("#domain").val()==""){
			alert("Insert Domain.");
			$("#domain").focus();
			return false;
		}
		if($("#tel1").val()==""){
			alert("Insert Office/Home Phone1.");
			$("#tel1").focus();
			return false;
		}
		if(isNaN($("#tel1").val())){
			alert("Office/Home Phone1 has to be numbers only.");
			$("#tel1").val("").focus();
			return false;
		}
		if($("#tel2").val()==""){
			alert("Insert Office/Home Phone2.");
			$("#tel2").focus();
			return false;
		}
		if(isNaN($("#tel2").val())){
			alert("Office/Home Phone2 has to be numbers only.");
			$("#tel2").val("").focus();
			return false;
		}
		if($("#tel3").val()==""){
			alert("Insert Office/Home Phone3.");
			$("#tel3").focus();
			return false;
		}
		if(isNaN($("#tel3").val())){
			alert("Office/Home Phone3 has to be numbers only.");
			$("#tel3").val("").focus();
			return false;
		}
		if($("#phone1").val()==""){
			alert("Select Mobile1.");			
			return false;
		}
		if($("#phone2").val()==""){
			alert("Insert Mobile2.");
			$("#phone2").focus();
			return false;
		}
		if(isNaN($("#phone2").val())){
			alert("Mobile2 has to be numbers only.");
			$("#phone2").val("").focus();
			return false;
		}
		if($("#phone3").val()==""){
			alert("Insert Mobile3.");
			$("#phone3").focus();
			return false;
		}
		if(isNaN($("#phone3").val())){
			alert("Mobile3 has to be numbers only.");
			$("#phone3").val("").focus();
			return false;
		}
		if($("#post").val()==""){
			alert("Insert post code.");
			$("#post").focus();
			return false;
		}
		if($("#address").val()==""){
			alert("Insert Address.");
			$("#address").focus();
			return false;
		}
		if($("#male").is(":checked")==false &&
		   $("#female").is(":checked")==false && 
		   $("#Prefer not to say").is(":checked")==false){
			alert("Select your sex.");
			return false;
		}
		
		if($("input:checkbox[name='hobby']:checked").length < 2){
			alert("Select at least 2 hobbies.");
			return false;
		}

		if($("#intro").val()==""){
			alert("Write About Me.");
			$("#intro").focus();
			return false;
		}
		if($("#intro").val().length > 100){
			alert("About Me has to be in up to 100 words.");
			$("#intro").focus();
			return false;
		}		
		
	}); // submit() end		
	
});  // ready() end

19. Create MemberInsert.java class in service package - service folder.

We need to override the method, click the "x" and add unimplemented methods.

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MemberDAO;
import model.MemberDTO;

public class MemberInsert implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("MemberInsert");
		
		request.setCharacterEncoding("utf-8");
		
		MemberDTO member = new MemberDTO();
		member.setId(request.getParameter("id"));
		member.setPasswd(request.getParameter("passwd"));
		member.setName(request.getParameter("name"));
		member.setJumin1(request.getParameter("jumin1"));
		member.setJumin2(request.getParameter("jumin2"));
		member.setMailid(request.getParameter("mailid"));
		member.setDomain(request.getParameter("domain"));
		member.setTel1(request.getParameter("Tel1"));
		member.setTel2(request.getParameter("Tel2"));
		member.setTel3(request.getParameter("Tel3"));
		member.setPhone1(request.getParameter("Phone1"));
		member.setPhone2(request.getParameter("Phone2"));
		member.setPhone3(request.getParameter("Phone3"));
		member.setPost(request.getParameter("Post"));
		member.setAddress(request.getParameter("address"));
		member.setGender(request.getParameter("gender"));
		
		String[] hobby = request.getParameterValues("hobby");
		String h = "";
		for(String h1 : hobby) {
			h += h1 + "=";
		}
		member.setHobby(h);
		member.setIntro(request.getParameter("intro"));
		
		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.insert(member);	// Sign up
		if(result == 1) System.out.println("Successfully signed up. Welcome!");
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);					// dispatcher method
		forward.setPath("./member/loginform.jsp"); // page forward
		
		
		ActionForward forward = new ActionForward();
		
		return forward;
	}

}

20. Add Insert method in MemberDAO.java.

	// Sign up 
	public int insert(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="insert into member2 ";
				   sql+="values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			pstmt.setString(2, member.getPasswd());
			pstmt.setString(3, member.getName());
			pstmt.setString(4, member.getJumin1());
			pstmt.setString(5, member.getJumin2());
			pstmt.setString(6, member.getMailid());
			pstmt.setString(7, member.getDomain());
			pstmt.setString(8, member.getTel1());
			pstmt.setString(9, member.getTel2());
			pstmt.setString(10, member.getTel3());
			pstmt.setString(11, member.getPhone1());
			pstmt.setString(12, member.getPhone2());
			pstmt.setString(13, member.getPhone3());
			pstmt.setString(14, member.getPost());
			pstmt.setString(15, member.getAddress());
			pstmt.setString(16, member.getGender());
			pstmt.setString(17, member.getHobby());
			pstmt.setString(18, member.getIntro());
			
			result = pstmt.executeUpdate();
			
		}catch(Exception e){
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

 

21. For ID check, create Idcheck.java in service - src.

22. Add IDcheck part(ajax) in MemberController.java class. 

//ID check(ajax)
		}else if(command.equals("/Idcheck.do")) {
			try {
				action = new IdCheck();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
// Sign up
		} else if (command.equals("/MemberForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("./member/memberform.jsp");

If you click the sign up button, it will load to the sign up form again and the code below"//Sign up" make it possible.

To check if the ID check works, check the console in Eclipse.

 

23. Add lines related to ID check in MemberDAO.java.

// ID check(ajax)
	public int idcheck(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member2 where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery(); 			// SQL statement
			
			if(rs.next()) {
				result = 1;
			}else {
				result = -1;
			}
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {			
			if(rs != null) try { rs.close();} catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

24. Create loginform.jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
	<!DOCTYPE html>
	<html>
	<head>
	<meta charset="UTF-8">
	<title>Log In</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>

	<script src="<%=request.getContextPath() %>/member/login.js"></script>
	
	</head>
	<body>
	
	<form method="post" action="<%=request.getContextPath() %>/Login.do">
	<table border=1 width=350 align=center>
		<caption>Log In</caption>
		<tr>
			<td>ID</td>	
			<td><input type=text size=30 id="id" name="id" autofocus="autofocus"></td>	
		</tr>
		<tr>
			<td>Password</td>
			<td><input type="password" size=30 id="passwd" name="passwd"></td>
		</tr>
		<tr>
			<td colspan=2 align=center>
				<input type="button" value="Sign Up" 
				       onClick="location.href='<%=request.getContextPath()%>/MemberForm.do' ">
				<input type="submit" value="Log In">
				<input type="reset" value="Cancel">
			</td>
		</tr>
		
	</table>
	</form>
	
	
	</body>
	</html>

25. Create Login.java class in service- src and override the method.

package service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.MemberDAO;

public class Login implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Login");

		request.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();

		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");

		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.memberAuth(id, passwd);
		if (result == 1)
			System.out.println("You are successfully logged in.");

		if (result == 1) { // Successful
			session.setAttribute("id", id); // Share with session
		} else { // Failed
			out.println("<script>");
			out.println("alert('Failed to log in.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();

			return null;
		}
		ActionForward forward = new ActionForward();
		forward.setRedirect(false); // Forward with dispatcher method
		forward.setPath("./member/main.jsp"); // To set the file name to forward

		return forward;
	}

}

26. Add memberAuth method in the DAO class.

// Login(Verification)
	public int memberAuth(String id, String passwd) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member2 where id=? and passwd=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, passwd);
			rs = pstmt.executeQuery();		//To execute SQL
			
			if(rs.next()) {		//Verification Success
				result = 1;
			}else {			  //Verification Fail
				result = -1;
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally{
			if(rs != null) try { rs.close();} catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

27. Connect this loginform to the controller class.

// Log in (Verification)
		} else if (command.equals("/Login.do")) {
			try {
				action = new Login();
				forward = action.execute(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

28. Create main.jsp file in member folder.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- When there is a session -->
<%-- <c:if test="${sessionScope.id != null }"> --%>
<c:if test="${!empty sessionScope.id}">    <!-- Empty operator -->
	${sessionScope.id }, Welcome! <br><br>
	
	Edit my profile<br>
	Log out<br>
	Delete my account<br>
</c:if>


<!-- When there is no session -->
<%-- <c:if test="${sessionScope.id == null }"> --%>
<c:if test="${empty sessionScope.id}">
	<a href="<%=request.getContextPath() %>/MemberForm.do">Sign up</a><br>
	<a href="<%=request.getContextPath() %>/LoginForm.do">Log in</a><br>
</c:if>

29. Add another else if for login form toMemberController.java.

// Login form
		} else if (command.equals("/LoginForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("./member/loginform.jsp");
		}

So far, we have made the sign-up form, log-in form, and main form connected to the database with MemberDAO class and MemberController class. In the next post, I will demonstrate the log-out form, account update form, and account deletion form.

 

+ Recent posts