package board.mvc.vo;
import java.util.List;
import mvc.domain.Board;
public class ListResult {
private int currentPage;
private long totalCount;
private int pageSize;
private List<Board> list;
private long totalPageCount;
public ListResult() {}
public ListResult(int currentPage, long totalCount, int pageSize, List<Board> list) {
this.currentPage = currentPage;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.list = list;
this.totalPageCount = calTotalPageCount();
}
private long calTotalPageCount() {
long tpc = totalCount/pageSize;
if(totalCount%pageSize != 0) tpc++;
return tpc;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public long getTotalCount() {
return totalCount;
}
public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<Board> getList() {
return list;
}
public void setList(List<Board> list) {
this.list = list;
}
public long getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(long totalPageCount) {
this.totalPageCount = totalPageCount;
}
}
package board.mvc.model;
class BoardSQL {
static final String LIST = "select * from BOARD order by SEQ desc";
static final String INSERT
= "insert into BOARD values(BOARD_SEQ.nextval, ?, ?, ?, ?, SYSDATE)";
static final String DEL="delete from BOARD where SEQ=?";
static final String DEL_ALL="delete from BOARD";
static final String CONTENT = "select * from BOARD where SEQ=?";
static final String UPDATE
= "update BOARD set EMAIL=?, SUBJECT=?, CONTENT=?, RDATE=SYSDATE where SEQ=?";
static final String PAGE = "select * from (select ROWNUM rnum, aa.* from (select * from BOARD order by SEQ desc) aa) where rnum>? and rnum<=?";
static final String SELECT_COUNT = "select count(*) from BOARD";
}
package board.mvc.model;
import java.sql.*;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import mvc.domain.Board;
import static board.mvc.model.BoardSQL.*;
class BoardDAO {
private DataSource ds;
BoardDAO(){
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/myoracle");
}catch(NamingException ne) {
}
}
ArrayList<Board> list(){
ArrayList<Board> dtos = new ArrayList<Board>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql = LIST;
try {
con = ds.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
int seq = rs.getInt(1);
String writer = rs.getString(2);
String email = rs.getString(3);
String subject = rs.getString(4);
String content = rs.getString(5);
java.sql.Date rdate = rs.getDate(6);
dtos.add(new Board(seq, writer, email, subject, content, rdate));
}
}catch(SQLException se) {
System.out.println("list() se: " + se);
}finally {
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
return dtos;
}
ArrayList<Board> list(int currentPage, int pageSize){ // 추가해준 부분
ArrayList<Board> list = new ArrayList<Board>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = PAGE;
int startRow = (currentPage-1)*pageSize;
int endRow = currentPage*pageSize;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, startRow);
pstmt.setInt(2, endRow);
rs = pstmt.executeQuery();
while(rs.next()) {
int seq = rs.getInt("seq");
String writer = rs.getString("writer");
String email = rs.getString("email");
String subject = rs.getString("subject");
String content = rs.getString("content");
Date rdate = rs.getDate("rdate");
Board b = new Board(seq, writer, email, subject, content, rdate);
list.add(b);
}
return list;
}catch(SQLException se) {
System.out.println("SQLException : "+se);
return null;
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
}
long getTotalCount() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql = SELECT_COUNT;
try {
con = ds.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if(rs.next()) {
int count = rs.getInt(1);
return count;
}else {
return -1;
}
}catch(SQLException se) {
return -1;
}finally {
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
}
void insert(Board dto) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = INSERT;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, dto.getWriter());
pstmt.setString(2, dto.getEmail());
pstmt.setString(3, dto.getSubject());
pstmt.setString(4, dto.getContent());
pstmt.executeUpdate();
}catch(SQLException se) {
}finally {
try {
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
}
boolean del(int seq) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = DEL;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, seq);
int i = pstmt.executeUpdate();
if(i>0) return true;
else return false;
}catch(SQLException se) {
return false;
}finally {
try {
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
}
void delAll() {
Connection con = null;
Statement stmt = null;
String sql = DEL_ALL;
try {
con = ds.getConnection();
stmt = con.createStatement();
stmt.executeUpdate(sql);
}catch(SQLException se) {
}finally {
try {
if(stmt != null) stmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
}
Board content(int seq) {
String sql = CONTENT;
Board dto = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, seq);
rs = pstmt.executeQuery();
while(rs.next()) {
seq = rs.getInt(1);
String writer = rs.getString(2);
String email = rs.getString(3);
String subject = rs.getString(4);
String content = rs.getString(5);
java.sql.Date rdate = rs.getDate(6);
dto = new Board(seq, writer, email, subject, content, rdate);
}
}catch(SQLException se) {
System.out.println("list() se: " + se);
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(SQLException se) {}
}
return dto;
}
void update(Board dto) {
String sql = UPDATE;
Connection con = null;
PreparedStatement pstmt = null;
try{
con = ds.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, dto.getEmail());
pstmt.setString(2, dto.getSubject());
pstmt.setString(3, dto.getContent());
pstmt.setInt(4, dto.getSeq());
pstmt.executeUpdate();
}catch(NumberFormatException ne){
}catch(SQLException se){
}finally{
try{
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(SQLException sse) {
}
}
}
}
package board.mvc.model;
import java.util.ArrayList;
import board.mvc.vo.ListResult;
import mvc.domain.Board;
public class BoardService {
private BoardDAO dao;
private static final BoardService instance = new BoardService();
private BoardService() {
dao = new BoardDAO();
}
public static BoardService getInstance() {
return instance;
}
public ListResult getListResult(int currentPage, int pageSize) {
ArrayList<Board> list = dao.list(currentPage, pageSize);
long totalCount = dao.getTotalCount();
return new ListResult(currentPage, totalCount, pageSize, list);
}
public ArrayList<Board> listS(){
return dao.list();
}
public void insertS(Board dto) {
dao.insert(dto);
}
public boolean delS(int seq) {
return dao.del(seq);
}
public void delAllS() {
dao.delAll();
}
public Board contentS(int seq) {
return dao.content(seq);
}
public void updateS(Board dto) {
dao.update(dto);
}
}
package board.mvc.control;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import board.mvc.model.BoardService;
import board.mvc.vo.ListResult;
import mvc.domain.Board;
@WebServlet("/board/board.do")
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String m = request.getParameter("m");
if(m != null) {
m = m.trim();
if(m.equals("list")) {
list(request, response);
}else if(m.equals("input")) {
input(request, response);
}else if(m.equals("insert")) {
insert(request, response);
}else if(m.equals("del")) {
del(request, response);
}else if(m.equals("del_all")) {
del_all(request, response);
}else if(m.equals("content")) {
content(request, response);
}else if(m.equals("update")) {
update(request, response);
}else if(m.equals("updateok")) {
updateok(request, response);
}else {
list(request, response);
}
}else {
list(request, response);
}
}
private void list(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cpStr = request.getParameter("cp");
String psStr = request.getParameter("ps");
HttpSession session = request.getSession();
//(1) cp
int cp = 1;
if(cpStr == null) {
Object cpObj = session.getAttribute("cp");
if(cpObj != null) {
cp = (Integer)cpObj;
}
}else {
cpStr = cpStr.trim();
cp = Integer.parseInt(cpStr);
}
session.setAttribute("cp", cp);
//(2) ps
int ps = 3;
if(psStr == null) {
Object psObj = session.getAttribute("ps");
if(psObj != null) {
ps = (Integer)psObj;
}
}else {
psStr = psStr.trim();
int psParam = Integer.parseInt(psStr);
Object psObj = session.getAttribute("ps");
if(psObj != null) {
int psSession = (Integer)psObj;
if(psSession != psParam) {
cp = 1;
session.setAttribute("cp", cp);
}
}else {
if(ps != psParam) {
cp = 1;
session.setAttribute("cp", cp);
}
}
ps = psParam;
}
session.setAttribute("ps", ps);
BoardService service = BoardService.getInstance();
ListResult listResult = service.getListResult(cp, ps);
request.setAttribute("listResult", listResult);
if(listResult.getList().size() == 0 && cp>1) {
response.sendRedirect("board.do?m=list&cp="+(cp-1));
}else {
String view = "list.jsp";
RequestDispatcher rd = request.getRequestDispatcher(view);
rd.forward(request, response);
}
}
private void input(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String view = "input.jsp";
response.sendRedirect(view);
}
private void insert(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String writer = request.getParameter("writer");
String email = request.getParameter("email");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
Board dto = new Board(-1, writer, email, subject, content, null);
BoardService service = BoardService.getInstance();
service.insertS(dto);
String view = "board.do";
response.sendRedirect(view);
}
private void del(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String seqStr = request.getParameter("seq");
int seq = -1;
if(seqStr != null) {
seqStr = seqStr.trim();
try {
seq = Integer.parseInt(seqStr);
BoardService service = BoardService.getInstance();
boolean flag = service.delS(seq);
request.setAttribute("flag", flag);
}catch(NumberFormatException ne) {}
}
String view = "del.jsp";
RequestDispatcher rd = request.getRequestDispatcher(view);
rd.forward(request, response);
}
private void del_all(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BoardService service = BoardService.getInstance();
service.delAllS();
String view = "board.do";
response.sendRedirect(view);
}
private void content(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int seq = -1;
String seqStr = request.getParameter("seq");
if(seqStr != null){
seqStr = seqStr.trim();
if(seqStr.length() != 0){
try{
seq = Integer.parseInt(seqStr);
BoardService service = BoardService.getInstance();
Board dto = service.contentS(seq);
request.setAttribute("dto", dto);
}catch(NumberFormatException ne){
}
}
}
String view = "content.jsp";
RequestDispatcher rd = request.getRequestDispatcher(view);
rd.forward(request, response);
}
private void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int seq = -1;
String seqStr = request.getParameter("seq");
if(seqStr != null){
seqStr = seqStr.trim();
if(seqStr.length() != 0){
try{
seq = Integer.parseInt(seqStr);
BoardService service = BoardService.getInstance();
Board dto = service.contentS(seq);
request.setAttribute("dto", dto);
}catch(NumberFormatException ne){
}
}
}
String view = "update.jsp";
RequestDispatcher rd = request.getRequestDispatcher(view);
rd.forward(request, response);
}
private void updateok(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String seqStr = request.getParameter("seq");
int seq = -1;
if(seqStr != null){
seqStr = seqStr.trim();
if(seqStr.length() != 0){
try{
seq = Integer.parseInt(seqStr);
BoardService service = BoardService.getInstance();
}catch(NumberFormatException ne){
}
}
}
String writer = request.getParameter("writer");
String email = request.getParameter("email");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
Board dto = new Board(seq, writer, email, subject, content, null);
BoardService service = BoardService.getInstance();
service.updateS(dto);
String view = "board.do";
response.sendRedirect(view);
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
import="java.util.*, mvc.domain.Board, board.mvc.vo.ListResult"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<meta charset='utf-8'>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
a { text-decoration:none }
</style>
<body style="text-align:center;">
<hr style='width:600px;'>
<h1>
Board with JSTL + EL
</h1>
<a href='../'>인덱스</a>
<a href='board.do?m=input'>글쓰기</a>
<a href='board.do?m=del_all'>모두 삭제</a>
<hr style='width:600px;'>
<div style='width:600px;margin:0 auto;text-align:center;'>
<table style='width:100%;'>
<tr>
<th>번호</th>
<th>이름</th>
<th>이메일</th>
<th>제목</th>
<th>날짜</th>
</tr>
<c:if test="${empty listResult.list}">
<tr>
<td style="text-align:center;" colspan='5'>데이터 없음</td>
</tr>
</c:if>
<c:forEach items="${listResult.list}" var="board">
<tr>
<td style="text-align:center;">${board.seq}</td>
<td>${board.writer}</td>
<td>${board.email}</td>
<td><a href='board.do?m=content&seq=${board.seq}'>${board.subject}</a></td>
<td style="text-align:center;">${board.rdate}</td>
</tr>
</c:forEach>
</table>
</div>
<hr style="width:600px;">
<div>
(총 페이지 수 : ${listResult.totalPageCount})
<c:forEach begin="1" end="${listResult.totalPageCount}" var="i">
<a href="board.do?m=list&cp=${i}&ps=${ps}">
<c:choose>
<c:when test="${i==listResult.currentPage}">
<strong>${i}</strong>
</c:when>
<c:otherwise>
${i}
</c:otherwise>
</c:choose>
</a>
</c:forEach>
(TOTAL : ${listResult.totalCount})
Page Size :
<select id="psId" name="ps" onchange="f(this)">
<c:choose>
<c:when test="${listResult.pageSize == 3}">
<option value="3" selected>3</option>
<option value="5">5</option>
<option value="10">10</option>
</c:when>
<c:when test="${listResult.pageSize == 5}">
<option value="3">3</option>
<option value="5" selected>5</option>
<option value="10">10</option>
</c:when>
<c:otherwise>
<option value="3">3</option>
<option value="5">5</option>
<option value="10" selected>10</option>
</c:otherwise>
</c:choose>
</select>
<script type="text/javascript">
window.onload = function(){
var getCookie = function(name) {
var value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return value? value[2] : null;
};
}
function f(select){
var ps = select.value;
console.log("ps :"+ps); <%-- 기능 : 웹페이지 콘솔창에 찍힘 (크롬 개발자 도구 : f12 )--%>
location.href="board.do?m=list&cp=1&ps="+ps;
}
</script>
</div>
<hr style="width:600px;">
자바서버 페이지 표준 태그 라이브러리은 Java EE 기반의 웹 애플리케이션 개발 플랫폼을 위한 컴포넌트 모음이다. JSTL은 XML 데이터 처리와 조건문, 반복문, 국제화와 지역화와 같은 일을 처리하기 위한 JSP 태그 라이브러리를 추가하여 JSP 사양을 확장했다.
WebContent\WEB-INF\lib
에 넣어준다.<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
EL은 Expression language의 약자로 JSP 2.0 스펙에 추가된 개념이다. 원래는 JSTL 1.0 규약에 소개된 내용으로 자바 코드를 대신해 실행 시간에 태그의 속성 값을 지정하는 역할을 했었다.
[1] 산술 연산자
ex) +, -, * , / 와 div, %와 mod
cf1)/와 div사용시 0으로 나눌 수 있다(infinity)
cf2)%와 mod사용시 0으로 나눌 수 없다.(오류)
[2] 논리 연산자
ex) &&와 and, ||와 or, !와 not
[3] 관계 연산자
ex) ==와 eq, !=과 ne, <와 lt, >와 gt,
<=와 le, >=와 ge
[4] empty
-> 비어있거나 null 일 경우 true 리턴
cf1) jsp의 변수(멤버/지역)는 EL에서 인식하지 못함
cf2) 정의되지 않은 변수/값(null)일 경우 표현처리
case1) 공백 처리 (ex: ${str} )
case2) 0 으로 처리 (ex: ${str + 10})
case3) false 로 처리 (ex: ${true and str})
Project/Clean
눌러주고 서버 재기동 해주면 잘 된다.