Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

parisangsoo

JSP 03/16 (성적관리 홈페이지) 본문

JSP

JSP 03/16 (성적관리 홈페이지)

SangssI 2023. 3. 19. 18:51

DB와 JSP 연결 및 파라미터 요청 및 응답

Ex) 학생 성적에 관한 간단한 웹 홈페이지 제작

학생의 성적을 추가,삭제,업데이트 등의 기능 구현

1. 학생성적을 조회하고 DB를 연결하는 메인 JSP (DB 에서의 SELECT)

<%@page import="vo.SungjuckVO"%>
<%@page import="dao.SungjuckDAO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    
    <%
    //성적정보 가져오기 //DB 연결
    List<SungjuckVO> sungjuck_list = SungjuckDAO.getInstance().selectList();
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	<script>
		function del ( no ){ // no의 값을 파라미터로 받아 삭제하는 함수
			
			
			if (!confirm("정말 삭제하시겠어요?") ) {
				return;	
			}
			location.href="Sungjuck_del.jsp?no=" + no; // 파라미터를 전달 하는 두번째 방법
		}
	
		
		function modify( no, name, kor, eng, mat ){ // 현재 저장되어 있는 no,name,kor,eng,mat의 내용을 파라미터로 전달
			// 파라미터를 get방식으로 전달 할때 url로 넘어가는 것을 이용한 파라미터 전달 2번째 방법
            // form태그가 없어도 파라미터 전달 가능.
            // form 태그를 사용할 수 없을 때 이용 가능하나 post 방법이라면 불가능한 방법
			location.href='Sungjuck_update.jsp?no='+no+"&name="+name+"&kor="+kor+"&eng="+eng+"&mat="+mat;
			
			
		}
	
	</script>
	
	
	
	
	<style> //CSS 블럭요소를 세로 정렬이 아닌 가로 정렬을 하고 싶을때 부모가 display : flex 속성을 이용하면 쉽게 배치 가능
    		// position의 apsolute 와 relative를 사용하면 매우 복잡하고 좌표값 설정이 어려움
		caption { background: silver;}
		table {border-collapse: collapse;
			   color: white;
			   background-color: gray;
			   margin : 0 auto;
			   font-size: 20px;
			   font-family: fantasy; 
			   box-shadow: 0px, 2px, 5px, black;}
		th {width : 80px;}
		input {width : 90px;}
		.a { font-size: 20px; 
			 width : 200px;}
	
	</style>
</head>
<body>
	<table border = "1">
	<caption>성적 정보</caption>
	<tr>
		<th>학생번호</th>
		<th>학생이름</th>
		<th>국어점수</th>
		<th>수학점수</th>
		<th>영어점수</th>
		<th>성적총합</th>
		<th>성적평균</th>
		<th>성적등수</th>
		<th colspan = "2">비      고</th>
	</tr>

	<% for (SungjuckVO vo : sungjuck_list) { %> //DB에서 받아온 내용의 vo객체의 내용을 가지는 list를 for문을 통해 html의 표로 나타내기 위한 내용
		<tr align = "center">
			<td><%= vo.getNo() %></td>
			<td><%= vo.getName() %></td>
			<td><%= vo.getKor() %></td>
			<td><%= vo.getEng() %></td>
			<td><%= vo.getMat() %></td>
			<td><%= vo.getTot() %></td>
			<td><%= vo.getAvg() %></td>
			<td><%= vo.getRank() %></td>
			
		
			<td>
                                                                // 파라미터를 jsp의 값을 전달. '' 필수 html에서는 '', "" 둘다 사용가능 (가독성을 위해 적절히 활용)
				<input type="button" value="삭제" onclick="del('<%= vo.getNo() %>');"> // onclick함수를 지정함으로써 클릭함으로써 지정한 함수로 이동(JS에 함수 내용 선언)
				<input type="button" value="수정" 
				onclick="modify('<%=vo.getNo()%>',
								 '<%=vo.getName()%>',
								 '<%=vo.getKor()%>',
								 '<%=vo.getEng()%>',
								 '<%=vo.getMat()%>');">
			</td>
			
			
		
			
			
		</tr>
	<%} %>
		
		
	
	
	
		<tr align = "center">
			<td colspan = "9">                                       //클릭 할 경우 지정한 jsp파일로 이동 // 클릭시 원하는 홈페이지로 이동하게 하는 location.href='jsp 파일' 형식 이용,  
				<input class="a" type="button" value ="학생정보 추가" onclick ="location.href='Sungjuck_input.jsp'"> <!--  -->
			</td>
		</tr>
	
	
	</table>
</body>
</html>

2. 내용 추가하기(INSERT)

① 학생정보 추가 버튼 클릭시 나타나는 JSP 파일

<%@ 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>
	<script>
	function send( f ){
		
		let name = f.name.value;
		if(name == ''){
			alert("이름을 입력하세요");
			f.name.focus();
			return;
		}
		
		let number = /^[0-9]+$/;
		let kor = f.kor.value;
		let eng = f.eng.value;
		let mat = f.mat.value;
		
		if(!number.test ( kor ) || kor < 0 || kor > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		if(!number.test ( eng ) || eng < 0 || eng > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		if(!number.test ( mat ) || mat < 0 || mat > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		
		f.action = "Sungjuck_register.jsp"
		f.submit();
		
		
	}	
	
	
	
	
	</script>

	<style>
		caption { background: silver;
					font-size: 15px;}
		table {border-collapse: collapse;
			   color: white;
			   background-color: gray;
			   margin : 0 auto;
			   font-size: 20px;
			   font-family: fantasy;
			   width : 190px;}
		th {width : 200px;
			 font-size: 15px;}
		input {width : 90px;}

	</style>
	
</head>
<body>
	<form>
		<table border = "1">
			<caption>:::성적등록:::</caption>
		
			<tr>
				<th>학생이름</th>
				<td><input name="name"></td>
			</tr>
			
			<tr>
				<th>국어점수</th>
				<td><input name="kor"></td>
			</tr>
			
			<tr>
				<th>영어점수</th>
				<td><input name="eng"></td>
			</tr>
			
			<tr>
				<th>수학점수</th>
				<td><input name="mat"></td>
			</tr>
			
			<tr>
				<td colspan="2">
					<input type="button" value ="등록" onclick="send(this.form);">
					<!-- <input type="button" value ="취소" onclick="location.href ='student.jsp'"> -->
					<input type="button" value="취소" onclick="history.go(-1)">
				</td>
		
			</tr>
		</table>
	</form>
</body>
</html>

② 등록 버튼을 눌렀을때 파라미터가 전달되고  내용이 추가되는 JSP

<%@page import="vo.SungjuckVO"%>
<%@page import="dao.SungjuckDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
 <%
 	request.setCharacterEncoding("utf-8"); // post방식때 쓰지만 get방식이어도 작성하는 것 추천
 
 	//sung_input.jsp 로부터 넘겨받은 파라미터를 수신
 	String name = request.getParameter("name");
 	int kor = Integer.parseInt(request.getParameter("kor"));
 	int eng = Integer.parseInt(request.getParameter("eng"));
 	int mat = Integer.parseInt(request.getParameter("mat"));
 	
 	SungjuckVO vo = new SungjuckVO(); // 넘겨받은 파라미터를 VO 객체의 내용에 저장
 	vo.setName(name);
 	vo.setKor(kor);
 	vo.setEng(eng);
 	vo.setMat(mat);
 	//DAO에 이름 ,국어,영어,정보를 전달
 	int n = SungjuckDAO.getInstance().insert( vo ); // Vo 객체를 파라미터로 전달하면 내용 추가
 	
 	
 	if(n == 1){
 		//등록에 성공했다면 student.jsp로 화면전환
 		//location.href="student.jsp";
 		response.sendRedirect("StudentInfo.jsp");
 	}
 	
 
 %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
</body>
</html>

3. 내용 삭제하기(DELETE)

삭제 버튼을 눌렀을때 no파라미터를 가지고 이동하는 JSP

<%@page import="dao.SungjuckDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
   
   <%
   		request.setCharacterEncoding("utf-8");
   
   
   //sung_del.jsp?no=1
		int no = Integer.parseInt(request.getParameter("no"));
   
   //삭제할 학생번호를 DAO에 저달
   SungjuckDAO.getInstance().delete( no );
   response.sendRedirect("StudentInfo.jsp");
   
   %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

4. 내용 수정하기(UPDATE)

①수정버튼을 클릭했을때 이동되는 JSP

<%@ 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>
	<script>
	window.onload = function() { //윈도우 창이 켜질때 바로 실행되는 함수
		<%
			String name = request.getParameter("name");
			int no = Integer.parseInt(request.getParameter("no"));
			int kor = Integer.parseInt(request.getParameter("kor"));
			int eng= Integer.parseInt(request.getParameter("eng"));
			int mat = Integer.parseInt(request.getParameter("mat"));
		%>
		
		let ff = documentBYI.ff;
		ff.name.value = '<%= name %>';
		ff.no.value = '<%= no %>';
		ff.kor.value = '<%= kor %>';
		ff.eng.value = '<%= eng %>';
		ff.mat.value = '<%= mat%>';
		
	};
	
	function send( f ){
		
		let name = f.name.value;
		if(name == ''){
			alert("이름을 입력하세요");
			f.name.focus();
			return;
		}
		
		let number = /^[0-9]+$/;
		let kor = f.kor.value;
		let eng = f.eng.value;
		let mat = f.mat.value;
		
		if(!number.test ( kor ) || kor < 0 || kor > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		if(!number.test ( eng ) || eng < 0 || eng > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		if(!number.test ( mat ) || mat < 0 || mat > 100) {
			alert("0 ~ 100 사이의 값만 입력하세요");
			return;
		}
		
		f.action = "Sungjuck_update_result.jsp";
		f.submit();
		
		
	}	
	
	
	
	
	</script>

	<style>
		caption { background: silver;
					font-size: 15px;}
		table {border-collapse: collapse;
			   color: white;
			   background-color: gray;
			   margin : 0 auto;
			   font-size: 20px;
			   font-family: fantasy;
			   width : 190px;}
		th {width : 200px;
			 font-size: 15px;}
		input {width : 90px;}

	</style>
	
</head>
<body>
	<form name = "ff">
		<input type ="hidden" name="no">
		<table border = "1">
			<caption>:::성적수정:::</caption>
		
			<tr>
				<th>학생이름</th>
				<td><input name="name"></td>
			</tr>
			
			<tr>
				<th>국어점수</th>
				<td><input name="kor"></td>
			</tr>
			
			<tr>
				<th>영어점수</th>
				<td><input name="eng"></td>
			</tr>
			
			<tr>
				<th>수학점수</th>
				<td><input name="mat"></td>
			</tr>
			
			<tr>
				<td colspan="2">
					<input type="button" value ="등록" onclick="send(this.form);">
					<!-- <input type="button" value ="취소" onclick="location.href ='student.jsp'"> -->
					<input type="button" value="취소" onclick="history.go(-1)">
				</td>
		
			</tr>
		</table>
	</form>
</body>
</html>

② 등록 버튼을 눌렀을때 파라미터가 전달되고  내용이 수정되는 JSP

<%@page import="dao.SungjuckDAO"%>
<%@page import="vo.SungjuckVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	
//업데이트를 위해 넘겨받은 파라미터를 vo로 묶는다
	int no = Integer.parseInt(request.getParameter("no"));
	String name = request.getParameter("name");
	int kor = Integer.parseInt(request.getParameter("kor"));
	int eng = Integer.parseInt(request.getParameter("eng"));
	int mat = Integer.parseInt(request.getParameter("mat"));

	SungjuckVO vo = new SungjuckVO();
	vo.setNo(no);
	vo.setName(name);
	vo.setKor(kor);
	vo.setEng(eng);
	vo.setMat(mat);		
//DAO에게 업데이트를 요청
	SungjuckDAO.getInstance().update(vo);
	
//업데이트가 완료되면 StudentInfo.jsp로 화면 전환
 	response.sendRedirect("StudentInfo.jsp");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

DB 연결하기 위해 필요한 3개의 클래스 VO,DAO,Service

1.SungjuckVO.java : DB의 데이터를 관리하기 위한 클래스

package vo;

public class SungjuckVO {
	private int no, kor, eng, mat, tot, rank;
	private String name;
	private float avg;
	
	
	
	
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public int getKor() {
		return kor;
	}
	public void setKor(int kor) {
		this.kor = kor;
	}
	public int getEng() {
		return eng;
	}
	public void setEng(int eng) {
		this.eng = eng;
	}
	public int getMat() {
		return mat;
	}
	public void setMat(int mat) {
		this.mat = mat;
	}
	public int getTot() {
		return tot;
	}
	public void setTot(int tot) {
		this.tot = tot;
	}
	public int getRank() {
		return rank;
	}
	public void setRank(int rank) {
		this.rank = rank;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getAvg() {
		return avg;
	}
	public void setAvg(float avg) {
		this.avg = avg;
	}
	
	
	
	
	
}

2.SungjuckDAO.java : DB의 JSP를 연결하고 수정,추가,삭제의 기능의 역할을 하는 자바 클래스

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import service.DBService;
import vo.SungjuckVO;

public class SungjuckDAO {
	// single-ton pattern: 
	// 객체1개만생성해서 지속적으로 서비스하자
	static SungjuckDAO single = null;

	public static SungjuckDAO getInstance() {
		//생성되지 않았으면 생성
		if (single == null)
			single = new SungjuckDAO();
		//생성된 객체정보를 반환
		return single;
	}
	
	
	//성적테이블 조회
	//_select_list
	public List<SungjuckVO> selectList() {

		List<SungjuckVO> list = new ArrayList<SungjuckVO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from SUNGTB_VIEW";

		try {
			//1.Connection얻어온다
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체정보를 얻어오기
			pstmt = conn.prepareStatement(sql);

			//3.결과행 처리객체 얻어오기
			rs = pstmt.executeQuery();

			while (rs.next()) {
				SungjuckVO vo = new SungjuckVO();
				//현재레코드값=>Vo저장
				vo.setNo(rs.getInt("no"));
				vo.setName(rs.getString("name"));
				vo.setKor(rs.getInt("kor"));
				vo.setEng(rs.getInt("eng"));
				vo.setMat(rs.getInt("mat"));
				vo.setTot(rs.getInt("tot"));
				vo.setAvg(rs.getFloat("avg"));
				vo.setRank(rs.getInt("rank"));
				
				
				//ArrayList추가
				list.add(vo);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return list;
	}
	
	//성적 정보를 추가
	//_insert
	public int insert( SungjuckVO vo ) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;

		String sql = "insert into SUNGTB values(seq_sungtb_no.nextVal, ?,?,?,?)"; // 채워야할 자리를 ?로 나타낸다.

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기 // sql문의 ?,?,?,?의 값을 채우는 영역
									// ? 개수에 대한 정확한 번호가 들어가야함
			pstmt.setString(1, vo.getName());
			pstmt.setInt(2, vo.getKor());
			pstmt.setInt(3, vo.getEng());
			pstmt.setInt(4, vo.getMat());

			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate(); // res = 0,1의 값을 가지고 실패 : 0, 성공 : 성공한 행의 수만큼의 정수

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
	//성적정보 삭제
	public int delete( int no ) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;

		String sql = "delete from SUNGTB where no=?";

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기 // ? 자리의 값을 불러옴
			pstmt.setInt(1, no);
			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
	//성적정보 수정
	//_update
	public int update(SungjuckVO vo) {
		// TODO Auto-generated method stub
		int res = 0;

		Connection conn = null;
		PreparedStatement pstmt = null;

		String sql = "update SUNGTB SET name=?, kor=?, eng=?, mat=? where no=?";

		try {
			//1.Connection획득
			conn = DBService.getInstance().getConnection();
			//2.명령처리객체 획득
			pstmt = conn.prepareStatement(sql);

			//3.pstmt parameter 채우기
			pstmt.setString(1, vo.getName());
			pstmt.setInt(2, vo.getKor());
			pstmt.setInt(3, vo.getEng());
			pstmt.setInt(4, vo.getMat());
			pstmt.setInt(5, vo.getNo());
			//4.DB로 전송(res:처리된행수)
			res = pstmt.executeUpdate();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
	
}

3.Service.java : DB의 JSP를 연결하기 직전까지 필요한 내용을 가지고 있는 클래스

package service;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBService {
	//DB접속과정을 처리할 클래스
	// single-ton pattern: 
	// 객체1개만생성해서 지속적으로 서비스하자
	
	
	
	DataSource ds;
	
	
	static DBService single = null; 

	public DBService() { // DB와 JSP의 연결 전 까지의 모든 준비를 마치는 메서드
		
		 try {
			 InitialContext ic = new InitialContext();
			 
			 Context ctx = (Context)ic.lookup("java:comp/env");
			 
			 ds = (DataSource)ctx.lookup("jdbc/oracle_test");
			 
			 
			 
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	public static DBService getInstance() {
		//생성되지 않았으면 생성
		if (single == null)
			single = new DBService();
		//생성된 객체정보를 반환
		return single;
	}

	public Connection getConnection() {
		 Connection conn = null;
		 try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return conn;
	}
	
	
}

'JSP' 카테고리의 다른 글

Ajax,EL,Json 03/20  (0) 2023.03.21
03/17 JSP (베이커리 홈페이지)  (0) 2023.03.19
03/16 (친구관리 홈페이지)  (0) 2023.03.19
DB와 JSP 연동 03/15  (0) 2023.03.15
JSP 03/14  (0) 2023.03.14
Comments