JSP paging

select count(*) from mem_jsp에서 몇개인지 알려면, rs.getInt("COUNT(*)")로 얻어온다.

<%@ 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>
	<%@ include file="/common/header.jsp" %>
	<jsp:useBean id="dao" class="member.MemberDAO" />
	<h3>모든 목록 확인</h3>
	<table border="1">
		<tr>
			<th>이름</th>
			<th>주소</th>
			<th>전화번호</th>
		</tr>
		<c:set var="rsMap" value="${dao.getList(param.page)}"></c:set>
		<c:forEach var="dto" items="${rsMap.get('list') }">
		<tr>
			<td>
				<c:choose>
					<c:when test="${loginId ne null }">
						<c:set var="result" value="/m_info.jsp?id=${dto.id}"></c:set>
					</c:when>
					<c:otherwise>
						<c:set var="result" value="/m_login.jsp"></c:set>
					</c:otherwise>
				</c:choose>
				<a href="${path}member${result}">${dto.name}</a>
			</td>
			<td>${dto.addr}</td>
			<td>${dto.tel}</td>
		</tr>
		</c:forEach>
		<tr>
			<td align="center" colspan="3">
				<c:forEach var="cnt" begin="1" end="${rsMap.get('endPage')}">
					<a href="m_list.jsp?page=${cnt}">${cnt}</a>
				</c:forEach>
			</td>
		</tr>
	</table>
</body>
</html>
package member;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

public class MemberDAO {
	String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	String user="c##LTY", pwd="1213";
	Connection con;
	PreparedStatement ps;
	ResultSet rs;
	
	public MemberDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("--드라이브 로드 성공--");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public MemberDTO getOneMember(String id) {
		MemberDTO dto = null;
		String sql = "select * from mem_jsp where id=?";
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			ps.setString(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				dto = new MemberDTO();
				dto.setId(rs.getString("id"));
				dto.setPwd(rs.getString("pwd"));
				dto.setName(rs.getString("name"));
				dto.setAddr(rs.getString("addr"));
				dto.setTel(rs.getString("tel"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return dto;
	}
	private int getTotalCount() {
		String sql = "select count(*) from mem_jsp";
		int tCnt = 0;
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				tCnt = rs.getInt("COUNT(*)");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tCnt;
	}
	private HashMap<String, Object> getOperation(int page, int tCnt){
		HashMap<String, Object> rsMap = new HashMap<>();
		if (page == 0) {
			page = 1;
		}
		int pageNum = 2; //한 페이지당 글 개수
		int endPage = tCnt / pageNum + (tCnt % pageNum == 0 ? 0 : 1); //총 페이지 개수
		int startNum = (page -  1) * pageNum + 1; //페이지당 처음 글 번호
		int endNum = pageNum * page; //페이지당 마지막 글 번호
		
		rsMap.put("endPage", endPage);
		rsMap.put("startNum", startNum);
		rsMap.put("endNum", endNum);
		return rsMap;
	}
	public HashMap<String, Object> getList(int page){
		System.out.println("page : " + page);
		int tCnt = getTotalCount();
		System.out.println("tCnt : " + tCnt);
		
		HashMap<String, Object> rsMap = getOperation(page, tCnt);
		
		String sql = "select A.* from"
				+"(select rownum rn,id,pwd,name,addr,tel from mem_jsp)"
				+"A where rn between ? and ?";
		//String sql = "select * from mem_jsp";
		MemberDTO dto = null;
		ArrayList<MemberDTO> list = new ArrayList<>();
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			ps.setInt(1, (int)rsMap.get("startNum"));
			ps.setInt(2, (int)rsMap.get("endNum"));
			rs = ps.executeQuery();
			while(rs.next()) {
				dto = new MemberDTO();
				dto.setId(rs.getString("id"));
				dto.setPwd(rs.getString("pwd"));
				dto.setName(rs.getString("name"));
				dto.setAddr(rs.getString("addr"));
				dto.setTel(rs.getString("tel"));
				list.add(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(ps != null) ps.close();
				if(con != null) con.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		rsMap.put("list", list);
		return rsMap;
	}
	public int register(MemberDTO dto) {
		int result = 0;
		String sql = "insert into mem_jsp(id, pwd, name, addr, tel) values(?,?,?,?,?)";
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			ps.setString(1, dto.getId());
			ps.setString(2, dto.getPwd());
			ps.setString(3, dto.getName());
			ps.setString(4, dto.getAddr());
			ps.setString(5, dto.getTel());
			
			result = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public int modify(MemberDTO dto) {
		int result = 0;
		String sql = "update mem_jsp set pwd=?, name=?, addr=?, tel=? where id=?";
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			ps.setString(1, dto.getPwd());
			ps.setString(2, dto.getName());
			ps.setString(3, dto.getAddr());
			ps.setString(4, dto.getTel());
			ps.setString(5, dto.getId());
			result = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public int delete(String id) {
		int result = 0;
		String sql = "delete from mem_jsp where id=?";
		try {
			con = DriverManager.getConnection(url, user, pwd);
			ps = con.prepareStatement(sql);
			ps.setString(1, id);
			result = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

JSP file upload & download

https://www.servlets.com/  -  COS File Upload Library  -  cos-22.05.zip(아래쪽)다운 - 압출 cos.jar 옮기기

enctype="multipart/form-data" : 파일이나 이미지를 전송할 때 주로 사용(post방식에서만 사용 가능)

pageContext.request : 클라이언트가 서버로 전송한 HTTP요청에 대한 정보(타입 = HttpServletRequest)

MultipartRequest mul = new ~~(); : cos.jar에서 제공해주는 라이브러리

new DefaultFileRenamePolicy() : 동일한 파일이 있을 경우, 파일명(1) 이런식으로 처리

Enumeration  e = mul.getFileNames() : 파일 목록들 (타입 = Enumeration<String>)

e.nextElement() : 파일 명 가져오기 

e.hasMoreElements() : 다음 값 확인(true or false)

mul.getFilesystemName( e.nextElement() ) : 실제 파일 명

mul.getOriginalFileName( e.nextElement() ) : 폴더에 저장될 파일 명

 

pageContext.response: (타입 = HttpServletResponse)

pageContext.response.addHeader("다운로드 방식(Content-Disposition)", "파일명 표시 ");

FileInputStream : 해당 파일에 대한 입력 스트림을 생성, 이후 read()로 읽어온다.(파일의 끝에 도달 = -1반환)

OutputStream : 출력스트림(InputStream)을 통해 얻어온 데이터를 out에 할당하여 클라이언트에게 전달

<%@ 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>
	<form action="upload.jsp" method="post" enctype="multipart/form-data">
		<input type="text" name="id" placeholder="id"><br>
		<input type="file" name="save_file"><br>
		<input type="submit" value="전송">
	</form>
	<a href="download_form.jsp">파일 확인</a>
</body>
</html>
<%@ 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>
	result : ${ pageContext.request }<br>
	result : <%= request %><br>
	
	<jsp:useBean id="file" class="file.FileOperation" />
	${ file.upload( pageContext.request) }
	<% response.sendRedirect("upload_form.jsp"); %>
</body>
</html>
<%@ 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>
	<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
	<jsp:useBean id="file" class="file.FileOperation" />
	<c:forEach var="item" items="${file.getFileList() }">
		<img alt="" src="download.jsp?img=${item}" width="100" height="100">
		<a href="download.jsp?img=${item}">${item}</a>
		<br>
	</c:forEach>
	<hr>
	<a href="upload_form.jsp">form이동</a>
</body>
</html>
<%@ 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>
	<%= response %>
	<jsp:useBean id="file" class="file.FileOperation" />
	${file.fileDown(param.img, pageContext.response) }
</body>
</html>
package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Enumeration;

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

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

public class FileOperation {
	public void upload(HttpServletRequest req) throws Exception {
		String path = "c:/jsp_file";
		int size = 1024 * 1024 * 200; //10MB
		System.out.println(req);
		MultipartRequest mul = new MultipartRequest(req, path, size, "UTF-8",
														new DefaultFileRenamePolicy());
		System.out.println("req : " + req.getParameter("id"));
		System.out.println("mul : " + mul.getParameter("id"));
		
		Enumeration<String> e = mul.getFileNames();
		System.out.println("e : " + e);
		System.out.println("다음 값 확인 : " + e.hasMoreElements());
		String fileName = e.nextElement(); //파일 명 가져오기
		System.out.println("파일 명(input name) : " + fileName);
		System.out.println("다음 값 확인 : " + e.hasMoreElements());
		
		String changeName = mul.getFilesystemName(fileName); //실제 파일 명
		String originName = mul.getOriginalFileName(fileName); //폴더에 저장될 파일 명
		
		System.out.println("실제 파일 명 : " + originName);
		System.out.println("변경 파일 명(저장용) : " + changeName);
	}
	public String[] getFileList() {
		File file = new File("c:/jsp_file");
		return file.list();
	}
	public void fileDown(String fileName, HttpServletResponse res) throws Exception {
		res.addHeader("Content-Disposition", "attachment;filename="+fileName);
		// 다운로드 방식 , 파일명을 저렇게 표기
		File file = new File("c:/jsp_file/"+fileName);
		FileInputStream in = new FileInputStream(file);
		OutputStream out = res.getOutputStream();
		byte b[] = new byte[1024];
		int data = 0;
		while(data != -1) {
			data = in.read(b);
			out.write(b);
		}
		out.close(); in.close();
	}
}

 

실행 결과

'jsp' 카테고리의 다른 글

JSP 활용(2)  (0) 2024.05.01
JSP 활용 (1)  (0) 2024.04.30
JSP 기초  (0) 2024.04.29

+ Recent posts