ORACLE

등록된 학생수 : 15

학번 이름 학과 지도교수 신청학점수  
9611 일지매 컴퓨터공학과 박승곤 0
9511 김신영 컴퓨터공학과 박승곤 0
9411 서진수 컴퓨터공학과 조인형 0
9612 김진욱 멀티미디어공학과 양선희 0
9512 신은경 멀티미디어공학과 김영조 0
9412 서재수 멀티미디어공학과 양선희 0
9413 이미경 소프트웨어공학과 나한열 0
9614 김문호 전자공학과 박원범 0
9613 안광훈 전자공학과 최슬기 0
9515 임세현 전자공학과 심슨 0
9414 김재수 전자공학과 심슨 0
9513 오나라 기계공학과 박원범 0
9415 박동호 기계공학과 박원범 0
9615 노정호 문헌정보학과 허은 0
9514 구유미 문헌정보학과 허은 0

 

class DB

package config;

import java.sql.Connection;

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

public class DB {
	public static Connection dbConn(){
		//context.xml에 설정된 dbcp에서 커넥션을 가져옴
		DataSource ds=null; //javax.sql
		Connection conn=null;
		try {
			//context.xml을 분석하는 객체
			Context ctx=new InitialContext();//javax.naming
			// context.xml의 Resource 태그 검색
//			ds=
//(DataSource)ctx.lookup("java:comp/env/myDB");
			ds=
(DataSource)ctx.lookup("java:comp/env/oraDB");			
			conn = ds.getConnection(); //커넥션을 할당받음
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn; //커넥션 리턴
	}
}

 

class MybatisService

package config;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisService {
// SqlSessionFactoryBuilder => SqlSessionFactory
//		=> SqlSession	
	//SqlSession 객체 생성기
	private static SqlSessionFactory factory;
	static {
		try {
			// Java Resources의 src
			Reader r = Resources.getResourceAsReader(
					"config/sqlMapConfig.xml");
			//SqlSessionFactory 생성기
			factory = new SqlSessionFactoryBuilder()
					.build(r);
			r.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SqlSessionFactory getFactory() {
		return factory;
	}
}

 

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 지시어 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 알리아스 설정 -->
	<typeAliases>
<!-- typeAlias type="전체경로" alias="별칭" -->	
	  <typeAlias type="emp.dto.EmpDTO" alias="e" />
	</typeAliases>
	<!-- db연결 참조코드 -->
	<environments default="">
		<environment id="">
			<transactionManager type="JDBC" />
			<dataSource type="JNDI">
				<property name="data_source" 
				value="java:comp/env/oraDB" />
			</dataSource>
		</environment>
	</environments>
	<!-- 실제 sql query -->
	<mappers>
		<mapper resource="emp/mapper/emp.xml" />
		<mapper resource=
			"student/mapper/student.xml" />		
		<mapper resource=
			"student/mapper/dept.xml" />	
		<mapper resource=
			"student/mapper/prof.xml" />	
		<mapper resource=
			"student/mapper/lecture.xml" />		
		<mapper resource=
			"memo/mapper/memo.xml" />	
		<mapper resource=
			"board/mapper/board.xml" />												
	</mappers>
</configuration>





 

class DepartmentDTO

 

package student.dto;

public class DepartmentDTO {
	private int deptno;
	private String dname;

	// 기본생성자
	public DepartmentDTO() {
	}

	// getter,setter
	public int getDeptno() {
		return deptno;
	}

	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	@Override
	public String toString() {
		return "DepartmentDTO [deptno=" + deptno + ", dname=" + dname + "]";
	}
}

 

class StudentDTO

package student.dto;

public class StudentDTO {
	private int studno; // 학번
	private String name; // 학생 이름
	private int deptno1; // 제1전공코드
	private String dname; // 학과명
	private int profno; // 교수사번
	private String pname; // 지도교수 이름
	private int point; //신청학점
	public int getPoint() {
		return point;
	}
	public void setPoint(int point) {
		this.point = point;
	}
	
	// 기본생성자
	public StudentDTO() {
	}

	// 매개변수가 있는 생성자(studno,name,deptno1,profno)
	public StudentDTO(int studno, String name, int deptno1, int profno) {
		super();
		this.studno = studno;
		this.name = name;
		this.deptno1 = deptno1;
		this.profno = profno;
	}

	public int getStudno() {
		return studno;
	}

	public void setStudno(int studno) {
		this.studno = studno;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getDeptno1() {
		return deptno1;
	}

	public void setDeptno1(int deptno1) {
		this.deptno1 = deptno1;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public int getProfno() {
		return profno;
	}

	public void setProfno(int profno) {
		this.profno = profno;
	}

	public String getPname() {
		return pname;
	}

	public void setPname(String pname) {
		this.pname = pname;
	}

	@Override
	public String toString() {
		return "StudentDTO [studno=" + studno + ", name=" + name + ", deptno1=" + deptno1 + ", dname=" + dname + ", profno="
				+ profno + ", pname=" + pname + "]";
	}

}

 

student.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- student.xml -->
<mapper namespace="student">
<!--테이블의 필드명과 dto의 필드명은 반드시 일치해야 함 -->
<!--  	<select id="studentList"
		resultType="student.dto.StudentDTO"> 
	select studno, s.name, d.dname, p.name pname
	from student s, department d, professor p
	where s.deptno1=d.deptno and s.profno=p.profno	
	</select> -->
 <!-- ${변수} 따옴표 제거, #{변수} 따옴표 포함 -->
 	<select id="list"
 		resultType="student.dto.StudentDTO">
		select *  
		from (
		  select rownum as rn, A.*
		  from (  
		    select studno,name 
		    from student
	  <choose>
 		<when test="search_option != 'all'">
 		  where ${search_option} 
 		  	like '%'|| #{keyword} ||'%'	
 		</when>
 		<when test="search_option == 'all'">
 		  where name like '%'|| #{keyword} ||'%' 
 		    or studno like '%'||#{keyword}||'%'
 		</when>
 	  </choose>
		    order by studno
		  ) A
		)
		where rn between #{start} and #{end} 		
 	</select>
 	
 	<select id="studentCount" resultType="int">
 		select count(*) from student
	  <choose>
 		<when test="search_option != 'all'">
 		  where ${search_option} 
 		  	like '%'|| #{keyword} ||'%'	
 		</when>
 		<when test="search_option == 'all'">
 		  where name like '%'|| #{keyword} ||'%' 
 		    or studno like '%'||#{keyword}||'%'
 		</when>
 	  </choose>
 	</select>
 
 
 	<select id="studentList"
		resultType="student.dto.StudentDTO">  
select studno, st.name, d.dname, p.name pname

from student st, department d, professor p
where st.deptno1=d.deptno and st.profno=p.profno
	</select> 
	
<!-- select studno, st.name, d.dname, p.name pname
,( select sum(point) from subject s, lecture l
where  l.subject_code=s.subject_code 
and l.studno=st.studno) point
from student st, department d, professor p
where st.deptno1=d.deptno and st.profno=p.profno -->
	
	
	<insert id="studentAdd">
	insert into student 
		(studno,name,id,jumin,deptno1,profno) 
	values (#{studno},#{name},' ',' '
		,#{deptno1},#{profno} )	
	</insert>
	
	<delete id="studentDel">
		delete from student where studno=#{studno}
	</delete>
</mapper>


 

dept.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- dept.xml -->
<mapper namespace="dept">
	<select id="deptList"
		resultType="student.dto.DepartmentDTO">
		select deptno,dname from department
	</select>
</mapper>

 

class StudentController

package student;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 student.dao.StudentDAO;
import student.dto.DepartmentDTO;
import student.dto.ProfessorDTO;
import student.dto.StudentDTO;

@WebServlet("/student_servlet/*")
public class StudentController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url=request.getRequestURL().toString();
		String path=request.getContextPath();
		StudentDAO dao=StudentDAO.getInstance();
		if(url.indexOf("list.do") != -1) {
			long start=System.currentTimeMillis();
			List<StudentDTO> list=dao.list();
			long end=System.currentTimeMillis();
			System.out.println("실행시간:"+(end-start)); 
			Map<String,Object> map
				=new HashMap<String,Object>();
			map.put("list", list);
			map.put("count", list.size());
			request.setAttribute("map", map);
			String page="/sql03/student_list.jsp";
			RequestDispatcher rd=
					request.getRequestDispatcher(page);
			rd.forward(request, response);
		}else if(url.indexOf("insert.do") != -1){
			
//학번,이름을 받아옴			
			int studno=
Integer.parseInt(request.getParameter("studno"));
			String name=request.getParameter("name");
			int deptno1=Integer.parseInt(
					request.getParameter("deptno1"));
			int profno=Integer.parseInt(
					request.getParameter("profno"));
			StudentDTO dto=
new StudentDTO(studno, name, deptno1, profno);
//dao에 insert 요청			
			dao.insert(dto); 
		}else if(url.indexOf("deptList.do") != -1){
			List<DepartmentDTO> list=dao.departmentList();
			request.setAttribute("list", list);
			System.out.println(list);
			String page="/sql03/dept_list.jsp";
			RequestDispatcher rd
				=request.getRequestDispatcher(page);
			rd.forward(request, response); 
		}else if(url.indexOf("prof.do") != -1){
			int deptno = Integer.parseInt(
					request.getParameter("deptno"));
			List<ProfessorDTO> list=dao.profList(deptno);
			request.setAttribute("list", list);
			String page="/sql03/prof_list.jsp";
			RequestDispatcher rd=
					request.getRequestDispatcher(page);
			rd.forward(request, response);
		}else if(url.indexOf("del.do") != -1){
			int studno=Integer.parseInt(
					request.getParameter("studno"));
			dao.delete(studno);
//삭제 후 student.jsp 페이지로 이동			
			String page=path+"/sql03/student.jsp";
			response.sendRedirect(page);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}






 

 

student_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<script src="${path}/include/jquery-3.1.1.min.js"></script>
<script>
function del(studno){
	location.href=
"${path}/student_servlet/del.do?studno="+studno;
}
</script>
</head>
<body>
등록된 학생수 : ${map.count}
<table border="1">
	<tr>
		<th>학번</th>
		<th>이름</th>
		<th>학과</th>
		<th>지도교수</th>
		<th>신청학점수</th>
		<th>&nbsp;</th>
	</tr>
<c:forEach	var="row" items="${map.list}">
	<tr align="center">
		<td>${row.studno}</td>
		<td>${row.name}</td>
		<td>${row.dname}</td>
		<td>${row.pname}</td>
		<td>${row.point}</td>
		<td><input type="button" 
			onclick="del('${row.studno}')"
			value="삭제"></td>
	</tr>
</c:forEach>	
</table>
</body>
</html>









 

student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<script src="${path}/include/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
	student_list();
	dept_list(); //학과 목록 요청
	prof_list(); //컴퓨터공학과
	$("#btnSave").click(function(){
		student_add();
	});
	$("#majorList").change(function(){
		prof_list();
	});
});
function prof_list(){
	var param="deptno=";
	var deptno = $("#deptno1").val();
	if( deptno == null ) { //기본학과코드를 101로 설정
		param += "101";
	}else{
		param += deptno;
	}
	$.ajax({
		type: "post",
		url: "${path}/student_servlet/prof.do",
		data: param,
		success: function(result){
			$("#profList").html(result);
		}
	});
}
function dept_list(){
	$.ajax({
		type: "post",
		url: "${path}/student_servlet/deptList.do",
		success: function(result){
			$("#majorList").html(result);
		}
	});
}
function student_add(){
	var param="studno="+$("#studno").val()
		+"&name="+$("#name").val()
		+"&deptno1="+$("#deptno1").val()
		+"&profno="+$("#profno").val();
			
	$.ajax({
		type: "post",
		url: "${path}/student_servlet/insert.do",
		data: param,
		success: function(){
			student_list();
		}
	});
}
function student_list(){
	$.ajax({
		type: "post",
		url: "${path}/student_servlet/list.do",
		success: function(result){
			$("#result").html(result);
		}
	});
}
</script>
</head>
<body>
<!-- WebContent/sql03/student.jsp -->
<h2>학생명단</h2>

학번 : <input id="studno">
이름 : <input id="name">
<span id="majorList">학과목록이 출력될 부분</span>
<span id="profList">교수목록이 출력될 부분</span>
<button id="btnSave">확인</button>

<div id="result"></div>
</body>
</html>









 

 

dept_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="../include/header.jsp" %>
<script src="/include/jquery-3.1.1.min.js"></script>
<script>
</script>
</head>
<body>
<select id="deptno1"> 
<c:forEach var="row" items="${list}">
  <option value="${row.deptno}">${row.dname}</option>
</c:forEach>	
</select>
</body>
</html>









 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

대장부란 인(仁)이라는 천하의 넓은 집에 살고, 예라는 천하의 바른 위치에 서서, 의리라는 천하의 큰 도를 행하는 것이다. -장자

댓글 ( 0)

댓글 남기기

작성
  •    
  •