2021.01.05 일지

0후·2021년 1월 5일
0

비트캠프

목록 보기
55/112

Paging + EL

  1. VO(Value Object)를 만들어서 ListResult.java를 만들어준다. 여기서 VO로 만들어주는 이유는 값 타입을 표현하기 위해 불변 클래스를 만들어 사용하는 것이다.
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;
	}
}
  1. BoardSQL문 변경, PAGE와 SELECT_COUNT 추가
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";
}
  1. DAO 변경, 페이징을 위한 list(오버로딩) 추가
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) {
		     }
		}
	}
}
  1. Service 변경, 여러개의 DAO를 동시에 사용할 수 있다. DAO가 여러 개 출력됐으므로 service가 더 큰 개념이라고 생각하면 된다.
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);
	}
}
  1. Controller 변경, View의 URL에서 cp라는 이름과 ps라는 이름으로 값이 넘어온다.
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);
    }
}
  1. list.jsp 수정
<%@ 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>
&nbsp;&nbsp;&nbsp;
<a href='board.do?m=input'>글쓰기</a>
&nbsp;&nbsp;&nbsp;
<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})
	&nbsp;&nbsp;&nbsp;
	<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>&nbsp;
	</c:forEach>
	(TOTAL : ${listResult.totalCount})
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	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;">

JSTL

JSTL이란?

자바서버 페이지 표준 태그 라이브러리은 Java EE 기반의 웹 애플리케이션 개발 플랫폼을 위한 컴포넌트 모음이다. JSTL은 XML 데이터 처리와 조건문, 반복문, 국제화와 지역화와 같은 일을 처리하기 위한 JSP 태그 라이브러리를 추가하여 JSP 사양을 확장했다.

사용방법?

  1. 사이트에서 jakarta-taglibs-standard-1.1.2.zip를 다운받는다.
  2. 압축 해제 후 lib 폴더의 두 개의 jar 파일을 이클립스 WebContent\WEB-INF\lib에 넣어준다.
  3. jsp 파일에서 사용할 때 최상단에 하단 문장을 넣어주고 사용하면 된다.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

EL

EL이란?

EL은 Expression language의 약자로 JSP 2.0 스펙에 추가된 개념이다. 원래는 JSTL 1.0 규약에 소개된 내용으로 자바 코드를 대신해 실행 시간에 태그의 속성 값을 지정하는 역할을 했었다.

EL의 기능은?

  1. 객체의 속성값을 얻어온다.
  2. 배열의 값을 얻어온다.
  3. List 값을 얻어온다.
  4. Map 값을 얻어온다.

EL의 내장객체 11개

  1. param
  2. paramValues
  3. header
  4. headerValues
  5. pageContext - EL에서 JSP디폴트객체 접근시 사용
  6. requestScope
  7. pageScope
  8. sessionScope
  9. applicationScope
  10. cookie
  11. initParam - ServletContext에 대한 initParam

EL 연산자

[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})

잘되던 톰캣이 갑자기 안될 때

  • eclipse에서 Project/Clean 눌러주고 서버 재기동 해주면 잘 된다.
profile
휘발방지

0개의 댓글