서블릿 매핑 정보
web.xml <!-- 성적처리 Servlet 게시판 --> <servlet> <servlet-name>scoreServlet</servlet-name> <servlet-class>com.score.ScoreServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>scoreServlet</servlet-name> <url-pattern>/sung/*</url-pattern> </servlet-mapping> |
리스트 조회 페이지(list.jsp)
list.jsp <%@page import="com.score.ScoreDTO"%> <%@page import="java.util.List"%> <%@page import="com.score.ScoreDAO"%> <%@page import="com.util.DBConn"%> <%@page import="java.sql.Connection"%> <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% request.setCharacterEncoding("UTF-8"); String cp = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>성적처리 리스트</title> <style type="text/css"> *{ padding:0px; margin:0px; } body { font-size : 10pt; } td { font-size : 10pt; } .btn{ font-size : 10pt; background: #e6e6e6; } </style> <script type="text/javascript"> function sendIt(){ var f = document.searchForm; f.action = "<%=cp %>/sung/list.do${params }"; f.submit(); } </script> </head> <body> <br><br> <table width="700" cellpadding="0" cellspacing="3" align="center" bgcolor="#e4e4e4"> <tr height="50"> <td bgcolor="#ffffff" style="padding-left: 10px;'"> <b>성적처리 리스트 화면</b> </td> </tr> </table> <br> <table width="650" cellpadding="0" cellspacing="3" align="center"> <tr height="35"> <td> <form action="" name="searchForm" method="post"> <select name="searchKey" class="selectField"> <option value="hak">학번</option> <option value="name">이름</option> </select> <input type="text" name="searchValue" value="${searchValue }" class="textField"/> <input type="button" value=" 검 색 " class="btn2" onclick="sendIt()"/> </form> </td> <td align="right"> <input type="button" class="btn" value="성적입력" onclick="javascript:location.href='<%=cp %>/sung/write.do';"> </td> </tr> </table> <table width="650" cellpadding="0" cellspacing="1" align="center" bgcolor="#cccccc"> <tr height="30"> <td align="center" bgcolor="#e6e6e6" width="80">학번</td> <td align="center" bgcolor="#e6e6e6" width="80">이름</td> <td align="center" bgcolor="#e6e6e6" width="60">국어</td> <td align="center" bgcolor="#e6e6e6" width="60">영어</td> <td align="center" bgcolor="#e6e6e6" width="60">수학</td> <td align="center" bgcolor="#e6e6e6" width="60">총점</td> <td align="center" bgcolor="#e6e6e6" width="60">평균</td> <td align="center" bgcolor="#e6e6e6" width="60">석차</td> <td align="center" bgcolor="#e6e6e6" width="130">수정</td> </tr> <c:forEach var="dto" items="${lists }"> <tr height="30"> <td align="center" bgcolor="#ffffff">${dto.hak }</td> <td align="center" bgcolor="#ffffff">${dto.name }</td> <td align="center" bgcolor="#ffffff">${dto.kor }</td> <td align="center" bgcolor="#ffffff">${dto.eng }</td> <td align="center" bgcolor="#ffffff">${dto.mat }</td> <td align="center" bgcolor="#ffffff">${dto.tot }</td> <td align="center" bgcolor="#ffffff">${dto.ave }</td> <td align="center" bgcolor="#ffffff">${dto.rank }</td> <td align="center" bgcolor="#ffffff">
<a href="update.do?hak=${dto.hak }&pageNum=${pageNum}${params}">수정</a> <a href="delete_ok.do?hak=${dto.hak }&pageNum=${pageNum}${params}">삭제</a></td>
</tr> </c:forEach> <tr> <td align="center" colspan="11" bgcolor="#e4e4e4"> <input type="hidden" value="${params }" name="params"> <c:if test="${dataCount!=0 }"> ${pageIndexList } </c:if> <c:if test="${dataCount==0 }"> 등록된 성적이 없습니다 </c:if> </td> </tr> </table> </body> </html> |
성적처리 수정 페이지(update.jsp)
update.jsp <%@page import="com.score.ScoreDTO"%> <%@page import="com.score.ScoreDAO"%> <%@page import="com.util.DBConn"%> <%@page import="java.sql.Connection"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html; charset=UTF-8"%> <% request.setCharacterEncoding("UTF-8"); String cp = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>성적처리 수정</title> <script type="text/javascript"> function sendIt(){
var f = document.myForm; f.action ="<%=cp %>/sung/update_ok.do"; f.submit(); } </script> <style type="text/css"> *{ padding:0px; margin:0px; } body { font-size : 10pt; } td { font-size : 10pt; } .txtField{ font-size : 10pt; border: 1px solid; } .btn{ font-size : 10pt; background: #e6e6e6; } </style> </head> <body> <br/><br/> <table width="500" cellpadding="0" cellspacing="3" align="center" bgcolor="#e4e4e4"> <tr height="50"> <td bgcolor="#ffffff" style="padding-left:10px;"> <b>성적처리 수정화면</b> </td> </tr> </table> <br/> <form action="" method="post" name="myForm"> <table width="500" cellpadding="0" cellspacing="0" align="center"> <tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">학번</td> <td style="padding-left: 5px;"> ${dto.hak } <input type="hidden" value="${dto.hak }" name="hak"> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">이름</td> <td style="padding-left: 5px;"> ${dto.name } <input type="hidden" value="${dto.name }" name="name"> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">국어</td> <td style="padding-left: 5px;"> <input type="text" name="kor" value="${dto.kor }"size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">영어</td> <td style="padding-left: 5px;"> <input type="text" name="eng" value="${dto.eng }"size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">수학</td> <td style="padding-left: 5px;"> <input type="text" name="mat" value="${dto.mat }" size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="35" > <td align="center" colspan="2"> <input type="button" class="btn" value="수정완료" onclick="sendIt()"/> <input type="button" class="btn" value="수정취소" onclick="javascript:location.href='<%=cp %>/sung/list.do?pageNum=${pageNum }';"> </td> </tr> </table> </form> </body> </html> |
성적처리 입력 페이지(write.jsp)
write.jsp <%@ page contentType="text/html; charset=UTF-8"%> <% request.setCharacterEncoding("UTF-8"); String cp = request.getContextPath();//특정 폴더를 쉽게 지칭하기 위한 시스템변수 개념으로 사용 //Context가 나오면 프로젝트안에서 전체적으로 모두 사용할 수 있음 //http://192.168.16.16:8080/study %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>성적처리 입력화면</title> <script type="text/javascript"> function sendIt(){ var f = document.myForm; //f.action ="http://ip/study/score/write_ok.jsp"; //여기서의 study는D:\java\work\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\study\org\apache\jsp f.action ="<%=cp %>/sung/write_ok.do"; f.submit(); } </script> <style type="text/css"> *{ padding:0px; margin:0px; } body { font-size : 10pt; } td { font-size : 10pt; } .txtField{ font-size : 10pt; border: 1px solid; } .btn{ font-size : 10pt; background: #e6e6e6; } </style> </head> <body> <br/><br/> <table width="500" cellpadding="0" cellspacing="3" align="center" bgcolor="#e4e4e4"> <tr height="50"> <td bgcolor="#ffffff" style="padding-left:10px;"> <b>성적처리 입력화면</b> </td> </tr> </table> <br/> <form action="" method="post" name="myForm"> <table width="500" cellpadding="0" cellspacing="0" align="center"> <tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">학번</td> <td style="padding-left: 5px;"> <input type="text" name="hak" size="10" maxlength="7" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">이름</td> <td style="padding-left: 5px;"> <input type="text" name="name" size="20" maxlength="10" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">국어</td> <td style="padding-left: 5px;"> <input type="text" name="kor" size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">영어</td> <td style="padding-left: 5px;"> <input type="text" name="eng" size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="1"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="30"> <td align="center" width="100" bgcolor="#e6e6e6">수학</td> <td style="padding-left: 5px;"> <input type="text" name="mat" size="20" maxlength="3" class="txtField"/> </td> </tr> <tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr> <tr height="35" > <td align="center" colspan="2"> <input type="button" class="btn" value="입력완료" onclick="sendIt()"/> <input type="reset" class="btn" value="다시입력" onclick="document.myForm.hak.focus();"> <input type="button" class="btn" value="입력취소" onclick="javascript:location.href='<%=cp %>/sung/list.do?pageNum=${pageNum }';"> </td> </tr> </table> </form> </body> </html> |
서블릿 클래스 생성(ScoreServlet.java)
ScoreServlet.java public class ScoreServlet extends HttpServlet { private static final long serialVersionUID = 1L;
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }
protected void forward(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException { //forward RequestDispatcher rd = req.getRequestDispatcher(url); rd.forward(req, resp); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8"); String cp = req.getContextPath();
//DB연결 Connection conn = DBCPConn.getConnection(); ScoreDAO dao = new ScoreDAO(conn);
//페이징 MyUtil myUtil = new MyUtil();
// 뒷부분의 주소를 읽어옴 String uri = req.getRequestURI(); String url;
if(uri.indexOf("write.do")!=-1){
url = "/sscore/write.jsp"; forward(req, resp, url);
}else if(uri.indexOf("write_ok.do")!=-1){
ScoreDTO dto = new ScoreDTO(); dto.setName(req.getParameter("name")); dto.setHak(req.getParameter("hak")); dto.setKor(Integer.parseInt(req.getParameter("kor"))); dto.setEng(Integer.parseInt(req.getParameter("eng"))); dto.setMat(Integer.parseInt(req.getParameter("mat")));
dao.insertData(dto);
//redirect url = cp + "/sung/list.do"; resp.sendRedirect(url);
}else if(uri.indexOf("list.do")!=-1){
String pageNum = req.getParameter("pageNum"); int currentPage = 1; //처음 띄우는 리스트 페이지
if(pageNum!=null){ currentPage = Integer.parseInt(pageNum); }else{ pageNum = "1"; }
String searchKey = req.getParameter("searchKey"); String searchValue = req.getParameter("searchValue");
if(searchValue==null || searchValue.equals(null)){ searchKey ="hak"; searchValue = ""; }else{
if(req.getMethod().equalsIgnoreCase("GET")){ searchValue = URLDecoder.decode(searchValue, "UTF-8"); } }
int dataCount = dao.getDataCount(searchKey, searchValue); int numPerPage = 5; int totalPage = myUtil.getPageCount(numPerPage, dataCount);
if(currentPage>totalPage) currentPage = totalPage;
int start = (currentPage-1)*numPerPage+1; int end = currentPage*numPerPage;
List<ScoreDTO> lists = dao.getList(start, end, searchKey, searchValue);
String param = "";
if(!searchValue.equals("")){
param = "searchKey=" + searchKey; param += "&searchValue=" + URLEncoder.encode(searchValue,"UTF-8"); }
String listUrl = cp+"/sung/list.do";
if(!param.equals("")){ listUrl +="&" + param; }
String pageIndexList = myUtil.pageIndexList(currentPage, totalPage, listUrl);
//포워딩할 데이터 req.setAttribute("lists", lists); req.setAttribute("pageIndexList", pageIndexList); req.setAttribute("dataCount", dataCount); req.setAttribute("pageNum", pageNum);
url = "/sscore/list.jsp"; forward(req, resp, url);
}else if(uri.indexOf("update.do")!=-1){
String hak = req.getParameter("hak"); String pageNum = req.getParameter("pageNum"); String searchKey = req.getParameter("searchKey"); String searchValue = req.getParameter("searchValue");
if(searchValue!=null){ searchValue =URLDecoder.decode(searchValue, "UTF-8"); }
ScoreDTO dto = dao.getReadData(hak);
if(dto==null){ url = cp + "/sung/list.do"; resp.sendRedirect(url); }
String param = "pageNum="+pageNum;
if(searchValue!=null){ param += "&searchKey=" + searchKey; param += "&searchValue=" + URLEncoder.encode(searchValue,"UTF-8"); }
req.setAttribute("dto", dto); req.setAttribute("pageNum", pageNum); req.setAttribute("params", param); url = "/sscore/update.jsp"; forward(req, resp, url);
}else if(uri.indexOf("update_ok.do")!=-1){
String params = req.getParameter("params"); ScoreDTO dto = new ScoreDTO(); dto.setName(req.getParameter("name")); dto.setHak(req.getParameter("hak")); dto.setKor(Integer.parseInt(req.getParameter("kor"))); dto.setEng(Integer.parseInt(req.getParameter("eng"))); dto.setMat(Integer.parseInt(req.getParameter("mat")));
dao.updateData(dto);
url = cp + "/sung/list.do?"+params; resp.sendRedirect(url);
}else if(uri.indexOf("delete_ok.do")!=-1){ String hak = req.getParameter("hak"); String pageNum = req.getParameter("pageNum"); String searchKey = req.getParameter("searchKey"); String searchValue = req.getParameter("searchValue"); if(searchValue!=null){ searchValue = URLDecoder.decode(searchValue, "UTF-8"); }
String param = "pageNum="+pageNum;
if(searchValue!=null){ param += "&searchKey=" + searchKey; param += "&searchValue=" + URLEncoder.encode(searchValue,"UTF-8"); } dao.deleteData(hak);
url = cp + "/sung/list.do?"+param; resp.sendRedirect(url); } } } |
DTO 클래스 생성(ScoreDTO.java)
public class ScoreDTO {
//입력받는 값 private String hak; private String name; private int kor; private int eng; private int mat;
//입력값을 이용해 연산하는 값 private int tot; private int ave; private int rank;
getter,setter 작성 } |
DAO 클래스 생성(ScoreDAO.java)
public class ScoreDAO { private Connection conn; //의존성주입 //구성요소간의 종속성을 소스코드에서 설정하지 않고 외부의 설정파일 등을 통해 주입하도록 하는 디자인 패턴 public ScoreDAO(Connection conn){ this.conn = conn; }
//성적입력 public int insertData(ScoreDTO dto){ int result = 0; PreparedStatement pstmt = null; String sql = ""; try { sql = "insert into score (hak,name,kor,eng,mat) "; sql += "values (?,?,?,?,?) ";
pstmt = conn.prepareStatement(sql); pstmt.setString(1, dto.getHak()); pstmt.setString(2, dto.getName()); pstmt.setInt(3, dto.getKor()); pstmt.setInt(4, dto.getEng()); pstmt.setInt(5, dto.getMat()); result = pstmt.executeUpdate(); pstmt.close();
} catch (Exception e) { System.out.println(e.toString()); } return result; }
//전체조회 public List<ScoreDTO> getList(int start, int end, String searchKey, String searchValue){
List<ScoreDTO> lists = new ArrayList<ScoreDTO>(); PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { searchValue = "%" + searchValue + "%"; sql = "select * from ("; sql += "select rownum rnum, hak, name, kor, eng, mat, "; sql += "(kor+eng+mat) tot, (kor+eng+mat)/3 ave, "; sql += "rank() over(order by (kor+eng+mat) desc) rank "; sql += "from score where " +searchKey+ " like ? )"; sql += "where rnum >= ? and rnum <=? ";
pstmt = conn.prepareStatement(sql); pstmt.setString(1, searchValue); pstmt.setInt(2, start); pstmt.setInt(3, end); rs = pstmt.executeQuery();
while(rs.next()){ ScoreDTO dto = new ScoreDTO(); dto.setHak(rs.getString("hak")); dto.setName(rs.getString("name")); dto.setKor(rs.getInt("kor")); dto.setEng(rs.getInt("eng")); dto.setMat(rs.getInt("mat")); dto.setTot(rs.getInt("tot")); dto.setAve(rs.getInt("ave")); dto.setRank(rs.getInt("rank")); lists.add(dto); } pstmt.close(); rs.close(); } catch (Exception e) { System.out.println(e.toString()); } return lists; } //학번조회 public ScoreDTO getReadData(String hak){
ScoreDTO dto = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql;
try { sql = "select hak, name, kor, eng, mat from score where hak=? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, hak); rs = pstmt.executeQuery();
if(rs.next()){ dto = new ScoreDTO(); dto.setHak(rs.getString("hak")); dto.setName(rs.getString("name")); dto.setKor(rs.getInt("kor")); dto.setEng(rs.getInt("eng")); dto.setMat(rs.getInt("mat")); } rs.close(); pstmt.close();
} catch (Exception e) { System.out.println(e.toString()); } return dto; } //성적수정 public int updateData(ScoreDTO dto){
int result = 0; PreparedStatement pstmt=null; String sql; try {
sql = "update score set kor=?, eng=?, mat=? "; sql += "where hak=?"; pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, dto.getKor()); pstmt.setInt(2, dto.getEng()); pstmt.setInt(3, dto.getMat()); pstmt.setString(4, dto.getHak());
result = pstmt.executeUpdate(); pstmt.close();
} catch (Exception e) { System.out.println(e.toString()); } return result;
} //성적삭제 public int deleteData(String hak){
int result = 0; PreparedStatement pstmt = null; String sql; try { sql = "delete score where hak=? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, hak); result = pstmt.executeUpdate(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } } |
'Dev > JSP & Servlet' 카테고리의 다른 글
쿠키의 개요, 생성, 전달, 삭제 (0) | 2019.02.28 |
---|---|
Servlet - 회원가입,로그인 페이지 만들기 (0) | 2019.02.27 |
Servlet - 게시판 만들기 (0) | 2019.02.26 |
Servlet - 서블릿 구조, EL, JSTL, DBCP (0) | 2019.02.25 |
JSP 게시판(3) - JSP 페이지 (0) | 2019.02.25 |