Searching what the reserved words are before you create tables in Oracle is crucial. 

 

In the following link, you can see the reserved words. 

In my first group project, I remember that we used some reserved words to create tables, so errors occurred when we were creating. I created new tables on eXERD, and the system said Invalid table name.

 

https://docs.oracle.com/cd/B19306_01/em.102/b40103/app_oracle_reserved_words.htm

 

Oracle Reserved Words

30/31 G Oracle Reserved Words This appendix provides a complete list of Oracle reserved words. List of Oracle Reserved Words In addition to the reserved words in Table G-1, Oracle also uses system-generated names beginning with SYS_ for implicitly generate

docs.oracle.com

If you find it hard to come up with new words instead of reserved words, you can refer to this website for synonyms. 

https://www.wordhippo.com/

 

WordHippo!

Thesaurus and word tools for your creative needs. Find the word you're looking for!

www.wordhippo.com

 

'DB > Oracle' 카테고리의 다른 글

Java-Oracle Interworking Configuration  (0) 2022.09.11
Oracle) Structured Query Language(SQL)  (0) 2022.09.03
Oracle) Setting up  (0) 2022.09.01

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>

 

In the last post, we launched the instance and set it up with the free tiers on AWS. 

In this post, we will use Remote Desktop Connection and upload JDK, Oracle, and Apache Tomcat in the Remote Desktop. 

 

Open the Remote Desktop Connection and insert the public IP address. 

Log in with the Administrator. 

You will see this Remote Desktop after you enter the decrypted password from AWS. 

Here, download JDK, Oracle, and Apache Tomcat. 

In the Server Manager, go to Services. 

In the Services, set Apache Tomcat's Startup type, Automatic.

To set the firewall, 

Now, when you enter the public IP in your localhost, you will see that it is connected. 

 

We will create a new Database Connection in the localhost Oracle SQL Developer to connect Oracle.

To deploy the tables that have already been made, we will create an account that already has a table. 

create user spring identified by spring123;

grant connect, resource to spring;

Create aws_spring in SQL Developer and Spring. 

We will deploy a spring project named springboard, so go to the sql file, and change the connection's name to aws_spring. Then, create a table and a sequence. It will 

Export the project as WAR. Unzip the file and import it to the Remote Desktop. 

Import the project in the root folder where the Apache Tomcat is set. 

Delete these sample files, copy the project from the localhost, and paste into the Remote Desktop. 

Now it is all done. Enter the Public IP Address to see if it is well done.

Look! It works! 

AWS stands for Amazon Web Service. It is a service of Amazon. 

There are three main services: EC2(Elastic Computer Cloud), RDS(Relational Database Service), and S3(Simple Storage Service). To use the service for free for a year, sign up for AWS. 

 

https://aws.amazon.com/

Click the link above to the main page or below to load directly to the signup page. 

https://portal.aws.amazon.com/billing/signup#/start/email

You must verify your email address, phone number, and credit/debit card.

 

When you see this, click the Basic support - Free to use for free. 

It is all set. 

To log in, we will tick the Root User.

After signing in, you will see this Console Home.

Go to EC2 page. 

Select the region where you are. I am currently in Seoul, so I selected Seoul. 

Click Launch instance.

Name the instance and choose one of the application and OS Images. I will choose Windows. To make sure you don't have, double-check if it is Free tier eligible

Also, check the Free tier eligiblity with the instance type. Click create new key pair

Create your own key pair that is hard to forget. And keypairname.pem file will be created.

In the Network settings, choose the existing security group and the default one.

Other, just leave them as they are. After all, you will see this Summary. If everything is alright, Launch Instance.

When you click the Instances tap, you will see the instance running that you just launched.

Take note of the Public IPv4 address since you will need it often.

To connect, check the box and click Connect

Here, you will upload the key pair that was downloaded before. 

Decrypt the password and take note of the decrypted password. You will not see this password every time, so make sure you know where you took the note of it.

 

In the Security group menu, click Inbound rules. We will edit the inbound rules. 

We will add RDP(Remote Desktop Protocol), Oracle-RDS, and HTTP(Hypertext Transfer Protocol) and save.

 

In the next post, we will connect this to the Remote Desktop.

 

Thymeleaf is a template engine that plays a key role in web frameworks, though, and is one of its most important components as they are in charge of producing the user interface or view layer (usually in XHTML or HTML form).

 

Here is a very nice article that you can refer to for introducing yourself to the Thymeleaf world. 

In this post, we will see the basic syntaxes of Thymeleaf.

https://www.baeldung.com/thymeleaf-in-spring-mvc

 

 

First, you must write this tag to use the thymeleaf tags in the HTML or XHTML. 

<html xmlns:th="http://www.thymeleaf.org">

And, save the objects in a controller class and call with the thymeleaf tags. 

SampleController.java 

package com.example.demo.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.model.Member;

@Controller
public class SampleController {

	@RequestMapping("sample1")
	public String sample1(Model model) {		
//		model.addAttribute("greeting", "Hello World");
		model.addAttribute("greeting", "Hello World");		
		return "sample1";
	}
	
	@RequestMapping("sample2")
	public String sample2(Model model) {
		Member member = new Member(1,"test","1234","Meadow", new Timestamp(System.currentTimeMillis()));
		
		model.addAttribute("member", member);
		
		return "sample2";
	}
	
	@RequestMapping("sample3")
	public String sample3(Model model) {
		List<Member> list = new ArrayList<Member>();
		
		for(int i=0; i<10; i++) {
			Member member = new Member(1,"test"+i,"1234","Meadow"+i, new Timestamp(System.currentTimeMillis()));			
			list.add(member);
		}		
		model.addAttribute("list", list);
		
		return "sample3";
	}
	
	@RequestMapping("sample4")
	public String sample4(Model model) {
		List<Member> list = new ArrayList<Member>();
		
		for(int i=0; i<10; i++) {
			Member member = new Member(i,"u000"+i %3,     // 3으로 나눈 나머지 id
					                     "p000"+i %3,     // 3으로 나눈 나머지 pw 
					                     "Meadow"+i, 
					                     new Timestamp(System.currentTimeMillis()));			
			list.add(member);
		}		
		model.addAttribute("list", list);
		
		return "sample4";
	}
	
	@RequestMapping("sample5")
	public String sample5(Model model) {
		
		String result = "SUCCESS";
		
		model.addAttribute("result", result);
		
		return "sample5";
	}
	
	@RequestMapping("sample6")
	public String sample6(Model model) {	
		
		model.addAttribute("now", new Date());
		model.addAttribute("price", 123456789);
		model.addAttribute("title", "Sample title");
		model.addAttribute("options", Arrays.asList("AAA","BBB","CCC","DDD"));
		
		return "sample6";
	}
	
	@RequestMapping("sample7")
	public String sample7(Model model) {	
		
		return "sample7";
	}
	
}

 

To print out String : th:text

<h1 th:text="${greeting}">Thymeleaf Test page</h1>

If you just write ${greeting}, it will not work as a thymeleaf tag. 

 

To print DTO object : th:text

<h1 th:text="${member}">Thymeleaf Test page</h1>

To print out the data from the controller class : th:utext

<div th:utext='${"<h3>"+member.no+"</h3>"}'></div> 
<div th:utext='${"<h3>"+member.id+"</h3>"}'></div> 
<div th:utext='${"<h3>"+member.pw+"</h3>"}'></div> 
<div th:utext='${"<h3>"+member.name+"</h3>"}'></div> 
<div th:utext='${"<h3>"+member.regdate+"</h3>"}'></div>

To print out list object : the:each="member : ${list}"

	<tr th:each="member : ${list}">
		<td th:text="${member.id}"></td>
		<td th:text="${member.name}"></td>
		<td th:text="${#dates.format(member.regdate,'yyyy-MM-dd HH:mm:ss')}"></td>
	</tr>

To run loops : th:each

<table border="1" align="center" width="300">
	<tr>
		<td>ID</td>
		<td>NAME</td>
		<td>REGDATE</td>
	</tr>
	<tr th:each="member : ${list}">
		<td th:text="${member.id}"></td>
		<td th:text="${member.name}"></td>
		<td th:text="${#dates.format(member.regdate,'yyyy-MM-dd HH:mm:ss')}"></td>
	</tr>
</table><br>

To define variables : th:with

<table border="1" align="center" width="300" th:with="target='u0001'">

If tag : th:if ~ th:unless

<table border="1" align="center" width="300" th:with="target='u0001'">
	<tr>
		<td>ID</td>
		<td>NAME</td>
		<td>REGDATE</td>
	</tr>
    
	<tr th:each="member : ${list}">
		<td th:if="${member.id}">
		    <a href="/modify" th:if="${member.id == target}">Modify</a>
		    <p th:unless="${member.id == target}">View</p>
		</td>
		<td th:text="${member.name}"></td>
		<td th:text="${#dates.format(member.regdate,'yyyy-MM-dd HH:mm:ss')}"></td>
	</tr>
</table>

To run javascript with thymeleaf : th:inline

<script th:inline="javascript">
	var result = [[${result}]]; 	   
	document.write(result);			
</script>

<script>
	var result = [[${result}]];          
	document.write(result);              
</script>

To set the format of dates

<h2 th:text="${#dates.format(now, 'yyyy-MM-dd HH:mm:ss')}"></h2>

To set the format of numbers

<h2 th:text="${#numbers.formatInteger(price, 3, 'COMMA')}"></h2>

To print out bold

<span th:utext="${#strings.replace(title,'t','<b>t</b>')}"></span>

To break down into words and print out as a list (parsing)

<ul>
	<li th:each="str:${#strings.listSplit(title,' ')}">[[${str}]]</li>
</ul>

 

To link 

<ul>    
	<li><a th:href="@{http://localhost:80/sample1}">sample1</a></li>
	<li><a th:href="@{/sample1}">sample1</a></li>
	<li><a th:href="@{~/sample1}">sample1</a></li>
	
	<!-- To send the value -->	
	<!-- http://localhost/Thymeleaf/sample1?p1=aaa&p2=bbb -->
	<li><a th:href="@{/sample1(p1='aaa', p2='bbb')}">sample1</a></li>
</ul>

To print out list with for loop

HomeController.java

package com.example.demo.controller;

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

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

@Controller
public class HomeController {

	
	@RequestMapping("/listTest")
	public void listTest(Model model) {
		
		List list = new ArrayList();
		
		for(int i=1; i<=20; i++) {
			list.add("Data:"+i);
		}
		
		model.addAttribute("name", "Sample Data");
		model.addAttribute("list", list);
	}
}

listTest.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>

	<p th:text=" 'Hello, ' + ${name} +'!' "/>
	
	<ul>
		<li th:each="data : ${list}"  th:text="${data}"></li>
	</ul>

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

 

What is Spring Boot? Spring Boot is an extension of Spring, which eliminates the boilerplate configurations required for setting up a Spring application.

 

Features

Spring Boot enables the development of independent running spring applications because Tomcat and Jetty are already embedded. It manages libraries with Maven/Gradle using Integrated Starter and provides automated spring settings which means you don't need six configuration files as Spring. 
Also, what makes it more convenient is that it does not require cumbersome XML settings. Spring Boot also provides Spring Actuator which is used for monitoring and managing applications. 

 

If you already have higher than STS3.0, you can easily create a Spring Boot Project. 

There are many dependencies that you can add easily such as websocket, NoSQL, SQL, MyBatis Framework, and so on. Here, check the Spring web box to add the dependency. 

Once we create the project, to check if it is created well, run it on the Spring Boot App.

If you see this on the console, it means it is set well! 

 

Configuration 

pom.xml 

configuration.xml

mapper class. 

 

There are no servlet-context.xml, root-context.xml, and web.xml.

In the static folder, we will save css related files and in the templates folder, we will save HTML files. 

In Spring Boot, you need to make controller classes by yourself, unlike Spring. So, create the controller folder in the demo folder, and create SampleController.java. 

 

The application.properties file is empty, you will add the basic configurations that you want to set such as a port number and prefix and suffix. Depending on the functions of the projects, you can add other properties in this file. Other then this, Spring and Spring Boot are very similar. 

 

Lombok 

Lombok is something that makes the project even simpler. Once you use Lombok function, you don't need getter and setter methods in DTO class. Instead of these methods, with this Lombok function, you can use simple annotations. 

 

To compare the projects with and without Lombok function, we will create a new project. 

 

Spring Starter Project without Lombok

Create a new project and check the boxes of the dependencies that you need for the project. 

The dependencies that you checked will be downloaded automatically once you click the Finish button and you will see the dependencies in pom.xml.

 

In application.properties, you won't see anything because, in Spring Boot, we need to add the configurations. 

So, we will set a port number and prefix/ suffix here.

 

In main / java / com / example / demo / model, create a DTO Class, Member.java

In this project, we are not using the Lombok, so we will create getter and setter methods. 

In the same demo folder, create a controller package and create SampleController.java.

Create index.jsp to connect the controller class. In the index.jsp, link "main" and create main.jsp.

 

In this demonstration, we will make a login form. 

main.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>
</head>
<body>
	<form method="post" action="send">
	ID: <input type=text name="id"> <br>
	Password: <input type=text name="passwd"> <br>
	<input type="submit" value="Log in">
	</form>

</body>
</html>

So the flow will be index.jsp -> SampleController.java -> main.jsp.

In terms of encoding, you don't have to care, because Spring boot will automatically take care of it.

 

Spring Starter Project with Lombok

With the Lombok dependency, you don't have to create getter and setter methods, or other constructors like toString() and Equals(). First, add the dependency in pom.xml and we need to download the dependency from the Lombok website(https://projectlombok.org/all-versions).

To execute the downloaded file, you need to do two things: add dependency and install it in STS.

Since we already added the dependency, we will do the latter one. 

Open the command prompt and insert the commands below.

 

Click the Install/Update button and you will see the alert "Install successful".

It is all set and now, we can use the Lombok function. 

In the Member.java, comment out the getter and setter methods. 

Instead of getter and setter methods, we will use annotations. 

	@Getter
	@Setter
	// @Data
	public class Member {
		private String id;
		private String passwd;
	}

As you can see, if you use the Lombok function, the codes will be still shorter and simpler. 

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

 

2022.10.11 - [Spring] - Spring) How to start a new Spring Framework Project[1]

 

Spring) How to start a new Spring Framework Project[1]

Starting a new Spring Framework Project is similar to creating a Dynamic Web Project in Eclipse. However, the structure is a bit more complicated if it is your very first time. So in this post, we w..

www.agilemeadow.com

 

32. Create boardlist.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"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Post List</title>
</head>
<body>
	<a href="boardform.do">New post</a>
	<br> Total posts: ${listcount }
	<table border=1 align=center width=700>
		<caption>Post list</caption>
		<tr>
			<th>No.</th>
			<th>Title</th>
			<th>Writer</th>
			<th>Date</th>
			<th>View Count</th>
		</tr>

		<!-- Post List -->
		<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>
				<a href="boardcontent.do?no=${b.no }&page=${page}"/>
				${b.subject }
				</td>
				<td>${b.writer }</td>
				<td>
				<fmt:formatDate value="${b.register }"
					 pattern="dd-MM-yyyy HH:mm:ss"/>
				</td>
				<td></td>
			</tr>
		</c:forEach>
	</table>
	
	<!-- Pagination -->
	<center>
	<c:if test="${listcount > 0 }">
	
	<!-- Move to page no.1 -->
	<a href="boardList.do?page=1" style="text-decoration:none"> << </a>
	
	<!-- Move to the previous block -->
	<c:if test="${starPage > 10 }">
	<a href="boardlist.do?page=${startPage-1 }" style="text-decoration:none">[Prev]</a>
	</c:if>
	
	<!-- Print 10 posts in each block -->
	<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="boardlist.do?page${i}">[${i }]</a>
	</c:if>
	
	</c:forEach>
	
	<!-- Move to the next block -->
	<c:if test="${endPage < pageCount }">
	<a href="boardlist.do?page${startPage+10 }" style="text-decoration:none">[Next]</a>
	</c:if>
	
	<!--  Move to the last page -->
	<a href="boardlist.do?page${pageCount }" style="text-decoration:none"> >> </a>
	
	</c:if>
	</center>
	
</body>
</html>

33. In the controller class, add codes for the detail page. 

BoardController.java

// Post Detail : view count +1 , Post detail
		@RequestMapping("boardcontent.do")
		public String boardcontent(int no, int page, Model model) {
			
			//View count +1
			bs.updatecount(no);
			Board board = bs.getBoard(no);
			String content = board.getContent().replace("\n", "<br>");
			
			model.addAttribute("board", board);
			model.addAttribute("content", content);
			model.addAttribute("page", page);
			
			return "board/boardcontent";
		}

33. In the service class, connect it to the dao class.

BoardService.java

	public void updatecount(int no) {
		dao.updatecount(no);
	}

	public Board getBoard(int no) {
		return dao.getBoard(no);
	}

BoardDao.java

	public void updatecount(int no) {
		// TODO Auto-generated method stub
		session.update("hit", no);
	}

	public Board getBoard(int no) {
		// TODO Auto-generated method stub
		return session.selectOne("content", no);
	}

34. In the board.xml, add the update and select SQL.

	<!-- view count + 1 -->
	<update id="hit" parameterType="int">
		update myboard set readcount=readcount+1 where no=#{no}
	</update>
	
	<!-- Post detail -->
	<select id="content" parameterType="int" resultType="board">
		select * from myboard where no = #{no}
	</select>

35. Create boardcontent.jsp.

Link the List, Edit, and Delete buttons to corresponding pages. 

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Post detail</title>
</head>
<body>
	<table border=1 width=400 align=center>
		<caption>Post detail</caption>
		<tr>
			<td>Writer</td>
			<td>${board.writer }</td>
		</tr>
		<tr>
			<td>Date</td>
			<td><fmt:formatDate value="${board.register }"
					pattern="dd-MM-yyyy HH:mm:ss" /></td>
		</tr>
		<tr>
			<td>View</td>
			<td>${board.readcount }</td>
		</tr>
		<tr>
			<td>Title</td>
			<td>${board.subject }</td>
		</tr>
		<tr>
			<td>Content</td>
			<td><pre>${board.content }</pre> ${content}</td>
		</tr>
		<tr>
			<td colspan=2 align=center>
			<input type="button" value="List"
			onClick ="location.href='boardlist.do?page=${page}' ">
			<input type="button" value="Edit"
			onClick="location.href='boardupdateform.do?no=${board.no}&page=${page}'"> 
			<input type="button" value="Delete"
			onClick="location.href='boarddeleteform.do?no=${board.no }&page=${page}'">
			</td>
		</tr>

	</table>

</body>
</html>

36. In the controller class, we will request the values with @RequestMapping annotation

// Post Detail : view count +1 , Post detail
		@RequestMapping("boardcontent.do")
		public String boardcontent(int no, int page, Model model) {
			
			//View count +1
			bs.updatecount(no);
			Board board = bs.getBoard(no);
			String content = board.getContent().replace("\n", "<br>");
			
			model.addAttribute("board", board);
			model.addAttribute("content", content);
			model.addAttribute("page", page);
			
			return "board/boardcontent";
		}

37. Create boardupdateform.jsp and link the controller class to this file. 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Post</title>
</head>
<body>

<form method=post action="boardupdate.do">
<input type="hidden" name="no" value="${board.no }">
<input type="hidden" name="page" value="${page }">
<table border=1 width=400 align=center>
	<caption>Edit Post</caption>
	<tr><th>Writer</th>
		<td><input type=text name="writer" required="required"
		value="${board.writer }" autofocus="autofocus"></td>
	</tr>
	<tr><th>Password</th>
		<td><input type=password name="passwd" required="required"></td>
	</tr>
	<tr><th>Title</th>
		<td><input type=text name="subject" required="required" value="${board.subject }"></td>
	</tr>
	<tr><th>Content</th>
		<td><textarea cols=40 rows=5 name="content" required="required">${board.content }</textarea></td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="Edit">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

38. BoardController.java -> BoardService.java -> BoardDao.java

BoardController.java

//Update Form 
		@RequestMapping("boardupdateform.do")
		public String boardupdateform(int no, int page, Model model) {
			
			Board board = bs.getBoard(no);	//Detail 
			
			model.addAttribute("board", board);
			model.addAttribute("page", page);
			
			return "board/boardupdateform";
		}
		
		// Update
		@RequestMapping("boardupdate.do")
		public String boardupdate(Board board, int page, Model model) {
			int result = 0;
			Board old = bs.getBoard(board.getNo());
			
			// Password Check
			if(old.getPasswd().equals(board.getPasswd())) { //Correct Password
				result = bs.update(board);			// Update 
			}else {    										//Incorrect Password
				result = -1;
			}
			model.addAttribute("result", result);
			model.addAttribute("board", board);
			model.addAttribute("page", page);

			return "board/updateresult";
		}

BoardService.java 

	public int update(Board board) {
		// TODO Auto-generated method stub
		return dao.update(board);
	}

BoardDao.java

	public int update(Board board) {
		// TODO Auto-generated method stub
		return session.update("update", board);
	}

39. Insert update SQL in the board.xml.

<!-- Update -->
	<update id="update" parameterType="board">
		update myboard set writer=#{writer}, subject=#{subject}, 
		content=#{content}, register=sysdate where no=#{no}
	</update>

40. Create updateresult.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>updateresult</title>
</head>
<body>

	<c:if test="${result == 1 }">
		<script>
			alert("Successfully updated.");
			location.href ="boardlist.do?page=${page}"; //List page
			//	location.href="boardcontent.do?no=${board.no}&page=${page}";	//Detail page
		</script>
	</c:if>

	<c:if test="${result != 1 }">
		<script>
			alert("Failed to update.");
			history.go(-1);
		</script>
	</c:if>

</body>
</html>

41. Create boarddeleteform.jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Delete Post</title>
</head>
<body>

no: ${param.no }<br>
page: ${param.page }<br>

<form method=post action="boarddelete.do">
<input type="hidden" name="no" value="${param.no }">
<input type="hidden" name="page" value="${param.page }">
<table border=1 width=400 align=center>
	<caption>Delete Post</caption>
	
	<tr><th>Password</th>
		<td><input type=password name="passwd" required="required"></td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="Delete">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

42. Add the code in the BoardController.java -> BoardService.java -> BoardDao.java.

BoardController.java

		// Delete
		@RequestMapping("boarddelete.do")
		public String boarddelete(Board board, int page, Model model) {
			int result = 0;
			Board old = bs.getBoard(board.getNo());		// Post Detail
			
			//Password Check
			if(old.getPasswd().equals(board.getPasswd())) { //Correct Password
				result = bs.delete(board.getNo());			// Delete
			}else {    										//Incorrect Password
				result = -1;
			}
			
			model.addAttribute("result", result);
			model.addAttribute("page", page);
			
			return"board/deleteresult";
		}
}

BoardService.java

	public int delete(int no) {
		// TODO Auto-generated method stub
		return dao.delete(no);
	}

BoardDao.java.

	public int delete(int no) {
		// TODO Auto-generated method stub
		return session.delete("delete", no);
	}

43. Insert delete SQL in the board.xml.

	<!-- Delete -->
	<delete id="delete" parameterType="int">
		delete from myboard where no = #{no}
	</delete>

44. Create deleteresult.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>Delete</title>
</head>
<body>
	<c:if test="${result == 1 }">
		<script>
			alert("Successfully deleted.");
			location.href = "boardlist.do?page=${page}";
		</script>
	</c:if>

	<c:if test="${result != 1 }">
		<script>
			alert("Failed to delete.");
			history.go(-1);
		</script>
	</c:if>

</body>
</html>

As you can see, once you get the pattern, it becomes easier to process more efficiently. 

Starting a new Spring Framework Project is similar to creating a Dynamic Web Project in Eclipse. However, the structure is a bit more complicated if it is your very first time. 

So in this post, we will discuss creating a spring project from scratch. 

 

Create a spring project on STS and a new account on Oracle. 

After then, create the folders and files.

 

Configuration file settings in order
1) pom.xml
2) web.xml
3) servlet-context.xml
4) configuration.xml
5) board.xml
6) root-context.xml

 

1. Create a new account 

2. Create a Spring Legacy Project.

Fill out the project name, and select the Spring MVC Project.

Write the top-level package in the reverse order of the normal website URLs. 

Once it is created, you will see this.

To see if it works, run it on the server.

You will see this on the Server.

3. Create sql folder and sql file. Connect to the new account. 

4. Create a new table and sequence. 

-- Bulletin board

select * from tab;
select * from seq;
select * from myboard;

create table myboard(
	  no number primary key,
	  writer varchar2(20),
      passwd varchar2(20),
	  subject varchar2(50),
	  content varchar2(100),
	  readcount number,
	  register date );

create sequence myboard_seq;

5. Set pom.xml and run on the server to see if it is set well.

6. Set web.xml. Include encoding tags. 

7. Set HomeController.java.

8. Create an index.jsp in webapp folder. Link to the "test.do".

You must keep testing the project every time you create a new file. 

<%@ 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>
	location.href="test.do";

</script>

</body>
</html>

9. Set servlet-context.xml. Set the base package as myspring and create a new myspring folder containing controller, dao, model, and service folders.

10. Make BoardController.java,BoardService.java, and BoardDao.java in each folder.

11. In the BoardController class, add @Controller, @Autowired annotations. Create the same annotations with other classes as below.

BoardService - @Service, @Autowired

BoardDao - @Repository, @Autowired

 

Please see the picture below to understand what to put in the classes.

12. Create Board.java in the model folder. 

package myspring.model;

import java.util.Date;

public class Board {
	
	private int no;
	private String writer;
	private String passwd;
	private String subject;
	private String content;
	private int readcount;
	private Date register;
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getReadcount() {
		return readcount;
	}
	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}
	public Date getRegister() {
		return register;
	}
	public void setRegister(Date register) {
		this.register = register;
	}
	
}

13. Create a board folder in the views folder. In the board folder, create the first file, boardform.jsp.

14. Change the link in the index file to the "boardform.do".

15. In the controller class, connect the boardform.do with the @RequestMapping annotation.

// Boardform
		@RequestMapping("boardform.do")
		public String boardform() {
			return "board/boardform";
		}

16. Set configuration.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>

	<typeAliases>
		<typeAlias alias="board" type="myspring.model.Board" />
	</typeAliases>	
	
</configuration>

17. Create a mapper file, board.xml.

18. Set root-context.xml to connect to the database.

You need to keep this order of configuration files to make the project run. 

19. To insert the contents in the database, go to the controller class and add the codes to connect DAO Class.

BoardController.java

// Write a new post
		@RequestMapping("boardwrite.do")
		public String boardwrite(Board board, Model model) {
			int result = bs.insert(board);
			if(result == 1) System.out.println("Successfully posted.");
			
			model.addAttribute("result", result);
			
			return "board/insertresult";
		}

20. In the service class and DAO Class, add the insert() method

BoardService.java

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

BoardDao.java

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

21. In the board.xml, add insert SQL. The parameter type, the board is the alias set in the configuration file. 

Do not put a semicolon after the SQL. 

<!-- New post -->
	<insert id="insert" parameterType="board"> 	<!-- board: Alias of Configuration.xml -->
		insert into myboard values(myboard_seq.nextval,#{writer},
		#{passwd}, #{subject}, #{content},0, sysdate)
	</insert>

22. Create a new file, insertresult.jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
    
<c:if test="${result == 1 }">
	<script>
		alert("Successfully posted.");
		location.href="boardlist.do";
	</script>
</c:if>

<c:if test="${result != 1 }">
	<script>
		alert("Failed to post");
		history.go(-1);
	</script>
</c:if>

23. Add codes in the controller class to see the post list. Also, include the codes for pagination. 

		// Post list & pagination
		@RequestMapping("boardlist.do")
		public String boardlist(HttpServletRequest request, Model model) {
			
			int page = 1;  // current page no. 
			int limit = 10;  // limit posts on the page 
			
			if(request.getParameter("page") != null) {
				page = Integer.parseInt(request.getParameter("page"));
			}
			
			int startRow = (page - 1) * limit + 1;
			int endRow = page * limit;
			
			int listcount = bs.getCount(); // Total data count 
			System.out.println("listcount: " + listcount);
			
			List<Board> boardlist = bs.getBoardList(page); // Post List
			System.out.println("boardlist:" + boardlist);

24. In the service class and the DAO class, add the getCount() method.

BoardService.java

	public int getCount() {
		return dao.getCount();
	}

BoardDao.java

	public int getCount() {
		return session.selectOne("count");
	}

25. Add select SQL in the board.xml.

26. Edit the index.jsp. 

location.href="boardlist.do";

27. In the BoardController.java, add the code showing the post list. 

28. In the Service class and the DAO class, ass the List part. 

BoardService.java

	public List<Board> getBoardList(int page) {
		return dao.getBoardList(page);
	}

BoardDao.java

	public List<Board> getBoardList(int page) {
		return session.selectList("list", page);
	}

29. Add the list id in the board.xml.

 You can use &gt; / &lt; means "greater than"/ "less than" in xml files which has the same role as the <![CDATA[]]>.

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

30. Add the codes in the Controller class for the start and end pages.

// Total page
			int pageCount = listcount / limit + ((listcount%limit == 0)? 0 : 1);
			
			int startPage = ((page - 1) / 10) * limit + 1; //1, 11, 21,..
			int endPage = startPage + 10 - 1;			  //10, 20, 30..
			
			if(endPage > pageCount) endPage = pageCount;
			
			model.addAttribute("page", page);
			model.addAttribute("listcount", listcount);
			model.addAttribute("boardlist", boardlist);
			model.addAttribute("startPage", startPage);
			model.addAttribute("endPage", endPage);
			
			
			return "board/boardlist";
		}

31. To demonstrate, insert the data on Oracle. 

insert into myboard values(myboard_seq.nextval, 'Meadow', '111', 'Spring & MyBatis', 'Bulletin Board Project',0,sysdate);

 

Continue in the next post.

+ Recent posts