---------------------------------------

재전송 방법


1. sendRedirect()

요청 주소 -> A

응답 주소 -> B

브라우저 주소 -> A -> B


2. forward()

요청 주소 -> A (서블릿)

응답 주소 -> B (JSP)

브라우저 주소 -> A -> A


-----------------------------------

forward() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


-특징

. 재전송 (서버 차원에서 URL를 다른 페이지로 변경해버린다)

. 입력(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 출력(HTML이 포함된 JSP 페이지) 전용 페이지

. request.setAttribute() 메소드를 이용해서 데이터를 재전송시킬 수 있다.

. 받을 때는 request.getAttribute() 메소드 이용.

. 재전송 데이터는 객체 형태의 데이터는 모두 가능.

. 서버 차원에서 URL를 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 없다.


-----------------------------------

sendRedirect() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


-특징

. 재전송 (서버 차원에서 URL를 다른 페이지로 변경해버린다)

. 요청페이지(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 결과페이지(HTML이 포함된 JSP 페이지) 전용 페이지

. 클라이언트 차원에서 URL를 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 있다.

. 재전송 데이터는 GET 방식으로 전송 가능.

. 재전송 가능한 데이터는 문자열 형태의 데이터만 가능.


--------------------------------------

데이터 송수신 테스트9

-> Send09, Receive09를 모두 서블릿으로 변경

-> HTML 페이지가 있는 인터페이스는 JSP로 작성.

-> 액션은 Servlet이 담당.


//Send09.java -> 서블릿 클래스. 주소 처리 담당. 액션 담당.

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send09 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//입력 화면 구성용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Send09.jsp");

dispatcher.forward(req, resp);

}


}




//Send09.jsp -> 데이터 입력용 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

//이름, 전화번호가 비어있는지 검사하는 과정 추가

//이름, 전화번호가 채워진 경우만 데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>데이터 송수신 테스트9</h2>

<!-- <form> 태그에서 action, method 속성 필수 -->

<form action="Receive09" method="post">

<!-- JSP에서는 식별자를 name 속성으로 구분 -->

이름 <input type="text" name="name"><br>

전화 <input type="text" name="tel"><br>

<!-- submit 버튼을 클릭하면 데이터 전송됨 -->

<!-- <input type="submit" value="회원가입"><br> -->

<!-- 자바스크립트 연동시 submit 대신 button 으로 처리 -->

<input type="button" value="회원가입"

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화번호를 채워야 합니다.</span>

</form>

</div>

</body>

</html>




//Receive09.java  -> 서블릿 클래스. 주소 처리 담당. 액션 담당.

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive09 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//액션 처리 코드

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

//결과 메시지 생성

StringBuilder str = new StringBuilder();

str.append(String.format("name:%s, tel:%s", name, tel));

//결과 메시지 재전송

req.setAttribute("str", str);

//결과 출력용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Receive09.jsp");

dispatcher.forward(req, resp);

}


}





//Receive09.jsp -> 결과 출력용 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//결과 메시지 수신

StringBuilder str = (StringBuilder)request.getAttribute("str");

%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트9</h2>

<h3><%=str%></h3>

</div>

</body>

</html>




//web.xml -> 서블릿 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Send09</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Send09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive09</servlet-name>

<servlet-class>com.test.Receive09</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive09</servlet-name>

<url-pattern>/Receive09</url-pattern>

</servlet-mapping>

  

</web-app>




//요청주소

http://localhost:8090/프로젝트이름/서블릿이름

http://localhost:8090/Servlet_20121205/Send09



--------------------------------------

데이터 송수신 테스트10

-> Send10, Receive10을 하나의 서블릿으로 변경

-> 서블릿 주소를 확장자로 통합 처리(*.확장자)

-> 서블릿 주소 분석 과정 필요

-> HTML 페이지가 있는 인터페이스는 JSP로 작성.

-> 액션은 Servlet이 담당.


//SendAndReceive10.java -> 서블릿 클래스. 주소 분석 과정. 액션 담당.

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class SendAndReceive10 extends HttpServlet {

private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//서블릿 주소 분석 과정 추가

String uri = req.getRequestURI();

//System.out.println(uri);

if (uri.indexOf("Send10.do") != -1) {

Send10(req, resp);

}

if (uri.indexOf("Receive10.do") != -1) {

Receive10(req, resp);

}

}

private void Send10(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//입력 화면 구성용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Send10.jsp");

dispatcher.forward(req, resp);

}

private void Receive10(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

//결과 메시지 생성

StringBuilder str = new StringBuilder();

str.append(String.format("name:%s, tel:%s", name, tel));

//결과 메시지 재전송

req.setAttribute("str", str);

//결과 출력용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Receive10.jsp");

dispatcher.forward(req, resp);

}

}





//Send10.jsp -> 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

//이름, 전화번호가 비어있는지 검사하는 과정 추가

//이름, 전화번호가 채워진 경우만 데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>데이터 송수신 테스트10</h2>

<!-- <form> 태그에서 action, method 속성 필수 -->

<form action="Receive10.do" method="post">

<!-- JSP에서는 식별자를 name 속성으로 구분 -->

이름 <input type="text" name="name"><br>

전화 <input type="text" name="tel"><br>

<!-- submit 버튼을 클릭하면 데이터 전송됨 -->

<!-- <input type="submit" value="회원가입"><br> -->

<!-- 자바스크립트 연동시 submit 대신 button 으로 처리 -->

<input type="button" value="회원가입"

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화번호를 채워야 합니다.</span>

</form>

</div>

</body>

</html>




//Receive10.jsp -> 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//결과 메시지 수신

StringBuilder str = (StringBuilder)request.getAttribute("str");

%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트10</h2>

<h3><%=str%></h3>

</div>

</body>

</html>




//web.xml -> 서블릿 주소 등록. 서블릿 주소를 확장자로 통합 처리.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Send09</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Send09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive09</servlet-name>

<servlet-class>com.test.Receive09</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive09</servlet-name>

<url-pattern>/Receive09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>sendandreceive10</servlet-name>

<!-- 서블릿 주소 분석 과정 필요 -->

<servlet-class>com.test.SendAndReceive10</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sendandreceive10</servlet-name>

<!-- 서블릿 주소를 확장자로 통합 처리

이름에 관계없이 확장자만 do인 경우는

모두 서블릿으로 처리됨 -->

<url-pattern>*.do</url-pattern>

</servlet-mapping>

  

</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Send10.do


------------------------------------

문제) 이름, 국어, 영어, 수학 점수를 입력 받아서 총점, 평균 계산해서 결과 출력하는 페이지 작성. JSP&Servlet 이용.


//SungjukServlet.java ->서블릿 주소 분석 과정 추가.

//-> 이름, 국어, 영어, 수학 점수를 수신해서 총점, 평균 계산

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class SungjukServlet extends HttpServlet{

private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//서블릿 주소 분석 과정 추가

String uri = req.getRequestURI();

//(브라우저에 요청된 주소를 프로그램적으로 읽어옴)

//System.out.println(uri); //(확인용) 

//(uri.indexOf("")특정 문자열이 존재하는지 어떤지 알려주는 기능/ -1이 아니면 존재함.)

if (uri.indexOf("Send11.sung") != -1) {

Send11(req, resp);

}

if (uri.indexOf("Receive11.sung") != -1){

Receive11(req, resp);

}

}

private void Send11(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//입력 화면 구성용 인터페이스 코드 작성(예전)

//-> 전용 JSP 페이지로 연결함.

//forward()

RequestDispatcher dispatcher 

= req.getRequestDispatcher("Send11.jsp");

dispatcher.forward(req, resp);

}

private void Receive11(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//액션 처리 코드

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");


String name = req.getParameter("name");

String kors = req.getParameter("kor");

String engs = req.getParameter("eng");

String mats = req.getParameter("mat");

int kor = Integer.parseInt(kors);

int eng = Integer.parseInt(engs);

int mat = Integer.parseInt(mats);

int tot = kor+eng+mat;

double ave= tot/(double)3;

//결과 메시지 재전송

req.setAttribute("name", name);

req.setAttribute("kor", kor);

req.setAttribute("eng", eng);

req.setAttribute("mat", mat);

req.setAttribute("tot", tot);

req.setAttribute("ave", ave);

//결과 출력용 인터페이스 코드 작성(예전)

//-> 전용 JSP 페이지로 연결함.

//forward()

RequestDispatcher dispatcher 

= req.getRequestDispatcher("Receive11.jsp");

dispatcher.forward(req, resp);

}


}





//Send11.jsp

//-> 이름, 국어, 영어, 수학 점수를 입력받는 페이지 작성. 서버에 데이터 전송.

//-> 데이터 검사 과정 추가. 자바스크립트 이용.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

var name = document.getElementById("name");

var korObj = document.getElementById("kor");

var engObj = document.getElementById("eng");

var matObj = document.getElementById("mat");

var kor = korObj.value;

var eng = engObj.value;

var mat = matObj.value;

var msg1 = document.getElementById("msg1");

var msg2 = document.getElementById("msg2");

msg1.style.display = "none";

msg2.style.display = "none";

if(name.value =="" || kor =="" || mat =="" ||eng==""){

msg1.style.display ="inline";

if(name.value ==""){

name.focus();

}

if(kor==""){

korObj.focus();

}

if(mat ==""){

matObj.focus();

}

if(eng ==""){

engObj.focus();

}

} else if(kor.match(/[^0-9]/) ||eng.match(/[^0-9]/) || mat.match(/[^0-9]/)

|| parseInt(kor)>100 || parseInt(eng)>100 || parseInt(mat)>100){

msg2.style.display ="inline";

if(mat.match(/[^0-9]/) || parseInt(mat)>100){

matObj.value = "";

matObj.focus();

}

if(eng.match(/[^0-9]/) || parseInt(eng)>100){

engObj.value = "";

engObj.focus();

}

if(kor.match(/[^0-9]/) || parseInt(kor)>100){

korObj.value = "";

korObj.focus();

}


}else {

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>성적 입력</h2>

<form action = "Receive11.sung" method ="post">

이름<input type="text" name="name" id="name"><br>

국어<input type="text" name="kor" id="kor">(0~100)<br>

영어<input type="text" name="eng" id="eng">(0~100)<br>

수학<input type="text" name="mat" id="mat">(0~100)<br>

<input type = "button" value="입력" 

onclick = "myFunc(this)"><br>

<span id = "msg1" style ="color:red; display:none;">모든 항목을 채우세요.</span> 

<span id = "msg2" style ="color:red; display:none;">점수는 범위에 맞는, 숫자를 쓰세요.</span> 

</form>

</div>

</body>

</html>




//Receive11.jsp

//-> 결과 메시지 출력.

//-> 테이블 태그 이용해서 표 형태로 출력.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String name = (String) request.getAttribute("name");


int kor = (Integer) request.getAttribute("kor");

int eng = (Integer) request.getAttribute("eng");

int mat = (Integer) request.getAttribute("mat");

int tot = (Integer) request.getAttribute("tot");

double ave = (Double) request.getAttribute("ave");


StringBuilder str = new StringBuilder();

str.append(String

.format("<table><tbody><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th>"));

str.append(String

.format("<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%.2f</td></tr></tbody></table>",

name, kor, eng, mat, tot, ave));

%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>성적 총점과 평균까지</h2>

<div><%=str%></div>

</div>

</body>

</html>




//web.xml -> 확장자 .sung로 서블릿 주소 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>sungjuk11</servlet-name>

<servlet-class>com.test.SungjukServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sungjuk11</servlet-name>

<url-pattern>*.sung</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Send11.sung


-----------------------------------------

문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성. 

오라클, JSP, Servlet 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------


//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}





//MemberDTO.java -> 자료 처리 전용 클래스.

package com.test;


public class MemberDTO {

private int mid;

private String name, tel;


public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}




//MemberServlet.java -> 서블릿. 서블릿 주소 분석. 입력 액션, 출력 액션.

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;

import java.util.ArrayList;


public class MemberServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//서블릿 주소 분석

String uri = req.getRequestURI();

if (uri.indexOf("Member.me") != -1) {

member(req, resp);

}

if (uri.indexOf("MemberInsert.me") != -1) {

memberInsert(req, resp);

}

}


private void member(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터베이스 연결

//자료를 읽어온다.

//자료 재전송

String count = "";

ArrayList<MemberDTO>

arrayList = new ArrayList<MemberDTO>();

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//SELECT 실행 구문 -> 회원수 -> count 변수에 저장

String sql1 = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt = conn.createStatement();

ResultSet rs1 = stmt.executeQuery(sql1); //결과집합

while(rs1.next()) { //row 단위 접근

int result = rs1.getInt("count"); //column 단위 접근

count = String.format("%d", result);

}

rs1.close();

//SELECT 실행 구문 -> 회원 명단 -> 테이블 태그 이용-> str 변수에 누적

String sql2 = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

ResultSet rs2 = stmt.executeQuery(sql2); //결과집합

while(rs2.next()) { //row 단위 접근

int mid = rs2.getInt("mid"); //column 단위 접근

String name = rs2.getString("name");

String tel = rs2.getString("tel");


MemberDTO dto = new MemberDTO();

dto.setMid(mid);

dto.setName(name);

dto.setTel(tel);

arrayList.add(dto);

}

rs2.close();

req.setAttribute("count", count);

req.setAttribute("arrayList", arrayList);

} catch(Exception e) {

System.out.println(e.toString());

}

//MemberServlet.jsp 페이지로 연결

//forward() 메소드 이용

RequestDispatcher dispatcher 

= req.getRequestDispatcher("MemberServlet.jsp");

dispatcher.forward(req, resp);

}


private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//자료를 입력한다.

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

try {

Connection conn = DBConn.getConnection();

String sql = String.format("INSERT INTO member (mid,name,tel) VALUES (memberSeq.nextval, '%s', '%s')", name, tel);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch(Exception e) {

System.out.println(e.toString());

}

//Member.me 서블릿을 재요청 한다.

//sendRedirect() 메소드 이용

String url = String.format("Member.me");

resp.sendRedirect(url);

}

}





//MemberServlet.jsp -> 입력, 출력 화면 구성용 페이지. 결과 메시지 출력.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

String count = (String)request.getAttribute("count");

StringBuilder str = new StringBuilder();

@SuppressWarnings("unchecked")

ArrayList<MemberDTO>

arrayList = (ArrayList<MemberDTO>)request.getAttribute("arrayList");

for (MemberDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td>%d</td>", dto.getMid()));

str.append(String.format("<td>%s</td>", dto.getName()));

str.append(String.format("<td>%s</td>", dto.getTel()));

str.append("</tr>");

}

%>    

<!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=EUC-KR">

<title>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈 칸 검사

if (name.value == ""

|| tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>이름과 전화번호를 저장하는 프로그램(JSP, Servlet, JDBC)</h2>

<form action="MemberInsert.me" method="post">

이름 <input type="text" name="name" id="name"><br>

전화 <input type="text" name="tel" id="tel"><br>

<input type="button" value=" 등록 "

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</form>

<h3>출력-------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table style="width:400px;" border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//web.xml -> 확장자(*.me)에 의한 서블릿 주소 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>member11</servlet-name>

<servlet-class>com.test.MemberServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>member11</servlet-name>

<url-pattern>*.me</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Member.me




------------------------------------------

문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 

오라클, JSP, Servlet 이용. 

총점 기준 정렬(내림차순) 출력.

ScoreDTO, ScoreDAO 작성 추가.



판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 ----------------

이름 [kim   ]

국어 [80    ]

영어 [90    ]

수학 [80    ]

[ 등록 ]


---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------




//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}






//ScoreDTO.java

package com.test;


public class ScoreDTO {


private String name;

private int kor, eng, mat;


private int tot;

private double ave;

private String grade;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

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 double getAve() {

return ave;

}

public void setAve(double ave) {

this.ave = ave;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}

}







//ScoreDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class ScoreDAO {


private Connection conn;


public void connect()

throws SQLException, ClassNotFoundException{

conn = DBConn.getConnection();


}


public void close() 

throws SQLException{

DBConn.close();

conn = null;

}



public int add(ScoreDTO dto) 

throws SQLException{

int rowCount =0;


String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %d, %d, %d)", dto.getName(), dto.getKor(), dto.getEng(), dto.getMat());

Statement stmt = conn.createStatement();

rowCount = stmt.executeUpdate(sql);


return rowCount;

}


public ArrayList<ScoreDTO> lists() 

throws SQLException{

ArrayList<ScoreDTO> arrayList = new ArrayList<ScoreDTO>();


String sql = String.format("SELECT name, kor, eng, mat, (kor+eng+mat) AS tot, (kor+eng+mat)/3 AS ave, CASE WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락' WHEN ((kor+eng+mat)/3 >= 60) THEN '합격' ELSE '불합격' END AS grade FROM score ORDER BY tot DESC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");


ScoreDTO dto = new ScoreDTO();

dto.setName(name);

dto.setKor(kor);

dto.setEng(eng);

dto.setMat(mat);

dto.setTot(tot);

dto.setAve(ave);

dto.setGrade(grade);


arrayList.add(dto);

}


rs.close();


return arrayList;


}

}






//ScoreServlet.java

package com.test;


import java.io.IOException;

import java.util.ArrayList;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class ScoreServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//서블릿 주소 분석

String uri = req.getRequestURI();

if (uri.indexOf("Score.sc") != -1) {

score(req, resp);

}

if (uri.indexOf("ScoreInsert.sc") != -1) {

scoreInsert(req, resp);

}

}

private void score(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터베이스 연결

//자료를 읽어온다.

//자료 재전송

ScoreDAO dao = new ScoreDAO();

ArrayList<ScoreDTO>

arrayList = new ArrayList<ScoreDTO>();

try {

dao.connect();

arrayList = dao.lists();

} catch(Exception e) {

System.out.println(e.toString());

}

req.setAttribute("arrayList", arrayList);


//ScoreServlet.jsp 페이지로 연결

//forward() 메소드 이용

RequestDispatcher dispatcher 

= req.getRequestDispatcher("ScoreServlet.jsp");

dispatcher.forward(req, resp);

}


private void scoreInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//자료를 입력한다.

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String kor = req.getParameter("kor");

String eng = req.getParameter("eng");

String mat = req.getParameter("mat");

ScoreDAO dao = new ScoreDAO();

try {

dao.connect();

ScoreDTO dto = new ScoreDTO();

dto.setName(name);

dto.setKor(Integer.parseInt(kor));

dto.setEng(Integer.parseInt(eng));

dto.setMat(Integer.parseInt(mat));

dao.add(dto);

} catch(Exception e) {

System.out.println(e.toString());

}

//Score.sc 서블릿을 재요청 한다.

//sendRedirect() 메소드 이용

String url = String.format("Score.sc");

resp.sendRedirect(url);

}

}





//ScoreServlet.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>       

<%

StringBuilder str = new StringBuilder();

@SuppressWarnings("unchecked")

ArrayList<ScoreDTO>

arrayList = (ArrayList<ScoreDTO>)request.getAttribute("arrayList");


int rank = 0;

for (ScoreDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td><td class=\"style1\">%s</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%.1f</td><td class=\"style1\">%s</td>"

, ++rank

, dto.getName()

, dto.getKor()

, dto.getEng()

, dto.getMat()

, dto.getTot()

, dto.getAve()

, dto.getGrade()));

str.append("</tr>");

}


%>    

<!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=EUC-KR">

<title>Insert title here</title>


<style type="text/css">

.subject {

width:80px;

}

.style1 {

text-align: center;

}

.style2 {

text-align: right;

}

</style>


<script type="text/javascript">

function myFunc(obj){

var name = document.getElementById('name');

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(name.value == "" || kor.value == "" || eng.value ==""|| 


mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)


||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 


||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>성적 처리(JSP, Servlet, JDBC)</h2>

<form action="ScoreInsert.sc" method="post">

이름 <input type="text" name="name" id="name"><br> 

국어 <input type="text" name="kor" id="kor" 


class="subject"><br>

영어 <input type="text" name="eng" id="eng" 


class="subject"><br>

수학 <input type="text" name="mat" id="mat" 


class="subject"><br>

<input type="button" value=" 등록 "

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 국어, 


영어, 수학을 입력해야 합니다.<br>국어, 영어, 수학을 0~100 사이의 숫자를 입력


해야 합니다.</span>

</form>

<h3>출력 ------------</h3>

<div>

<table border="1" style="width:500px;">

<tbody>

<tr>

<th>등수</th>

<th>이름</th>

<th>국어</th>

<th>영어</th>

<th>수학</th>

<th>총점</th>

<th>평균</th>

<th>판정</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>score11</servlet-name>

<servlet-class>com.test.ScoreServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>score11</servlet-name>

<url-pattern>*.sc</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Score.sc


--------------------------------------


'Java > JSP & Servlet' 카테고리의 다른 글

[20121207] 18일차 (상담게시판)  (0) 2012.12.18
[20121206] 17일차  (0) 2012.12.14
[20121204] 15일차 (Servlet JDBC 연동)  (0) 2012.12.04
[20121203] 14일차 (Servlet)  (0) 2012.12.04
[20121122] 8일차 (직원관리 최종버젼)  (0) 2012.12.04

WRITTEN BY
빨강꼬마

,

Servlet & JDBC



1. 다이나믹 웹 프로젝트 생성 후에 WebContent > WEB-INF > lib 폴더에 ojdbc14.jar 파일을 넣어야 함.


------------------------------------------------------------------------------------

DBConn 클래스를 이용한 오라클 연결 테스트


//DBConn.java -> Java Resources > src 폴더에 패키지 생성 후 복사할 것.

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}




//Oracle01.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle01 extends HttpServlet {


private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}

protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String str = "연결 실패!";

Connection conn = null;

try {

conn = DBConn.getConnection();

str = "연결 성공!";

}catch(Exception e){

System.out.println(e.toString());

}finally {

try {

DBConn.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>오라클 연결 테스트</h2>");

out.print("<div>");

out.print(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


}



------------------------------------------------------------------------------------

SQL 쿼리 전송 테스트1 (scott 계정)


//회원 테이블 생성. 회원번호, 이름, 전화번호. 시퀀스 객체 생성.

CREATE TABLE member (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member

ADD CONSTRAINT member_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE memberSeq;



//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, 'hong', '111-1111')



//DBConn.java


//Oracle02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Oracle02 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

//html 도큐먼트를 동적 생성하기 위한 부분

PrintWriter out = resp.getWriter();

String str = "";

try {

//연결

Connection conn = DBConn.getConnection();

//쿼리 준비

//쿼리 작성시 끝에 ; 표시하지 말것.

String sql = String.format("INSERT INTO member (mid,name, tel) VALUES (memberSeq.nextval, 'lee', '123-1234')");

//쿼리 실행

//Java에서 쿼리를 실행하면 

//내부적으로 COMMIT은 자동 실행됨.

//executeUpdate() 메소드는 DML문인 경우만 실행.

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(sql);

//결과 메시지

str = String.format("%d개의 행이 입력되었습니다. <br>"

, count);

}catch(Exception e) {

System.out.println(e.toString());

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>SQL 쿼리 전송 테스트1</h2>");

out.print("<div>");

out.print(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}





//web.xml




-----------------------------------------------------------------------------------

회원 테이블 자료 출력 테스트. SELECT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//SELECT mid, name, tel FROM member ORDER BY mid


//DBConn.java


//Oracle03.java


//web.xml



------------------------------------------------------------------------------------

문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성2. 오라클, JSP 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333






------------------------------------------

문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 오라클, Servlet 이용. 

총점 기준 정렬(내림차순) 출력.


판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 ----------------

이름 [kim   ]

국어 [80    ]

영어 [90    ]

수학 [80    ]

[ 등록 ]


---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------


---------------------------------------------

--오라클에 성적 저장용 테이블 생성

CREATE TABLE score (

sid NUMBER --PK, 자동 번호 부여

,name VARCHAR2(10)

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score

ADD CONSTRAINT score_sid_pk PRIMARY KEY (sid);

ALTER TABLE score

ADD CONSTRAINT score_kor_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_mat_ck CHECK (mat BETWEEN 0 AND 100);


--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE scoreSeq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score (sid, name, kor, eng, mat)

VALUES (scoreSeq.nextval, 'hong', 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave


--, 조건검사 쿼리 추가 ->합격, 불합격, 과락 출력

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade


FROM score

ORDER BY tot DESC


--scoreView를 이용한 SELECT 쿼리

SELECT sid, name, kor, eng, mat, tot, ave, grade 

FROM scoreView 

ORDER BY tot DESC



//DBConn.java


//Oracle08.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle08 extends HttpServlet {


private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

StringBuilder str = new StringBuilder();

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//SELECT 실행 구문 -> 회원 명단 -> 테이블 태그 이용-> STR 변수에 누적

String sql = String.format("SELECT sid, name, kor, eng, mat, tot, ave, grade FROM scoreView ORDER BY tot DESC");


Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql); //결과집합

int rank = 0;

while(rs.next()) { //row 단위 접근

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td><td class=\"style1\">%s</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%.1f</td><td class=\"style1\">%s</td>"

, ++rank, name, kor, eng, mat, tot, ave, grade));

str.append("</tr>");

}

rs.close();

} catch(Exception e) {

System.out.println(e.toString());

}

//HTML 도큐먼트를 동적 생성하기 위한 부분

PrintWriter out = resp.getWriter();


out.println(" <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println(" <html>");

out.println(" <head>");

out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println(" <title>Insert title here</title>");

out.println(" ");

out.println(" <style type=\"text/css\">");

out.println(" .subject {");

out.println(" width:80px;");

out.println(" }");

out.println(" .style1 {");

out.println(" text-align: center;");

out.println(" }");

out.println(" .style2 {");

out.println(" text-align: right;");

out.println(" }");

out.println(" </style>");

out.println(" ");

out.println(" <script type=\"text/javascript\">");

out.println(" function myFunc(obj){");

out.println(" var name = document.getElementById('name');");

out.println(" var kor = document.getElementById('kor');");

out.println(" var eng = document.getElementById(\"eng\");");

out.println(" var mat = document.getElementById(\"mat\");");

out.println(" ");

out.println(" var msg = document.getElementById(\"msg\");");

out.println(" msg.style.display = \"none\";");

out.println(" ");

out.println(" //빈칸 검사");

out.println(" if(name.value == \"\" || kor.value == \"\" || eng.value ==\"\"|| mat.value==\"\"){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" } ");

out.println(" //숫자 검사");

out.println(" if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)||mat.value.match(/[^0-9]/)){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" } ");

out.println(" //범위 검사");

out.println(" if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" }");

out.println(" //데이터 전송");

out.println(" obj.form.submit();");

out.println(" }");

out.println(" </script>");

out.println(" ");

out.println(" </head>");

out.println(" <body>");

out.println(" <div>");

out.println(" <h2>성적 처리</h2>");

out.println(" <form action=\"Oracle08_Insert\" method=\"post\">");

out.println(" 이름 <input type=\"text\" name=\"name\" id=\"name\"><br>"); 

out.println(" 국어 <input type=\"text\" name=\"kor\" id=\"kor\" class=\"subject\"><br>");

out.println(" 영어 <input type=\"text\" name=\"eng\" id=\"eng\" class=\"subject\"><br>");

out.println(" 수학 <input type=\"text\" name=\"mat\" id=\"mat\" class=\"subject\"><br>");

out.println(" <input type=\"button\" value=\" 등록 \"");

out.println(" onclick=\"myFunc(this)\"><br>");

out.println(" <span id=\"msg\" style=\"color:red; display:none;\">이름, 국어, 영어, 수학을 입력해야 합니다.<br>국어, 영어, 수학을 0~100 사이의 숫자를 입력해야 합니다.</span>");

out.println(" </form>");

out.println(" <h3>출력 ------------</h3>");

out.println(" <div>");

out.println(" <table border=\"1\" style=\"width:500px;\">");

out.println(" <tbody>");

out.println(" <tr>");

out.println(" <th>등수</th>");

out.println(" <th>이름</th>");

out.println(" <th>국어</th>");

out.println(" <th>영어</th>");

out.println(" <th>수학</th>");

out.println(" <th>총점</th>");

out.println(" <th>평균</th>");

out.println(" <th>판정</th>");

out.println(" </tr>");

out.println(str);

out.println(" </tbody>");

out.println(" </table>");

out.println(" </div>");

out.println(" </div>");

out.println(" </body>");

out.println(" </html>");

}

}





//Oracle08_Insert.java

package com.test;


import java.io.IOException;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle08_Insert extends HttpServlet {


private static final long serialVersionUID = 1L;


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String kor = req.getParameter("kor");

String eng = req.getParameter("eng");

String mat = req.getParameter("mat");

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//INSERT 실행 구문

String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %s, %s, %s)", name, kor, eng, mat);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch(Exception e) {

System.out.println(e.toString());

}

//sendRedirect() 메소드 이용

String url = String.format("Oracle08");

resp.sendRedirect(url);

}

}





//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121204</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

 

<servlet>

<servlet-name>oracle08</servlet-name>

<servlet-class>com.test.Oracle08</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>oracle08</servlet-name>

<url-pattern>/Oracle08</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>oracle08_insert</servlet-name>

<servlet-class>com.test.Oracle08_Insert</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>oracle08_insert</servlet-name>

<url-pattern>/Oracle08_Insert</url-pattern>

</servlet-mapping>

</web-app>


-----------------------------------------------------------------------------------------------------


문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성4. 오라클, Servlet 이용.

데이터 입력과 출력을 동시 실행. 삭제 기능 추가.

MemberDTO, MemberDAO를 별도 작성.


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


-----------------------------------

전체 회원수 : 2명

-----------------------------------

회원번호 이름   전화번호      삭제

-----------------------------------

1        홍길동 010-123-1234  삭제

2        김길동 010-222-3333  삭제

-----------------------------------


//DBConn.java


//MemberDTO.java 


//MemberDAO.java 


//Oracle09.java


//Oracle09_Insert.java


//Oracle09_Delete.java



------------------------------------------------------------------------------------------------------

재전송 방법.


1. sendRedirect()

요청주소 -> A

응답주소 -> B

브라우저 -> A -> B


2. forward();

요청주소 -> A (서블릿)

응답주소 -> B (JSP)

브라우저 주소 -> A -> A

'Java > JSP & Servlet' 카테고리의 다른 글

[20121206] 17일차  (0) 2012.12.14
[20121205] 16일차 (JSP / Servlet / JDBC 연동)  (0) 2012.12.05
[20121203] 14일차 (Servlet)  (0) 2012.12.04
[20121122] 8일차 (직원관리 최종버젼)  (0) 2012.12.04
[20121121] 7일차 (직원관리)  (0) 2012.12.04

WRITTEN BY
빨강꼬마

,

이전까지 프로젝트 진행함.

--------------------------------------------------------------------------------



프로젝트 생성 후 환경설정 시작


- DBConn.java

- ojdbc14.jar

- standerd.jer

- jstl.jar



--------------------------------------------------------------------------------

Servlet(서블릿)


1. 서블릿은 Sun사에서 내놓은 웹프로그래밍 언어의 한 종류. Java 언어를 기반으로 동적인 컨텐츠를 생성.


2. Java 코드안에 HTML 코드가 혼재되어 있다.


3. 서블릿은 Servlet 인터페이스를 구현하여 GenericServlet을 만들고 이를 다시

   http 프로토콜에 맞게 확장한 HttpServlet 클래스를 상속한 후 내부 메서드를 재성의(오버라이딩)하여 사용한다.


4. 서블릿의 동작 순서

- 클라이언트의 요청 (서블릿 주소)

- 서블릿 Handler 8080 포트에서 요청 받음.

- 서블릿 컨테이너에서 해당 서블릿 검색

- 해당 서블릿 실행

- 서블릿의 결과인 HTML 도큐먼트를 웹클라이언트에서 출력(웹페이지).


5. Deployment Descripter(배치 기술서)

- 환경 설정 파일.

- web.xml

- 서블릿 맵핑

- 패키지를 포함한 클래스명 과 경로 패턴은 동일할 필요는 없음.

- 서블릿 이름은 위와 아래가 동일해야함.



<servlet>

<servlet-name>서블릿 이름</servlet-name>

<setvlet-class>패키지를 포함한 클래스명</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>서블릿 이름</servlet-name>

<url-pattern>경로 패턴</url-pattern>

</servlet-mapping>


----------------------------------예)

WEB.XML 내 서블릿 맵핑 작업


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <servlet>

<servlet-name>servlet01</servlet-name>

<servlet-class>com.test.Servlet01</servlet-class>

  </servlet>

  <servlet-mapping>

<servlet-name>servlet01</servlet-name>

    <url-pattern>/Servlet01</url-pattern>

  </servlet-mapping>


</web-app>





* 맵핑을 해야 서블릿 요청이 가능함.

* HttpServlet 클래스를 상속받은 클래스를 서블릿이라 부름.

* doGET, doPOST 가 먼저 호출



WEB.XML에서 서블릿 맵핑후 실제 실행 주소

http://localhost:8090/Servlet_20121203/Servlet01




-----------------------------------------------------------------------

첫 번째 서블릿 클래스 작성


//Servlet01.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet01 extends HttpServlet {

private static final long serialVersionUID = 1L;


//사용자 요청이 GET방식인 경우 자동 호출

//브라우저에 요청한 주소는 GET 방식.

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//HTML 도큐먼트 동적 생성 코드 작성

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<title>");

out.println("</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>Hello, Servlet World!</div>");

out.println("</body>");

out.println("</html>");

}


//사용자 요청이 POST인 경우 자동 호출

//<form action="" method="post"></form> 태그를 이용한 요청

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO Auto-generated method stub

super.doPost(req, resp);

}


}


실행 주소

http://localhost:8090/Servlet_20121203/Servlet01



-----------------------------------------------------------

서블릿과 JSP 비교


//Servlet02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String str = "Hello, JSP World!";

%>    

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h3><%=str%></h3>

</div>

</body>

</html>



//eclipse_source\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Servlet_20121203\org\apache\jsp\Servlet02_jsp.java

//JSP 소스 코드가 서블릿으로 변환된 모습

//Servlet02_jsp.java

package org.apache.jsp;


import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;


public final class Servlet02_jsp extends org.apache.jasper.runtime.HttpJspBase

    implements org.apache.jasper.runtime.JspSourceDependent {


  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();


  private static java.util.List _jspx_dependants;


  private javax.el.ExpressionFactory _el_expressionfactory;

  private org.apache.AnnotationProcessor _jsp_annotationprocessor;


  public Object getDependants() {

    return _jspx_dependants;

  }


  public void _jspInit() {

    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();

    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());

  }


  public void _jspDestroy() {

  }


  public void _jspService(HttpServletRequest request, HttpServletResponse response)

        throws java.io.IOException, ServletException {


    PageContext pageContext = null;

    HttpSession session = null;

    ServletContext application = null;

    ServletConfig config = null;

    JspWriter out = null;

    Object page = this;

    JspWriter _jspx_out = null;

    PageContext _jspx_page_context = null;



    try {

      response.setContentType("text/html; charset=EUC-KR");

      pageContext = _jspxFactory.getPageContext(this, request, response,

      null, true, 8192, true);

      _jspx_page_context = pageContext;

      application = pageContext.getServletContext();

      config = pageContext.getServletConfig();

      session = pageContext.getSession();

      out = pageContext.getOut();

      _jspx_out = out;


      out.write('\r');

      out.write('\n');


String str = "Hello, JSP World!";


      out.write("    \r\n");

      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");

      out.write("<html>\r\n");

      out.write("<head>\r\n");

      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">\r\n");

      out.write("<title>Insert title here</title>\r\n");

      out.write("</head>\r\n");

      out.write("<body>\r\n");

      out.write("<div>\r\n");

      out.write("\t<h3>");

      out.print(str);

      out.write("</h3>\r\n");

      out.write("</div>\r\n");

      out.write("</body>\r\n");

      out.write("</html>");

    } catch (Throwable t) {

      if (!(t instanceof SkipPageException)){

        out = _jspx_out;

        if (out != null && out.getBufferSize() != 0)

          try { out.clearBuffer(); } catch (java.io.IOException e) {}

        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);

        else log(t.getMessage(), t);

      }

    } finally {

      _jspxFactory.releasePageContext(_jspx_page_context);

    }

  }

}




---------------------------------------------------------------------------------------

문제) 반복문을 이용해서 1~100 사이의 짝수만 출력. Servlet 이용.

* 서블릿 클래스 작성 - HttpServlet 클래스 상속한 클래스

* 서블릿 맵핑 - web.xml - 웹서버 재실행 필요.


---------------------------------------------------------------------------------------

//Servlet03.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet03 extends HttpServlet {


//사용자 요청이 GET방식인 경우 자동 호출

//브라우저에 요청한 주소는 GET 방식.

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

StringBuilder str = new StringBuilder();

for (int a=2; a<=100; a+=2) {

str.append(String.format("%d<br>",a));

}

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


//사용자 요청이 POST인 경우 자동 호출

//<form action="" method="post"></form> 태그를 이용한 요청

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


}



}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Servlet01</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Servlet01</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>servlet03</servlet-name>

<servlet-class>com.test.Servlet03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet03</servlet-name>

<url-pattern>/Servlet03</url-pattern>

</servlet-mapping>


</web-app>



----------------------------------------------------------------

문제) 반복문을 이용해서 1~100 사이의 짝수만 출력. 

마지막에 짝수들의 합까지 출력. JSP 이용.

실행 예)

2

4

6

8

...


100

------

합계:2550



//Servlet04.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet04 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


StringBuilder str = new StringBuilder();

int sum = 0;


for (int a=1; a<=100; a++) {

if (a%2 == 0) {

str.append(String.format("%d<br>", a));

sum += a;

}

}

str.append(String.format("----------<br>합계: %d", sum));


//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO Auto-generated method stub

super.doPost(req, resp);

}


}




-----------

데이터 송수신 테스트1 (텍스트 박스 객체)



//Send01.jsp -> 입력 페이지 역할. 입력된 데이터를 서버로 전송.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if (name.value == "" || tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h2> 데이터 전송 테스트1</h2>

<!-- action 속성에 서블릿 주소로 표기할 것 -->

<form action="Receive01" method="post">

이름 <input type="text" id="name" name="name"><br>

전화 <input type="text" id="tel" name="tel"><br>

<input type="button" value="전송" onclick="myFunc(this)">

<span id="msg" style="color:red; display:none">데이터 모두 입력해라~</span>

</form>

</div>

</body>

</html>


//Receive01.java -> 처리, 출력 페이지 역할. 클라이언트가 전송한 데이터 수신 및 처리. 결과 메시지를 클라이언트에게 전송.

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive01 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


//송수신 데이터에 한글이 포함된 경우이므로 아래의 명령 추가

req.setCharacterEncoding("euc-kr");

//데이터 수신

String name = req.getParameter("name");

String tel = req.getParameter("tel");

String str = String.format("%s %s", name, tel);

//결과출력

//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트1</h2>");

out.println("<h3>");

out.println(str);

out.println("</h3>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


}



//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>


<servlet>

<servlet-name>receive01</servlet-name>

<servlet-class>com.test.Receive01</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive01</servlet-name>

<url-pattern>/Receive01</url-pattern>

</servlet-mapping>


</web-app>


//요청주소

http://localhost:8090/Servlet_20121203/Send01.jsp


------------------------------------------------------------------------------------------

데이터 송수신 테스트2 

-> Send02, Receive02를 모두 서블릿으로 변경


//Send02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send02 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var name = document.getElementById(\"name\");");

out.println("var tel = document.getElementById(\"tel\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (name.value == \"\" || tel.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트2</h2>");

out.println("<form action=\"Receive02\" method=\"post\">");

out.println("이름 <input type=\"text\" id=\"name\" name=\"name\"><br>");

out.println("전화 <input type=\"text\" id=\"tel\" name=\"tel\"><br>");

out.println("<input type=\"button\" value=\"전송\" onclick=\"myFunc(this)\">");

out.println("<span id=\"msg\" style=\"color:red; display:none\">데이터 모두 입력해라~</span>");

out.println("</form>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


}

}




//Receive02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive02 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


//송수신 데이터에 한글이 포함된 경우이므로 아래의 명령 추가

req.setCharacterEncoding("euc-kr");

//데이터 수신

String name = req.getParameter("name");

String tel = req.getParameter("tel");

String str = String.format("이름:%s 전화번호:%s", name, tel);

//결과출력

//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트2</h2>");

out.println("<h3>");

out.println(str);

out.println("</h3>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

 

<servlet>

<servlet-name>send02</servlet-name>

<servlet-class>com.test.Send02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send02</servlet-name>

<url-pattern>/Send02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>receive02</servlet-name>

<servlet-class>com.test.Receive02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive02</servlet-name>

<url-pattern>/Receive02</url-pattern>

</servlet-mapping>


</web-app>



//요청주소

http://localhost:8090/Servlet_20121203/Send02


------------------------------------------------------------------------------------------

문제) 거스름돈을 환폐단위로 구분해서 출력. 서블릿 이용.

실행 예)


금액(10~1000) [990  ]  [결과]


총액 : 990원

오백원 1개, 백원 4개, 오십원 1개, 십원 4개


//Send03.java


//Receive03.java


//web.xml



---------------------------------------

데이터 송수신 테스트3 (라디오 객체)


//Send04.java


//Receive04.java


//web.xml



---------------------------------------

데이터 송수신 테스트4 (체크박스 객체)



//Send05.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send05 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}

protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("");

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var checkboxes = document.getElementsByName(\"icecream\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("var check = false;");

out.println("for (var a=0; a<checkboxes.length; a++) {");

out.println("if (checkboxes[a].checked) {");

out.println("check = true;");

out.println("}");

out.println("}");

out.println("if (check) {");

out.println("obj.form.submit();");

out.println("} else {");

out.println("msg.style.display = \"inline\";");

out.println("}");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트4</h2>");

out.println("<form action=\"Receive05\" method=\"post\">");

out.println("- 종류 선택 -<br><br>");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"1\"> 고스트월드");     

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"2\"> 엄마는 외계인"); 

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"3\"> 바나나몬스터<br>");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"4\"> 초코라떼크런치 ");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"5\"> 뉴욕치즈케익 ");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"6\"> 슈팅스타<br>");

out.println("<input type=\"button\" value=\"확인\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">종류를 선택해야 합니다.</span>");

out.println("</form>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


}




//Receive05.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive05 extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}

protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String[] array = req.getParameterValues("icecream");

StringBuilder str = new StringBuilder();

String[] icecreamName = {"고스트월드", "엄마는 외계인", "바나나몬스터", "초코라떼크런치", "뉴욕치즈케익", "슈팅스타"};

for (String icecream : array) {

str.append(String.format("<li>%s</li>",icecreamName[Integer.parseInt(icecream)-1]));

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트3</h2>");

out.println("<h3>출력 ------------</h3>");

out.println("<div>선택한 종류는<ol>");

out.println(str);

out.println("</ol>입니다.</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");


}

}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Servlet01</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Servlet01</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>servlet03</servlet-name>

<servlet-class>com.test.Servlet03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet03</servlet-name>

<url-pattern>/Servlet03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>servlet04</servlet-name>

<servlet-class>com.test.Servlet04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet04</servlet-name>

<url-pattern>/Servlet04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive01</servlet-name>

<servlet-class>com.test.Receive01</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive01</servlet-name>

<url-pattern>/Receive01</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send02</servlet-name>

<servlet-class>com.test.Send02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send02</servlet-name>

<url-pattern>/Send02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>receive02</servlet-name>

<servlet-class>com.test.Receive02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive02</servlet-name>

<url-pattern>/Receive02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>send03</servlet-name>

<servlet-class>com.test.Send03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send03</servlet-name>

<url-pattern>/Send03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive03</servlet-name>

<servlet-class>com.test.Receive03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive03</servlet-name>

<url-pattern>/Receive03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send04</servlet-name>

<servlet-class>com.test.Send04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send04</servlet-name>

<url-pattern>/Send04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive04</servlet-name>

<servlet-class>com.test.Receive04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive04</servlet-name>

<url-pattern>/Receive04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send05</servlet-name>

<servlet-class>com.test.Send05</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send05</servlet-name>

<url-pattern>/Send05</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive05</servlet-name>

<servlet-class>com.test.Receive05</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive05</servlet-name>

<url-pattern>/Receive05</url-pattern>

</servlet-mapping>


</web-app>


----------------------------------------------------------------------------------------------

문제) 임의의 수를 입력 받아서 3의 배수, 4의 배수로 구분해서 출력.


실행 예)

임의의 정수(3 또는 4의 배수) [3  ] [결과]


입력받은 숫자 : 3

구분 : 3의 배수



//Send_Receive06.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send_Receive06 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String num = req.getParameter("num");

StringBuilder str = new StringBuilder();

int data = Integer.parseInt(num);

        String s = "3 또는 4의 배수가 아닙니다.";

if ((data % 3) == 0) {

            s = "3의 배수";

        }

if ((data % 4) == 0) {

          s = "4의 배수";

      }

      if ((data % 12) == 0) {

          s = "3 또는 4의 배수";

      }

     

        str.append(String.format("입력 받은 숫자 : %s<br>", num));

       str.append(String.format("구분 : %s<br>", s));        

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}



//web.xml


----------------------------------------------------------------------------------------------------

문제) 임의의 수를 입력 받아서 3의 배수, 4의 배수로 구분해서 출력.


실행 예)

임의의 정수(3 또는 4의 배수) [3  ] [결과]


입력받은 숫자 : 3

구분 : 3의 배수



//Send_Receive06.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send_Receive07 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGetPost(req, resp);

}


protected void doGetPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String num = req.getParameter("num");

StringBuilder str = new StringBuilder();

if (num == null) {

str.append("");

} else {

int data = Integer.parseInt(num);

        String s = "3 또는 4의 배수가 아닙니다.";

if ((data % 3) == 0) {

            s = "3의 배수";

      }

if ((data % 4) == 0) {

        s = "4의 배수";

      }

      if ((data % 12) == 0) {

          s = "3 또는 4의 배수";

    }

    

        str.append(String.format("입력 받은 숫자 : %s<br>", num));

       str.append(String.format("구분 : %s<br>", s));

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println("</div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}



//web.xml


---------------------------------------------------------------------------------------

문제) 세 개의 숫자를 전달 받아서 그 중에서  가장 큰 숫자, 가장 작은 숫자 구하기. 서블릿 이용.


실행 예)

숫자1 [OO  ]   숫자2 [XX  ]   숫자3 [YY  ]   [결과]


입력 받은 숫자 : OO, XX, YY

가장 큰 숫자 :  OO

가장 작은 숫자 :  YY


//Send_Receive08.java



//web.xml


WRITTEN BY
빨강꼬마

,

--------------------------------

로그인, 로그아웃


1. Session 객체. JSP의 내장 객체 중에서 한 종류.


2. JSP 내장 객체. 객체 생성 과정 없이 바로 사용 가능한 객체.

- request

- response

- out

- session


JSP (JSP 문법 코드) -> (자동 컴파일) -> Servlet (순수 자바 소스 코드)

-> request는 HttpServletRequest 객체로 생성되는 과정이 자동 포함됨.

response는 HttpServletResponse 객체로 생성되는 과정이 자동 포함됨.


3. session 객체는 JSP 페이지에 대해서 독립적인 저장소 역할.


JSP 내부에서 변수 선언시 -> 지역 변수

다른 JSP에서 변수의 값을 사용하려면?

-> 데이터 송수신 과정 필요. 1 대 1만 가능.


로그인 정보처럼 여러 페이지에 인식해야 되는 정보는 송수신 과정으로는 처리 불가능.

-> 독립적인 저장소 필요 -> 세션


4. session.setAttribute(), session.getAttribute(), session.removeAttribute()


--------------------------------------------

JSTL 기능 구현


1. standard.jar, jstl.jar 파일을 프로젝트의 WebContent>WEB-INF>lib 폴더에 복사할 것.


2. import 구문 사용 가능

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<c:import url="JSP 파일"></c:import>


3. if 구문 사용 가능. else 표현은 없다. 조건식은 표현식으로 구성.

<c:if test="조건"></c:if>



--------------------------------------------

직원관리 (JSP버전) 최종 소스 코드



----------------------------------------------

//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}




----------------------------------------------

//EmployeeDTO.java

package com.test;


public class EmployeeDTO {

//멤버변수

private int emp_id, city_id, buseo_id, jikwi_id;

private int min_basicpay, basicpay, sudang, pay;

private String ibsadate; //날짜지만 문자열로 취급

private String name, ssn, city, buseo, jikwi, tel;

//getter, setter

public int getEmp_id() {

return emp_id;

}

public void setEmp_id(int emp_id) {

this.emp_id = emp_id;

}

public int getCity_id() {

return city_id;

}

public void setCity_id(int city_id) {

this.city_id = city_id;

}

public int getBuseo_id() {

return buseo_id;

}

public void setBuseo_id(int buseo_id) {

this.buseo_id = buseo_id;

}

public int getJikwi_id() {

return jikwi_id;

}

public void setJikwi_id(int jikwi_id) {

this.jikwi_id = jikwi_id;

}

public int getMin_basicpay() {

return min_basicpay;

}

public void setMin_basicpay(int min_basicpay) {

this.min_basicpay = min_basicpay;

}

public int getBasicpay() {

return basicpay;

}

public void setBasicpay(int basicpay) {

this.basicpay = basicpay;

}

public int getSudang() {

return sudang;

}

public void setSudang(int sudang) {

this.sudang = sudang;

}

public int getPay() {

return pay;

}

public void setPay(int pay) {

this.pay = pay;

}

public String getIbsadate() {

return ibsadate;

}

public void setIbsadate(String ibsadate) {

this.ibsadate = ibsadate;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSsn() {

return ssn;

}

public void setSsn(String ssn) {

this.ssn = ssn;

}

public String getCity() {

return city;

}

public void setCity(String city) {

this.city = city;

}

public String getBuseo() {

return buseo;

}

public void setBuseo(String buseo) {

this.buseo = buseo;

}

public String getJikwi() {

return jikwi;

}

public void setJikwi(String jikwi) {

this.jikwi = jikwi;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}





----------------------------------------------

//CityDTO.java

package com.test;


public class CityDTO {

private int city_id;

private String city;

public int getCity_id() {

return city_id;

}

public void setCity_id(int city_id) {

this.city_id = city_id;

}

public String getCity() {

return city;

}

public void setCity(String city) {

this.city = city;

}

}





----------------------------------------------

//BuseoDTO.java

package com.test;


public class BuseoDTO {

private int buseo_id;

private String buseo;

public int getBuseo_id() {

return buseo_id;

}

public void setBuseo_id(int buseo_id) {

this.buseo_id = buseo_id;

}

public String getBuseo() {

return buseo;

}

public void setBuseo(String buseo) {

this.buseo = buseo;

}

}





----------------------------------------------

//JikwiDTO.java

package com.test;


public class JikwiDTO {

private int jikwi_id;

private String jikwi;

public int getJikwi_id() {

return jikwi_id;

}

public void setJikwi_id(int jikwi_id) {

this.jikwi_id = jikwi_id;

}

public String getJikwi() {

return jikwi;

}

public void setJikwi(String jikwi) {

this.jikwi = jikwi;

}

}





----------------------------------------------

//EmployeeDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class EmployeeDAO {


private Connection conn;


public void connect() 

throws SQLException, ClassNotFoundException{

conn = DBConn.getConnection();


}


public void close()

throws SQLException {

DBConn.close();

conn = null;

}



public ArrayList<EmployeeDTO> cityList()

throws SQLException {


ArrayList<EmployeeDTO> arrayList 

= new ArrayList<EmployeeDTO>();


String sql = String.format("SELECT city_id, city FROM city ORDER BY city_id");


Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

EmployeeDTO dto = new EmployeeDTO();

dto.setCity_id(rs.getInt("city_id"));

dto.setCity(rs.getString("city"));


arrayList.add(dto);

}


rs.close();


return arrayList;

}


public ArrayList<EmployeeDTO> buseoList()

throws SQLException {


ArrayList<EmployeeDTO> arrayList 

= new ArrayList<EmployeeDTO>();


String sql = String.format("SELECT buseo_id, buseo FROM buseo ORDER BY buseo_id");


Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

EmployeeDTO dto = new EmployeeDTO();

dto.setBuseo_id(rs.getInt("buseo_id"));

dto.setBuseo(rs.getString("buseo"));


arrayList.add(dto);

}


rs.close();


return arrayList;

}


public ArrayList<EmployeeDTO> jikwiList()

throws SQLException {


ArrayList<EmployeeDTO> arrayList 

= new ArrayList<EmployeeDTO>();


String sql = String.format("SELECT jikwi_id, jikwi FROM jikwi ORDER BY jikwi_id");


Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

EmployeeDTO dto = new EmployeeDTO();

dto.setJikwi_id(rs.getInt("jikwi_id"));

dto.setJikwi(rs.getString("jikwi"));


arrayList.add(dto);

}


rs.close();


return arrayList;

}


public int minBasicPay(int jikwi_id) 

throws SQLException {

int result=0;

String sql = String.format("SELECT min_basicpay FROM jikwi WHERE jikwi_id = %d", jikwi_id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

result = rs.getInt("min_basicpay");

}


rs.close();

return result;

}


public ArrayList<EmployeeDTO> lists(String orders)

throws SQLException {

ArrayList<EmployeeDTO> arrayList

= new ArrayList<EmployeeDTO>();

String sql = String.format("SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay, sudang, pay FROM empView %s", orders);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

EmployeeDTO dto = new EmployeeDTO();

dto.setEmp_id(rs.getInt("emp_id"));

dto.setName(rs.getString("name"));

dto.setSsn(rs.getString("ssn"));

dto.setIbsadate(rs.getString("ibsadate"));

//dto.setCity_id(rs.getInt("city_id"));

dto.setCity(rs.getString("city"));

dto.setTel(rs.getString("tel"));

//dto.setBuseo_id(rs.getInt("buseo_id"));

dto.setBuseo(rs.getString("buseo"));

//dto.setJikwi_id(rs.getInt("jikwi_id"));

dto.setJikwi(rs.getString("jikwi"));

dto.setBasicpay(rs.getInt("basicpay"));

dto.setSudang(rs.getInt("sudang"));

dto.setPay(rs.getInt("pay"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<EmployeeDTO> empLists(String orders)

throws SQLException {

ArrayList<EmployeeDTO> arrayList

= new ArrayList<EmployeeDTO>();

String sql = String.format("SELECT emp_id, name, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi FROM employeeView %s", orders);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

EmployeeDTO dto = new EmployeeDTO();

dto.setEmp_id(rs.getInt("emp_id"));

dto.setName(rs.getString("name"));

dto.setIbsadate(rs.getString("ibsadate"));

//dto.setCity_id(rs.getInt("city_id"));

dto.setCity(rs.getString("city"));

dto.setTel(rs.getString("tel"));

//dto.setBuseo_id(rs.getInt("buseo_id"));

dto.setBuseo(rs.getString("buseo"));

//dto.setJikwi_id(rs.getInt("jikwi_id"));

dto.setJikwi(rs.getString("jikwi"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM emp");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

public int add(EmployeeDTO dto)

throws SQLException {

int result =0;

String sql = String.format("INSERT INTO emp (emp_id, name, ssn, ibsadate, city_id, tel, buseo_id, jikwi_id, basicpay, sudang) VALUES (empSeq.nextval, '%s', '%s', '%s', %d, '%s', %d, %d, %d, %d)"

, dto.getName()

, dto.getSsn()

, dto.getIbsadate()

, dto.getCity_id()

, dto.getTel()

, dto.getBuseo_id()

, dto.getJikwi_id()

, dto.getBasicpay()

, dto.getSudang());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}


public int count(String wheres)

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM empView %s", wheres);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

public ArrayList<EmployeeDTO> searchLists(String wheres, String orders)

throws SQLException {

ArrayList<EmployeeDTO> arrayList

= new ArrayList<EmployeeDTO>();

String sql = String.format("SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay, sudang, pay FROM empView %s %s", wheres, orders);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

EmployeeDTO dto = new EmployeeDTO();

dto.setEmp_id(rs.getInt("emp_id"));

dto.setName(rs.getString("name"));

dto.setSsn(rs.getString("ssn"));

dto.setIbsadate(rs.getString("ibsadate"));

dto.setCity_id(rs.getInt("city_id"));

dto.setCity(rs.getString("city"));

dto.setTel(rs.getString("tel"));

dto.setBuseo_id(rs.getInt("buseo_id"));

dto.setBuseo(rs.getString("buseo"));

dto.setJikwi_id(rs.getInt("jikwi_id"));

dto.setJikwi(rs.getString("jikwi"));

dto.setBasicpay(rs.getInt("basicpay"));

dto.setSudang(rs.getInt("sudang"));

dto.setPay(rs.getInt("pay"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<EmployeeDTO> empSearchLists(String wheres, String orders)

throws SQLException {

ArrayList<EmployeeDTO> arrayList

= new ArrayList<EmployeeDTO>();

String sql = String.format("SELECT emp_id, name, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi FROM employeeView %s %s", wheres, orders);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

EmployeeDTO dto = new EmployeeDTO();

dto.setEmp_id(rs.getInt("emp_id"));

dto.setName(rs.getString("name"));

dto.setIbsadate(rs.getString("ibsadate"));

dto.setCity_id(rs.getInt("city_id"));

dto.setCity(rs.getString("city"));

dto.setTel(rs.getString("tel"));

dto.setBuseo_id(rs.getInt("buseo_id"));

dto.setBuseo(rs.getString("buseo"));

dto.setJikwi_id(rs.getInt("jikwi_id"));

dto.setJikwi(rs.getString("jikwi"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


public int modify(EmployeeDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE emp SET name='%s', ssn='%s', ibsadate='%s', city_id=%d, tel='%s', buseo_id=%d, jikwi_id=%d, basicpay=%d, sudang=%d WHERE emp_id=%d", dto.getName(), dto.getSsn(), dto.getIbsadate(), dto.getCity_id(), dto.getTel(), dto.getBuseo_id(), dto.getJikwi_id(), dto.getBasicpay(), dto.getSudang(), dto.getEmp_id());

System.out.println(sql);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int emp_id)

throws SQLException {

int result = 0;

String sql = String.format("DELETE emp WHERE emp_id=%d", emp_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int loginEmp(String id, String pw)

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM emp WHERE name='%s' AND SUBSTR(ssn, 8, 7)='%s'", id, pw);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

public int loginAdmin(String id, String pw)

throws SQLException {

int result = 0;


String sql = String.format("SELECT COUNT(*) AS count FROM empAdmin WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

}





----------------------------------------------

//CityDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class CityDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String city)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO city (city_id, city) VALUES (citySeq.nextval, '%s')", city);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<CityDTO> lists()

throws SQLException  {

ArrayList<CityDTO> arrayList

= new ArrayList<CityDTO>();

String sql = String.format("SELECT city_id, city FROM city ORDER BY city_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int city_id = rs.getInt("city_id");

String city = rs.getString("city");

CityDTO dto = new CityDTO();

dto.setCity_id(city_id);

dto.setCity(city);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<CityDTO> search(String key, String value)

throws SQLException  {

ArrayList<CityDTO> arrayList

= new ArrayList<CityDTO>();

return arrayList;

}*/

public int modify(CityDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE city SET city='%s' WHERE city_id=%d", dto.getCity(), dto.getCity_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int city_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE city WHERE city_id=%d", city_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}





----------------------------------------------

//BuseoDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class BuseoDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String buseo)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO buseo (buseo_id, buseo) VALUES (buseoSeq.nextval, '%s')", buseo);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<BuseoDTO> lists()

throws SQLException  {

ArrayList<BuseoDTO> arrayList

= new ArrayList<BuseoDTO>();

String sql = String.format("SELECT buseo_id, buseo FROM buseo ORDER BY buseo_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int buseo_id = rs.getInt("buseo_id");

String buseo = rs.getString("buseo");

BuseoDTO dto = new BuseoDTO();

dto.setBuseo_id(buseo_id);

dto.setBuseo(buseo);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<BuseoDTO> search(String key, String value)

throws SQLException  {

ArrayList<BuseoDTO> arrayList

= new ArrayList<BuseoDTO>();

return arrayList;

}*/

public int modify(BuseoDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE buseo SET buseo='%s' WHERE buseo_id=%d", dto.getBuseo(), dto.getBuseo_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int buseo_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE buseo WHERE buseo_id=%d", buseo_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}





----------------------------------------------

//JikwiDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class JikwiDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String jikwi)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jikwi (jikwi_id, jikwi) VALUES (jikwiSeq.nextval, '%s')", jikwi);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<JikwiDTO> lists()

throws SQLException  {

ArrayList<JikwiDTO> arrayList

= new ArrayList<JikwiDTO>();

String sql = String.format("SELECT jikwi_id, jikwi FROM jikwi ORDER BY jikwi_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int jikwi_id = rs.getInt("jikwi_id");

String jikwi = rs.getString("jikwi");

JikwiDTO dto = new JikwiDTO();

dto.setJikwi_id(jikwi_id);

dto.setJikwi(jikwi);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<JikwiDTO> search(String key, String value)

throws SQLException  {

ArrayList<JikwiDTO> arrayList

= new ArrayList<JikwiDTO>();

return arrayList;

}*/

public int modify(JikwiDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE jikwi SET jikwi='%s' WHERE jikwi_id=%d", dto.getJikwi(), dto.getJikwi_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int jikwi_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE jikwi WHERE jikwi_id=%d", jikwi_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}




----------------------------------------------

//BasicStyle.css -> CSS 스타일 시트 전용.

@CHARSET "EUC-KR";


body {

color:#2f3743;

}


a { /* a 태그에만 적용 */

text-decoration: none; /* 글자의 장식 지정 없앰 */

color:gray; /* 글자색 */

}


a:hover { /* a 태그에 커서가 올려져 있을때만 적용 */

text-decoration: underline; /* 밑줄 장식 지정 */

color:red;

}


table.style00 td, table.style00 th 

{

padding: 3px;

border-right-style: solid;

border-bottom-style: solid;

border-width: 1px;

border-color: #6980b8;

}


table.style00 td:hover 

{

background-color:#d2d2d2;

}


.style1 {   /* class 속성의 값이 style1인 경우만 적용 */

text-align:center; /* 가운데 정렬 */

}


.style2 {   /* class 속성의 값이 style2인 경우만 적용 */

text-align:right; /* 오른쪽 정렬 */

}


#result {

overflow:auto;  /* DIV 태그 내부에 스크롤 생성 */ 

height:300px;

}





----------------------------------------------

//LoginForm.jsp  -> 로그인 페이지. ID, PW 확인 및 세션 처리

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

String result = "false";

request.setCharacterEncoding("euc-kr");

String group = request.getParameter("group");

String id = request.getParameter("id");

String pw = request.getParameter("pw");

if (id != null && pw != null) {

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

//ID, PW 검사 과정

int count = 0;

if (group.equals("admin")) {

count = dao.loginAdmin(id, pw);

} else if (group.equals("emp")) {

count = dao.loginEmp(id, pw);

}

//결과는 두 가지

if (count == 1) {

//로그인 성공 -> 세션 객체 생성 -> 화면 전환

//세션 

//-> 로그인 성공 여부 확인용

//-> 직원 확인용

//-> 관리자 확인용

session.setAttribute("loginCheck", "true");

if (group.equals("admin")) {

session.setAttribute("admin", id);

} else if (group.equals("emp")) {

session.setAttribute("emp", id);

}

response.sendRedirect("Employee_Select.jsp");

} else {

//로그인 실패 -> 현재 화면에서 에러 메시지 출력

result = "true";

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP 버전)</title>


<script type="text/javascript">

function myFunc(obj) {

//문제) 데이터 검사 과정 추가할 것.

//데이터 전송

obj.form.submit();

}

function msg() {

if (<%=result%>) {

alert("아이디 또는 패스워드가 틀렸습니다.");

}

}


</script>


</head>

<body onload="msg()">

<div align="center" style="padding-top:100px;">


<form method="post">


<h1>직원관리 (JSP버전)</h1>

<input type="radio"

name="group" value="admin"> 관리자

<input type="radio"

name="group" 

checked="checked"

value="emp"> 일반직원

<table class="style4">

<tr>

<td valign="middle">

<img src="img/img_login.gif">

</td>

<td>

<table>

<tr>

<td>ID</td>

<td><input type="text" style="width:150px;" id="id" name="id"></td>

</tr>

<tr>

<td>PW</td>

<td><input type="password" style="width:150px;" id="pw" name="pw"></td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="button" value="로그인"

onclick="myFunc(this)">

<br>

<span id="msg" style="color:red; display:none;">에러메시지 출력 영역</span>

</td>

</tr>

</table>

</td>

</tr>

</table>

</form>

</div>

</body>

</html>




----------------------------------------------

//Logout.jsp -> 로그아웃 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//세션 개별 소멸

//session.removeAttribute("loginCheck");

//session.removeAttribute("admin");

//session.removeAttribute("emp");


//세션 전체 소멸

session.invalidate();

response.sendRedirect("LoginForm.jsp");

%>




----------------------------------------------

//MainMenu.jsp -> 메인 메뉴 전용.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

<c:if test="${!empty sessionScope.admin}">

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

</c:if>

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>    





----------------------------------------------

//City.jsp -> 지역관리. 입력, 출력, 수정, 삭제 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


CityDAO dao = new CityDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

CityDTO dto = new CityDTO();

dto.setCity_id(Integer.parseInt(num));

dto.setCity(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (CityDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getCity_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function cityForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_지역관리</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

지역번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">지역번호를 입력해야 합니다.</span><br>

지역이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">지역이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:cityForm('insert')">지역추가</a>]

[<a href="javascript:cityForm('update')">지역수정</a>]

[<a href="javascript:cityForm('delete')">지역삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>지역</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




----------------------------------------------

//Buseo.jsp -> 부서관리. 입력, 출력, 수정, 삭제 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


BuseoDAO dao = new BuseoDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

BuseoDTO dto = new BuseoDTO();

dto.setBuseo_id(Integer.parseInt(num));

dto.setBuseo(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (BuseoDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getBuseo_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function buseoForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_부서관리</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

부서번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">부서번호를 입력해야 합니다.</span><br>

부서이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">부서이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:buseoForm('insert')">부서추가</a>]

[<a href="javascript:buseoForm('update')">부서수정</a>]

[<a href="javascript:buseoForm('delete')">부서삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>부서</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




----------------------------------------------

//Jikwi.jsp -> 직위관리. 입력, 출력, 수정, 삭제 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


JikwiDAO dao = new JikwiDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

JikwiDTO dto = new JikwiDTO();

dto.setJikwi_id(Integer.parseInt(num));

dto.setJikwi(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (JikwiDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getJikwi_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function jikwiForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_직위관리</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

직위번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">직위번호를 입력해야 합니다.</span><br>

직위이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">직위이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:jikwiForm('insert')">직위추가</a>]

[<a href="javascript:jikwiForm('update')">직위수정</a>]

[<a href="javascript:jikwiForm('delete')">직위삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>직위</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




----------------------------------------------

//Employee_Select.jsp -> 직원관리. 출력 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>

<%


//로그인 여부 확인

if (session.getAttribute("loginCheck") == null) {

response.sendRedirect("LoginForm.jsp");

}


String order = request.getParameter("order");

if (order == null) {

order = "emp_id";

}

String direction = request.getParameter("direction");

if (direction == null) {

direction = "asc";

}

//제목을 기준으로 정렬시키기 위해서 추가한 부분

String urlEmp_id = "";

String urlName = "";

String urlSsn = "";

String urlIbsadate = "";

String urlCity = "";

String urlTel = "";

String urlBuseo = "";

String urlJikwi = "";

String urlBasicpay = "";

String urlSudang = "";

String urlPay = "";

//제목을 기준으로 정렬시키기 위해서 추가한 부분

if (order.equals("emp_id") && direction.equals("asc")) {

urlEmp_id = "Employee_Select.jsp?order=emp_id&direction=desc";

} else {

urlEmp_id = "Employee_Select.jsp?order=emp_id&direction=asc";

}

if (order.equals("name") && direction.equals("asc")) {

urlName = "Employee_Select.jsp?order=name&direction=desc";

} else {

urlName = "Employee_Select.jsp?order=name&direction=asc";

}

if (order.equals("ssn") && direction.equals("asc")) {

urlSsn = "Employee_Select.jsp?order=ssn&direction=desc";

} else {

urlSsn = "Employee_Select.jsp?order=ssn&direction=asc";

}

if (order.equals("ibsadate") && direction.equals("asc")) {

urlIbsadate = "Employee_Select.jsp?order=ibsadate&direction=desc";

} else {

urlIbsadate = "Employee_Select.jsp?order=ibsadate&direction=asc";

}

if (order.equals("city") && direction.equals("asc")) {

urlCity = "Employee_Select.jsp?order=city&direction=desc";

} else {

urlCity = "Employee_Select.jsp?order=city&direction=asc";

}

if (order.equals("tel") && direction.equals("asc")) {

urlTel = "Employee_Select.jsp?order=tel&direction=desc";

} else {

urlTel = "Employee_Select.jsp?order=tel&direction=asc";

}

if (order.equals("buseo") && direction.equals("asc")) {

urlBuseo = "Employee_Select.jsp?order=buseo&direction=desc";

} else {

urlBuseo = "Employee_Select.jsp?order=buseo&direction=asc";

}

if (order.equals("jikwi") && direction.equals("asc")) {

urlJikwi = "Employee_Select.jsp?order=jikwi&direction=desc";

} else {

urlJikwi = "Employee_Select.jsp?order=jikwi&direction=asc";

}

if (order.equals("basicpay") && direction.equals("asc")) {

urlBasicpay = "Employee_Select.jsp?order=basicpay&direction=desc";

} else {

urlBasicpay = "Employee_Select.jsp?order=basicpay&direction=asc";

}

if (order.equals("sudang") && direction.equals("asc")) {

urlSudang = "Employee_Select.jsp?order=sudang&direction=desc";

} else {

urlSudang = "Employee_Select.jsp?order=sudang&direction=asc";

}

if (order.equals("pay") && direction.equals("asc")) {

urlPay = "Employee_Select.jsp?order=pay&direction=desc";

} else {

urlPay = "Employee_Select.jsp?order=pay&direction=asc";

}


StringBuilder str = new StringBuilder();

String count = "0";

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

count = String.valueOf(dao.count());

String orders = String.format("ORDER BY %s %s", order, direction);

if (session.getAttribute("admin") != null) {

for (EmployeeDTO dto : dao.lists(orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

} else if (session.getAttribute("emp") != null) {

for (EmployeeDTO dto : dao.empLists(orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


</head>

<body>

<div>

<div>

<h2>직원관리_직원출력[<%=session.getAttribute("emp")%>]</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>


<div>

<h3>전체 직원수 : <%=count%>명</h3>

<div id="result">

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th><a href="<%=urlEmp_id%>">사번</a></th>

<th><a href="<%=urlName%>">이름</a></th>

<c:if test="${!empty sessionScope.admin}">

<th><a href="<%=urlSsn%>">주민번호</a></th>

</c:if>

<th><a href="<%=urlIbsadate%>">입사일</a></th>

<th><a href="<%=urlCity%>">지역</a></th>

<th><a href="<%=urlTel%>">전화번호</a></th>

<th><a href="<%=urlBuseo%>">부서</a></th>

<th><a href="<%=urlJikwi%>">직위</a></th>

<c:if test="${!empty sessionScope.admin}">

<th><a href="<%=urlBasicpay%>">기본급</a></th>

<th><a href="<%=urlSudang%>">수당</a></th>

<th><a href="<%=urlPay%>">급여</a></th>

</c:if>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</div>

</body>

</html>




----------------------------------------------

//Employee_Search.jsp -> 직원관리. 검색 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>

<%

//로그인 여부 확인

if (session.getAttribute("loginCheck") == null) {

response.sendRedirect("LoginForm.jsp");

}


request.setCharacterEncoding("euc-kr");

String key = request.getParameter("key");

if (key == null) {

key = "";

}

String value = request.getParameter("value");

if (value == null) {

value = "";

}


String order = request.getParameter("order");

if (order == null) {

order = "emp_id";

}

String direction = request.getParameter("direction");

if (direction == null) {

direction = "asc";

}

//제목을 기준으로 정렬시키기 위해서 추가한 부분

String urlEmp_id = "";

String urlName = "";

String urlSsn = "";

String urlIbsadate = "";

String urlCity = "";

String urlTel = "";

String urlBuseo = "";

String urlJikwi = "";

String urlBasicpay = "";

String urlSudang = "";

String urlPay = "";

//제목을 기준으로 정렬시키기 위해서 추가한 부분

if (order.equals("emp_id") && direction.equals("asc")) {

urlEmp_id = String.format("Employee_Search.jsp?order=emp_id&direction=desc&key=%s&value=%s", key, value);

} else {

urlEmp_id = String.format("Employee_Search.jsp?order=emp_id&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("name") && direction.equals("asc")) {

urlName = String.format("Employee_Search.jsp?order=name&direction=desc&key=%s&value=%s", key, value);

} else {

urlName = String.format("Employee_Search.jsp?order=name&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("ssn") && direction.equals("asc")) {

urlSsn = String.format("Employee_Search.jsp?order=ssn&direction=desc&key=%s&value=%s", key, value);

} else {

urlSsn = String.format("Employee_Search.jsp?order=ssn&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("ibsadate") && direction.equals("asc")) {

urlIbsadate = String.format("Employee_Search.jsp?order=ibsadate&direction=desc&key=%s&value=%s", key, value);

} else {

urlIbsadate = String.format("Employee_Search.jsp?order=ibsadate&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("city") && direction.equals("asc")) {

urlCity = String.format("Employee_Search.jsp?order=city&direction=desc&key=%s&value=%s", key, value);

} else {

urlCity = String.format("Employee_Search.jsp?order=city&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("tel") && direction.equals("asc")) {

urlTel = String.format("Employee_Search.jsp?order=tel&direction=desc&key=%s&value=%s", key, value);

} else {

urlTel = String.format("Employee_Search.jsp?order=tel&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("buseo") && direction.equals("asc")) {

urlBuseo = String.format("Employee_Search.jsp?order=buseo&direction=desc&key=%s&value=%s", key, value);

} else {

urlBuseo = String.format("Employee_Search.jsp?order=buseo&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("jikwi") && direction.equals("asc")) {

urlJikwi = String.format("Employee_Search.jsp?order=jikwi&direction=desc&key=%s&value=%s", key, value);

} else {

urlJikwi = String.format("Employee_Search.jsp?order=jikwi&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("basicpay") && direction.equals("asc")) {

urlBasicpay = String.format("Employee_Search.jsp?order=basicpay&direction=desc&key=%s&value=%s", key, value);

} else {

urlBasicpay = String.format("Employee_Search.jsp?order=basicpay&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("sudang") && direction.equals("asc")) {

urlSudang = String.format("Employee_Search.jsp?order=sudang&direction=desc&key=%s&value=%s", key, value);

} else {

urlSudang = String.format("Employee_Search.jsp?order=sudang&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("pay") && direction.equals("asc")) {

urlPay = String.format("Employee_Search.jsp?order=pay&direction=desc&key=%s&value=%s", key, value);

} else {

urlPay = String.format("Employee_Search.jsp?order=pay&direction=asc&key=%s&value=%s", key, value);

}


StringBuilder str = new StringBuilder();

String count = "0";

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

String wheres = String.format("WHERE %s='%s'", key, value);

String orders = String.format("ORDER BY %s %s", order, direction);


count = String.valueOf(dao.count(wheres));

if (session.getAttribute("admin") != null) {

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

} else if (session.getAttribute("emp") != null) {

for (EmployeeDTO dto : dao.empSearchLists(wheres,orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

//데이터 전송

myForm.submit();

}

function radioCheck() {

var obj = document.getElementById("<%=key%>");

obj.checked = true;

}

</script>


</head>

<body onload="radioCheck()">

<div>

<div>

<h2>직원관리_직원검색[<%=session.getAttribute("emp")%>]</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="get" id="myForm">

검색기준 

<input type="radio" name="key" value="emp_id" id="emp_id">사번

<input type="radio" name="key" value="name" id="name">이름

<input type="radio" name="key" value="city" id="city">지역

<input type="radio" name="key" value="buseo" id="buseo">부서

<input type="radio" name="key" value="jikwi" id="jikwi">직위

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

<span id="searchMsg" style="color:red;display:none;">검색 기준 또는 검색 단어를 채워야 합니다.</span>

</form>

<h3>검색 결과 직원수 : <%=count%>명</h3>

<div id="result">

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th><a href="<%=urlEmp_id%>">사번</a></th>

<th><a href="<%=urlName%>">이름</a></th>

<c:if test="${!empty sessionScope.admin}">

<th><a href="<%=urlSsn%>">주민번호</a></th>

</c:if>

<th><a href="<%=urlIbsadate%>">입사일</a></th>

<th><a href="<%=urlCity%>">지역</a></th>

<th><a href="<%=urlTel%>">전화번호</a></th>

<th><a href="<%=urlBuseo%>">부서</a></th>

<th><a href="<%=urlJikwi%>">직위</a></th>

<c:if test="${!empty sessionScope.admin}">

<th><a href="<%=urlBasicpay%>">기본급</a></th>

<th><a href="<%=urlSudang%>">수당</a></th>

<th><a href="<%=urlPay%>">급여</a></th>

</c:if>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</div>

</body>

</html>



----------------------------------------------

//MinBasicPayCheck.jsp -> 직원관리 입력 폼에서 직위 선택시 최소기본급을 리턴하는 전용 페이지. Ajax 요청 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

String jikwi_id = request.getParameter("jikwi_id");


EmployeeDAO dao = new EmployeeDAO();

int minBasicPay = 0;

try {

dao.connect();

minBasicPay = dao.minBasicPay(Integer.parseInt(jikwi_id));

}catch(Exception e) {

System.out.println(e.toString());

}finally{

dao.close();

}

out.write(String.format("%,d", minBasicPay));

%>





----------------------------------------------

//Employee_InsertForm.jsp -> 직원관리. 입력 폼 화면 구성. Ajax 요청 기능. jQuery 달력 기능.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>    

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


String insertOK = request.getParameter("insertOK");

if (insertOK == null) {

insertOK = "false";

}


StringBuilder cityLists = new StringBuilder();

StringBuilder buseoLists = new StringBuilder();

StringBuilder jikwiLists = new StringBuilder();


EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

for (EmployeeDTO dto : dao.cityList()) {

cityLists.append(String.format("<option value=\"%d\">%s</option>", dto.getCity_id(), dto.getCity()));

}

for (EmployeeDTO dto : dao.buseoList()) {

buseoLists.append(String.format("<option value=\"%d\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

}

for (EmployeeDTO dto : dao.jikwiList()) {

jikwiLists.append(String.format("<option value=\"%d\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<link rel="stylesheet"

href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>

<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>

<script>

$(function() {

$("#ibsadate").datepicker({dateFormat:"yy-mm-dd"});

});

</script>


<script type="text/javascript">

//Ajax 전역 변수

var xmlReq;


function myFunc() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

var name = document.getElementById("name");

var ssn = document.getElementById("ssn");

var ibsadate = document.getElementById("ibsadate");

var tel = document.getElementById("tel");

var basicpay = document.getElementById("basicpay");

var sudang = document.getElementById("sudang");

var nameMsg = document.getElementById("nameMsg");

var ssnMsg = document.getElementById("ssnMsg");

var ibsadateMsg = document.getElementById("ibsadateMsg");

var telMsg = document.getElementById("telMsg");

var basicpayMsg = document.getElementById("basicpayMsg");

var sudangMsg = document.getElementById("sudangMsg");

nameMsg.style.display = "none";

ssnMsg.style.display = "none";

ibsadateMsg.style.display = "none";

telMsg.style.display = "none";

basicpayMsg.style.display = "none";

sudangMsg.style.display = "none";

//빈칸 검사

if(name.value == ""){

nameMsg.style.display = "inline";

return;

}

if(ssn.value == ""){

ssnMsg.style.display = "inline";

return;

}

if(ibsadate.value == ""){

ibsadateMsg.style.display = "inline";

return;

}

if(tel.value == ""){

telMsg.style.display = "inline";

return;

}

if(basicpay.value == ""){

basicpayMsg.style.display = "inline";

return;

}

//숫자 검사

if (basicpay.value.match(/[^0-9]/)){

basicpayMsg.style.display = "inline";

return;

if(sudang.value == ""){

sudangMsg.style.display = "inline";

return;

}

if (sudang.value.match(/[^0-9]/)){

sudangMsg.style.display = "inline";

return;

//데이터 전송

myForm.submit();

}

function msg() {

if (<%=insertOK%>) {

alert("입력이 완료되었습니다.");

}

}

function minBasicPayCheck(obj) {

var jikwi_id = obj.options[obj.selectedIndex];

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "MinBasicPayCheck.jsp";

var postString = "jikwi_id="+jikwi_id.value;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}

function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}

function printData() {

var result = xmlReq.responseText;

var minBasicPay = document.getElementById("minBasicPay");

minBasicPay.innerHTML = result;

}

</script>


</head>

<body onload="msg()">

<div>

<div>

<h2>직원관리_직원입력</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>


<div>

<form action="Employee_Insert.jsp" method="post" id="myForm">

<table>

<tr>

<td>이름</td>

<td><input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">이름를 채워야 합니다.</span></td>

</tr>

<tr>

<td>주민번호(YYMMDD-NNNNNNN)</td>

<td><input type="text" id="ssn" name="ssn"><span id="ssnMsg" style="color:red; display:none;">주민번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>입사일(YYYY-MM-DD)</td>

<td><input type="text" id="ibsadate" name="ibsadate"><span id="ibsadateMsg" style="color:red; display:none;">입사일을 채워야 합니다.</span></td>

</tr>

<tr>

<td>지역</td>

<td><select style="width:154px;" id="city_id" name="city_id"><%=cityLists%></select></td>

</tr>

<tr>

<td>전화번호</td>

<td><input type="text" id="tel" name="tel"><span id="telMsg" style="color:red; display:none;">전화번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>부서</td>

<td><select style="width:154px;" id="buseo_id" name="buseo_id"><%=buseoLists%></select></td>

</tr>

<tr>

<td>직위</td>

<td><select style="width:154px;" id="jikwi_id" name="jikwi_id" onchange="minBasicPayCheck(this)"><%=jikwiLists%></select></td>

</tr>

<tr>

<td>기본급(최소 <span id="minBasicPay">????</span> 이상)</td>

<td><input type="text" id="basicpay" name="basicpay"><span id="basicpayMsg" style="color:red; display:none;">기본급은 숫자로만 채워야 합니다.</span></td>

</tr>

<tr>

<td>수당</td>

<td><input type="text" id="sudang" name="sudang"><span id="sudangMsg" style="color:red; display:none;">수당은 숫자로만 채워야 합니다.</span></td>

</tr>

</table>

[<a href="javascript:myFunc()">입력</a>]

</form>

</div>

</div>

</body>

</html>




----------------------------------------------

//Employee_Insert.jsp -> 직원관리. 입력 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*"%>

<%

//문제) 직원 입력 과정 추가할 것.

//한글 인코딩 처리 필요

//데이터 수신

//DAO 객체 생성

//데이터베이스 연결

//DTO 객체 생성

//INSERT 쿼리 메소드 호출

request.setCharacterEncoding("euc-kr");

String name = request.getParameter("name");

String ssn = request.getParameter("ssn");

String ibsadate = request.getParameter("ibsadate");

String city_id = request.getParameter("city_id");

String tel = request.getParameter("tel");

String buseo_id = request.getParameter("buseo_id");

String jikwi_id = request.getParameter("jikwi_id");

String basicpay = request.getParameter("basicpay");

String sudang = request.getParameter("sudang");

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

EmployeeDTO dto = new EmployeeDTO();

dto.setName(name);

dto.setSsn(ssn);

dto.setIbsadate(ibsadate);

dto.setCity_id(Integer.parseInt(city_id));

dto.setTel(tel);

dto.setBuseo_id(Integer.parseInt(buseo_id));

dto.setJikwi_id(Integer.parseInt(jikwi_id));

dto.setBasicpay(Integer.parseInt(basicpay));

dto.setSudang(Integer.parseInt(sudang));

dao.add(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

//입력 과정이 모두 끝나면 입력 폼 페이지로 돌아가도록 함.

String url = String.format("Employee_InsertForm.jsp?insertOK=true");

response.sendRedirect(url);

%>




----------------------------------------------

//Employee_UpdateForm.jsp -> 직원관리. 수정 폼 화면 구성.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>      

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


String value = request.getParameter("value");

if (value == null) {

value = "";

}


EmployeeDAO dao = new EmployeeDAO();

String name = "";

String ssn = "";

String ibsadate = "";

String tel = "";

String basicpay = "";

String sudang = "";

int city_id = 0;

int buseo_id = 0;

int jikwi_id = 0;

StringBuilder cityLists = new StringBuilder();

StringBuilder buseoLists = new StringBuilder();

StringBuilder jikwiLists = new StringBuilder();

try {

dao.connect();

String wheres = String.format("WHERE emp_id='%s'", value);

String orders = "";

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

name = dto.getName();

ssn = dto.getSsn();

ibsadate = dto.getIbsadate();

tel = dto.getTel();

basicpay = String.valueOf(dto.getBasicpay());

sudang = String.valueOf(dto.getSudang());

city_id = dto.getCity_id();

buseo_id = dto.getBuseo_id();

jikwi_id = dto.getJikwi_id();

}

for (EmployeeDTO dto : dao.cityList()) {

if (city_id == dto.getCity_id()) {

cityLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getCity_id(), dto.getCity()));

} else {

cityLists.append(String.format("<option value=\"%d\">%s</option>", dto.getCity_id(), dto.getCity()));

}

}

for (EmployeeDTO dto : dao.buseoList()) {

if (buseo_id == dto.getBuseo_id()) {

buseoLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

} else {

buseoLists.append(String.format("<option value=\"%d\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

}

}

for (EmployeeDTO dto : dao.jikwiList()) {

if (jikwi_id == dto.getJikwi_id()) {

jikwiLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

} else {

jikwiLists.append(String.format("<option value=\"%d\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

}

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

var emp_id = document.getElementById("emp_id");

var searchValue = document.getElementById("value");

emp_id.value = searchValue.value;

//데이터 전송

myForm.submit();

}

//문제) 직위 변경시 최소 기본급 메시지 수정되는 부분 작성. Ajax.

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_직원수정</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="get" id="myForm">

사번

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

<span id="searchMsg" style="color:red;display:none;">사번을 채워야 합니다.</span>

</form>

<form action="Employee_Update.jsp" method="post" id="myForm">

<input type="hidden" id="emp_id" name="emp_id" value="">

<table>

<tr>

<td>이름</td>

<td><input type="text" id="name" name="name" value="<%=name%>"><span id="nameMsg" style="color:red; display:none;">이름를 채워야 합니다.</span></td>

</tr>

<tr>

<td>주민번호(YYMMDD-NNNNNNN)</td>

<td><input type="text" id="ssn" name="ssn" value="<%=ssn%>"><span id="ssnMsg" style="color:red; display:none;">주민번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>입사일(YYYY-MM-DD)</td>

<td><input type="text" id="ibsadate" name="ibsadate" value="<%=ibsadate%>"><span id="ibsadateMsg" style="color:red; display:none;">입사일을 채워야 합니다.</span></td>

</tr>

<tr>

<td>지역</td>

<td><select style="width:154px;" id="city_id" name="city_id"><%=cityLists%></select></td>

</tr>

<tr>

<td>전화번호</td>

<td><input type="text" id="tel" name="tel" value="<%=tel%>"><span id="telMsg" style="color:red; display:none;">전화번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>부서</td>

<td><select style="width:154px;" id="buseo_id" name="buseo_id"><%=buseoLists%></select></td>

</tr>

<tr>

<td>직위</td>

<td><select style="width:154px;" id="jikwi_id" name="jikwi_id" onchange="minBasicPayCheck(this)"><%=jikwiLists%></select></td>

</tr>

<tr>

<td>기본급(최소 <span id="minBasicPay">????</span> 이상)</td>

<td><input type="text" id="basicpay" name="basicpay" value="<%=basicpay%>"><span id="basicpayMsg" style="color:red; display:none;">기본급은 숫자로만 채워야 합니다.</span></td>

</tr>

<tr>

<td>수당</td>

<td><input type="text" id="sudang" name="sudang" value="<%=sudang%>"><span id="sudangMsg" style="color:red; display:none;">수당은 숫자로만 채워야 합니다.</span></td>

</tr>

</table>

[<a href="javascript:myFunc()">수정</a>]

</form>

</div>

</div>

</body>

</html>




----------------------------------------------

//Employee_Update.jsp -> 직원관리. 수정 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//한글 인코딩 처리

//데이터 수신

//emp_id, name, ...., sudang

//EmployeeDAO 객체 생성

//데이터베이스 연결]

//EmployeeDTO 객체 생성-> setter 호출

//UPDATE 쿼리 메소드 호출 -> dto 객체 전달

//수정 작업이 모두 끝나면 수정 폼 페이지로 이동


%>




----------------------------------------------

//Employee_DeleteForm.jsp -> 직원관리. 삭제 폼 화면 구성.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>    

<%

//로그인 여부 확인

//관리자 확인

if (session.getAttribute("loginCheck") == null || session.getAttribute("admin") == null) {

response.sendRedirect("Logout.jsp");

}


String deleteOK = request.getParameter("deleteOK");

if (deleteOK == null) {

deleteOK = "false";

}


String url = "deleteCancel()";

String value = request.getParameter("value");

if (value == null) {

value = "";

}

StringBuilder str = new StringBuilder();

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

String wheres = String.format("WHERE emp_id='%s'", value);

String orders = "";

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

url = "deleteOk()";

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

//데이터 전송

myForm.submit();

}

function deleteOk() {

//확인 버튼 선택한 경우만 삭제 진행

if (confirm("현재 자료를 삭제하시겠습니까?")) {

//삭제 페이지로 이동. emp_id 전달.

var emp_id = document.getElementById("value");

window.location.href = "Employee_Delete.jsp?emp_id="+emp_id.value;

}

}

function deleteCancel() {

alert("삭제 대상을 검색해야 합니다.");

}

function msg() {

if (<%=deleteOK%>) {

alert("삭제가 완료되었습니다.");

}

}

</script>


</head>

<body onload="msg()">

<div>

<div>

<h2>직원관리_직원삭제</h2>

<c:import url="MainMenu.jsp"></c:import>

</div>

<div>

<form method="get" id="myForm">

사번

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

[<a href="javascript:<%=url%>">삭제</a>]

<span id="searchMsg" style="color:red;display:none;">사번을 채워야 합니다.</span>

</form>

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th>사번</th>

<th>이름</th>

<th>주민번호</th>

<th>입사일</th>

<th>지역</th>

<th>전화번호</th>

<th>부서</th>

<th>직위</th>

<th>기본급</th>

<th>수당</th>

<th>급여</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




----------------------------------------------

//Employee_Delete.jsp -> 직원관리. 삭제 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

//emp_id 수신

//EmployeeDAO 객체 생성

//데이터 연결

//DELETE 쿼리 메소드 호출 -> remove()

String emp_id = request.getParameter("emp_id");

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

dao.remove(Integer.parseInt(emp_id));

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


//삭제 작업이 모두 완료되면 삭제 폼 페이지로 이동

String url = String.format("Employee_DeleteForm.jsp?deleteOK=true");

response.sendRedirect(url);


%>




----------------------------------------------

직원관리 (JSP버전) 완성됨.

-> WAR 파일은 프로젝트 복구용으로 사용하던가,

알집 프로그램으로 압축 풀어서 소스 코드 확인용으로 사용하면 됩니다.



'Java > JSP & Servlet' 카테고리의 다른 글

[20121204] 15일차 (Servlet JDBC 연동)  (0) 2012.12.04
[20121203] 14일차 (Servlet)  (0) 2012.12.04
[20121121] 7일차 (직원관리)  (0) 2012.12.04
[20121120] 6일차 (직원관리)  (0) 2012.12.04
[20121119] 5일차 (직원관리)  (0) 2012.12.04

WRITTEN BY
빨강꼬마

,

----------------------------------------

//Employee_InsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%


String insertOK = request.getParameter("insertOK");

if (insertOK == null) {

insertOK = "false";

}


StringBuilder cityLists = new StringBuilder();

StringBuilder buseoLists = new StringBuilder();

StringBuilder jikwiLists = new StringBuilder();


EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

for (EmployeeDTO dto : dao.cityList()) {

cityLists.append(String.format("<option value=\"%d\">%s</option>", dto.getCity_id(), dto.getCity()));

}

for (EmployeeDTO dto : dao.buseoList()) {

buseoLists.append(String.format("<option value=\"%d\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

}

for (EmployeeDTO dto : dao.jikwiList()) {

jikwiLists.append(String.format("<option value=\"%d\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<link rel="stylesheet"

href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>

<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>

<script>

$(function() {

$("#ibsadate").datepicker({dateFormat:"yy-mm-dd"});

});

</script>


<script type="text/javascript">

//Ajax 전역 변수

var xmlReq;


function myFunc() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

var name = document.getElementById("name");

var ssn = document.getElementById("ssn");

var ibsadate = document.getElementById("ibsadate");

var tel = document.getElementById("tel");

var basicpay = document.getElementById("basicpay");

var sudang = document.getElementById("sudang");

var nameMsg = document.getElementById("nameMsg");

var ssnMsg = document.getElementById("ssnMsg");

var ibsadateMsg = document.getElementById("ibsadateMsg");

var telMsg = document.getElementById("telMsg");

var basicpayMsg = document.getElementById("basicpayMsg");

var sudangMsg = document.getElementById("sudangMsg");

nameMsg.style.display = "none";

ssnMsg.style.display = "none";

ibsadateMsg.style.display = "none";

telMsg.style.display = "none";

basicpayMsg.style.display = "none";

sudangMsg.style.display = "none";

//빈칸 검사

if(name.value == ""){

nameMsg.style.display = "inline";

return;

}

if(ssn.value == ""){

ssnMsg.style.display = "inline";

return;

}

if(ibsadate.value == ""){

ibsadateMsg.style.display = "inline";

return;

}

if(tel.value == ""){

telMsg.style.display = "inline";

return;

}

if(basicpay.value == ""){

basicpayMsg.style.display = "inline";

return;

}

//숫자 검사

if (basicpay.value.match(/[^0-9]/)){

basicpayMsg.style.display = "inline";

return;

if(sudang.value == ""){

sudangMsg.style.display = "inline";

return;

}

if (sudang.value.match(/[^0-9]/)){

sudangMsg.style.display = "inline";

return;

//데이터 전송

myForm.submit();

}

function msg() {

if (<%=insertOK%>) {

alert("입력이 완료되었습니다.");

}

}

function minBasicPayCheck(obj) {

var jikwi_id = obj.options[obj.selectedIndex];

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "MinBasicPayCheck.jsp";

var postString = "jikwi_id="+jikwi_id.value;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}

function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}

function printData() {

var result = xmlReq.responseText;

var minBasicPay = document.getElementById("minBasicPay");

minBasicPay.innerHTML = result;

}

</script>


</head>

<body onload="msg()">

<div>

<div>

<h2>직원관리_직원입력</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>


<div>

<form action="Employee_Insert.jsp" method="post" id="myForm">

<table>

<tr>

<td>이름</td>

<td><input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">이름를 채워야 합니다.</span></td>

</tr>

<tr>

<td>주민번호(YYMMDD-NNNNNNN)</td>

<td><input type="text" id="ssn" name="ssn"><span id="ssnMsg" style="color:red; display:none;">주민번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>입사일(YYYY-MM-DD)</td>

<td><input type="text" id="ibsadate" name="ibsadate"><span id="ibsadateMsg" style="color:red; display:none;">입사일을 채워야 합니다.</span></td>

</tr>

<tr>

<td>지역</td>

<td><select style="width:154px;" id="city_id" name="city_id"><%=cityLists%></select></td>

</tr>

<tr>

<td>전화번호</td>

<td><input type="text" id="tel" name="tel"><span id="telMsg" style="color:red; display:none;">전화번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>부서</td>

<td><select style="width:154px;" id="buseo_id" name="buseo_id"><%=buseoLists%></select></td>

</tr>

<tr>

<td>직위</td>

<td><select style="width:154px;" id="jikwi_id" name="jikwi_id" onchange="minBasicPayCheck(this)"><%=jikwiLists%></select></td>

</tr>

<tr>

<td>기본급(최소 <span id="minBasicPay">????</span> 이상)</td>

<td><input type="text" id="basicpay" name="basicpay"><span id="basicpayMsg" style="color:red; display:none;">기본급은 숫자로만 채워야 합니다.</span></td>

</tr>

<tr>

<td>수당</td>

<td><input type="text" id="sudang" name="sudang"><span id="sudangMsg" style="color:red; display:none;">수당은 숫자로만 채워야 합니다.</span></td>

</tr>

</table>

[<a href="javascript:myFunc()">입력</a>]

</form>

</div>

</div>

</body>

</html>



//Employee_Insert.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*"%>

<%

//문제) 직원 입력 과정 추가할 것.

//한글 인코딩 처리 필요

//데이터 수신

//DAO 객체 생성

//데이터베이스 연결

//DTO 객체 생성

//INSERT 쿼리 메소드 호출

request.setCharacterEncoding("euc-kr");

String name = request.getParameter("name");

String ssn = request.getParameter("ssn");

String ibsadate = request.getParameter("ibsadate");

String city_id = request.getParameter("city_id");

String tel = request.getParameter("tel");

String buseo_id = request.getParameter("buseo_id");

String jikwi_id = request.getParameter("jikwi_id");

String basicpay = request.getParameter("basicpay");

String sudang = request.getParameter("sudang");

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

EmployeeDTO dto = new EmployeeDTO();

dto.setName(name);

dto.setSsn(ssn);

dto.setIbsadate(ibsadate);

dto.setCity_id(Integer.parseInt(city_id));

dto.setTel(tel);

dto.setBuseo_id(Integer.parseInt(buseo_id));

dto.setJikwi_id(Integer.parseInt(jikwi_id));

dto.setBasicpay(Integer.parseInt(basicpay));

dto.setSudang(Integer.parseInt(sudang));

dao.add(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

//입력 과정이 모두 끝나면 입력 폼 페이지로 돌아가도록 함.

String url = String.format("Employee_InsertForm.jsp?insertOK=true");

response.sendRedirect(url);

%>




//MinBasicPayCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

String jikwi_id = request.getParameter("jikwi_id");


EmployeeDAO dao = new EmployeeDAO();

int minBasicPay = 0;

try {

dao.connect();

minBasicPay = dao.minBasicPay(Integer.parseInt(jikwi_id));

}catch(Exception e) {

System.out.println(e.toString());

}finally{

dao.close();

}

out.write(String.format("%,d", minBasicPay));

%>



------------------------------------------------------

//Employee_DeleteForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

String deleteOK = request.getParameter("deleteOK");

if (deleteOK == null) {

deleteOK = "false";

}


String url = "deleteCancel()";

String value = request.getParameter("value");

if (value == null) {

value = "";

}

StringBuilder str = new StringBuilder();

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

String wheres = String.format("WHERE emp_id='%s'", value);

String orders = "";

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

url = "deleteOk()";

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

//데이터 전송

myForm.submit();

}

function deleteOk() {

//확인 버튼 선택한 경우만 삭제 진행

if (confirm("현재 자료를 삭제하시겠습니까?")) {

//삭제 페이지로 이동. emp_id 전달.

var emp_id = document.getElementById("value");

window.location.href = "Employee_Delete.jsp?emp_id="+emp_id.value;

}

}


function deleteCancel() {

alert("삭제 대상을 검색해야 합니다.");

}

function msg() {

if (<%=deleteOK%>) {

alert("삭제가 완료되었습니다.");

}

}

</script>


</head>

<body onload="msg()">

<div>

<div>

<h2>직원관리_직원삭제</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="get" id="myForm">

사번

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

[<a href="javascript:<%=url%>">삭제</a>]

<span id="searchMsg" style="color:red;display:none;">사번을 채워야 합니다.</span>

</form>

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th>사번</th>

<th>이름</th>

<th>주민번호</th>

<th>입사일</th>

<th>지역</th>

<th>전화번호</th>

<th>부서</th>

<th>직위</th>

<th>기본급</th>

<th>수당</th>

<th>급여</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>





//Employee_Delete.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

//emp_id 수신

//EmployeeDAO 객체 생성

//데이터 연결

//DELETE 쿼리 메소드 호출 -> remove()

String emp_id = request.getParameter("emp_id");

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

dao.remove(Integer.parseInt(emp_id));

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


//삭제 작업이 모두 완료되면 삭제 폼 페이지로 이동

String url = String.format("Employee_DeleteForm.jsp?deleteOK=true");

response.sendRedirect(url);


%>




--------------------------------------------------------

//Employee_UpdateForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>      

<%

String value = request.getParameter("value");

if (value == null) {

value = "";

}


EmployeeDAO dao = new EmployeeDAO();

String name = "";

String ssn = "";

String ibsadate = "";

String tel = "";

String basicpay = "";

String sudang = "";

int city_id = 0;

int buseo_id = 0;

int jikwi_id = 0;

StringBuilder cityLists = new StringBuilder();

StringBuilder buseoLists = new StringBuilder();

StringBuilder jikwiLists = new StringBuilder();

try {

dao.connect();

String wheres = String.format("WHERE emp_id='%s'", value);

String orders = "";

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

name = dto.getName();

ssn = dto.getSsn();

ibsadate = dto.getIbsadate();

tel = dto.getTel();

basicpay = String.valueOf(dto.getBasicpay());

sudang = String.valueOf(dto.getSudang());

city_id = dto.getCity_id();

buseo_id = dto.getBuseo_id();

jikwi_id = dto.getJikwi_id();

}

for (EmployeeDTO dto : dao.cityList()) {

if (city_id == dto.getCity_id()) {

cityLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getCity_id(), dto.getCity()));

} else {

cityLists.append(String.format("<option value=\"%d\">%s</option>", dto.getCity_id(), dto.getCity()));

}

}

for (EmployeeDTO dto : dao.buseoList()) {

if (buseo_id == dto.getBuseo_id()) {

buseoLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

} else {

buseoLists.append(String.format("<option value=\"%d\">%s</option>", dto.getBuseo_id(), dto.getBuseo()));

}

}

for (EmployeeDTO dto : dao.jikwiList()) {

if (jikwi_id == dto.getJikwi_id()) {

jikwiLists.append(String.format("<option value=\"%d\" selected=\"selected\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

} else {

jikwiLists.append(String.format("<option value=\"%d\">%s</option>", dto.getJikwi_id(), dto.getJikwi()));

}

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

var emp_id = document.getElementById("emp_id");

var searchValue = document.getElementById("value");

emp_id.value = searchValue.value;

//데이터 전송

myForm.submit();

}

//문제) 직위 변경시 최소 기본급 메시지 수정되는 부분 작성. Ajax.

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_직원검색</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="get" id="myForm">

사번

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

<span id="searchMsg" style="color:red;display:none;">사번을 채워야 합니다.</span>

</form>

<form action="Employee_Update.jsp" method="post" id="myForm">

<input type="hidden" id="emp_id" name="emp_id" value="">

<table>

<tr>

<td>이름</td>

<td><input type="text" id="name" name="name" value="<%=name%>"><span id="nameMsg" style="color:red; display:none;">이름를 채워야 합니다.</span></td>

</tr>

<tr>

<td>주민번호(YYMMDD-NNNNNNN)</td>

<td><input type="text" id="ssn" name="ssn" value="<%=ssn%>"><span id="ssnMsg" style="color:red; display:none;">주민번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>입사일(YYYY-MM-DD)</td>

<td><input type="text" id="ibsadate" name="ibsadate" value="<%=ibsadate%>"><span id="ibsadateMsg" style="color:red; display:none;">입사일을 채워야 합니다.</span></td>

</tr>

<tr>

<td>지역</td>

<td><select style="width:154px;" id="city_id" name="city_id"><%=cityLists%></select></td>

</tr>

<tr>

<td>전화번호</td>

<td><input type="text" id="tel" name="tel" value="<%=tel%>"><span id="telMsg" style="color:red; display:none;">전화번호를 채워야 합니다.</span></td>

</tr>

<tr>

<td>부서</td>

<td><select style="width:154px;" id="buseo_id" name="buseo_id"><%=buseoLists%></select></td>

</tr>

<tr>

<td>직위</td>

<td><select style="width:154px;" id="jikwi_id" name="jikwi_id" onchange="minBasicPayCheck(this)"><%=jikwiLists%></select></td>

</tr>

<tr>

<td>기본급(최소 <span id="minBasicPay">????</span> 이상)</td>

<td><input type="text" id="basicpay" name="basicpay" value="<%=basicpay%>"><span id="basicpayMsg" style="color:red; display:none;">기본급은 숫자로만 채워야 합니다.</span></td>

</tr>

<tr>

<td>수당</td>

<td><input type="text" id="sudang" name="sudang" value="<%=sudang%>"><span id="sudangMsg" style="color:red; display:none;">수당은 숫자로만 채워야 합니다.</span></td>

</tr>

</table>

[<a href="javascript:myFunc()">수정</a>]

</form>

</div>

</div>

</body>

</html>




//Employee_Update.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//한글 인코딩 처리

//데이터 수신

//emp_id, name, ...., sudang

//EmployeeDAO 객체 생성

//데이터베이스 연결]

//EmployeeDTO 객체 생성-> setter 호출

//UPDATE 쿼리 메소드 호출 -> dto 객체 전달

//수정 작업이 모두 끝나면 수정 폼 페이지로 이동


%>




--------------------------------------------------------



WRITTEN BY
빨강꼬마

,

----------------------------------------

//Employee_Search.jsp

<%@page import="java.net.URLDecoder"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>

<%


request.setCharacterEncoding("euc-kr");

String key = request.getParameter("key");

if (key == null) {

key = "";

}

String value = request.getParameter("value");

if (value == null) {

value = "";

}


String order = request.getParameter("order");

if (order == null) {

order = "emp_id";

}

String direction = request.getParameter("direction");

if (direction == null) {

direction = "asc";

}

//제목을 기준으로 정렬시키기 위해서 추가한 부분

String urlEmp_id = "";

String urlName = "";

String urlSsn = "";

String urlIbsadate = "";

String urlCity = "";

String urlTel = "";

String urlBuseo = "";

String urlJikwi = "";

String urlBasicpay = "";

String urlSudang = "";

String urlPay = "";

//제목을 기준으로 정렬시키기 위해서 추가한 부분

if (order.equals("emp_id") && direction.equals("asc")) {

urlEmp_id = String.format("Employee_Search.jsp?order=emp_id&direction=desc&key=%s&value=%s", key, value);

} else {

urlEmp_id = String.format("Employee_Search.jsp?order=emp_id&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("name") && direction.equals("asc")) {

urlName = String.format("Employee_Search.jsp?order=name&direction=desc&key=%s&value=%s", key, value);

} else {

urlName = String.format("Employee_Search.jsp?order=name&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("ssn") && direction.equals("asc")) {

urlSsn = String.format("Employee_Search.jsp?order=ssn&direction=desc&key=%s&value=%s", key, value);

} else {

urlSsn = String.format("Employee_Search.jsp?order=ssn&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("ibsadate") && direction.equals("asc")) {

urlIbsadate = String.format("Employee_Search.jsp?order=ibsadate&direction=desc&key=%s&value=%s", key, value);

} else {

urlIbsadate = String.format("Employee_Search.jsp?order=ibsadate&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("city") && direction.equals("asc")) {

urlCity = String.format("Employee_Search.jsp?order=city&direction=desc&key=%s&value=%s", key, value);

} else {

urlCity = String.format("Employee_Search.jsp?order=city&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("tel") && direction.equals("asc")) {

urlTel = String.format("Employee_Search.jsp?order=tel&direction=desc&key=%s&value=%s", key, value);

} else {

urlTel = String.format("Employee_Search.jsp?order=tel&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("buseo") && direction.equals("asc")) {

urlBuseo = String.format("Employee_Search.jsp?order=buseo&direction=desc&key=%s&value=%s", key, value);

} else {

urlBuseo = String.format("Employee_Search.jsp?order=buseo&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("jikwi") && direction.equals("asc")) {

urlJikwi = String.format("Employee_Search.jsp?order=jikwi&direction=desc&key=%s&value=%s", key, value);

} else {

urlJikwi = String.format("Employee_Search.jsp?order=jikwi&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("basicpay") && direction.equals("asc")) {

urlBasicpay = String.format("Employee_Search.jsp?order=basicpay&direction=desc&key=%s&value=%s", key, value);

} else {

urlBasicpay = String.format("Employee_Search.jsp?order=basicpay&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("sudang") && direction.equals("asc")) {

urlSudang = String.format("Employee_Search.jsp?order=sudang&direction=desc&key=%s&value=%s", key, value);

} else {

urlSudang = String.format("Employee_Search.jsp?order=sudang&direction=asc&key=%s&value=%s", key, value);

}

if (order.equals("pay") && direction.equals("asc")) {

urlPay = String.format("Employee_Search.jsp?order=pay&direction=desc&key=%s&value=%s", key, value);

} else {

urlPay = String.format("Employee_Search.jsp?order=pay&direction=asc&key=%s&value=%s", key, value);

}


StringBuilder str = new StringBuilder();

String count = "0";

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

String wheres = String.format("WHERE %s='%s'", key, value);

String orders = String.format("ORDER BY %s %s", order, direction);


count = String.valueOf(dao.count(wheres));

for (EmployeeDTO dto : dao.searchLists(wheres,orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function search() {

var myForm = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가할 것.

//데이터 전송

myForm.submit();

}

function radioCheck() {

var obj = document.getElementById("<%=key%>");

obj.checked = true;

}

</script>


</head>

<body onload="radioCheck()">

<div>

<div>

<h2>직원관리_직원검색</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="get" id="myForm">

검색기준 

<input type="radio" name="key" value="emp_id" id="emp_id">사번

<input type="radio" name="key" value="name" id="name">이름

<input type="radio" name="key" value="city" id="city">지역

<input type="radio" name="key" value="buseo" id="buseo">부서

<input type="radio" name="key" value="jikwi" id="jikwi">직위

<input type="text" style="width:200px;"

name="value" id="value" value="<%=value%>">

[<a href="javascript:search()">검색</a>]

<span id="searchMsg" style="color:red;display:none;">검색 기준 또는 검색 단어를 채워야 합니다.</span>

</form>

<h3>검색 결과 직원수 : <%=count%>명</h3>

<div id="result">

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th><a href="<%=urlEmp_id%>">사번</a></th>

<th><a href="<%=urlName%>">이름</a></th>

<th><a href="<%=urlSsn%>">주민번호</a></th>

<th><a href="<%=urlIbsadate%>">입사일</a></th>

<th><a href="<%=urlCity%>">지역</a></th>

<th><a href="<%=urlTel%>">전화번호</a></th>

<th><a href="<%=urlBuseo%>">부서</a></th>

<th><a href="<%=urlJikwi%>">직위</a></th>

<th><a href="<%=urlBasicpay%>">기본급</a></th>

<th><a href="<%=urlSudang%>">수당</a></th>

<th><a href="<%=urlPay%>">급여</a></th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</div>

</body>

</html>



* 검색 결과 출력 후 제목 클릭시 정렬하는 부분.

-> 한글에 대한 get 방식 데이터 전송 문제

-> 해결 방법은 server.xml에서 

<Connector connectionTimeout="20000" port="8090" protocol="HTTP/1.1" redirectPort="8443"/>

부분을 

<Connector connectionTimeout="20000" port="8090" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="euc-kr"/>

로 고칠 것.

------------------------------------------------





WRITTEN BY
빨강꼬마

,

---------------------------------------------

직원관리 프로젝트

-> 새 프로젝트 생성(Employee_20121119)

-> 메뉴 구성 추가

-> DBConn, EmployeeDTO, EmployeeDAO 클래스 이용.

-> emp.sql 쿼리를 먼저 실행해서 환경 구성할 것.



--------------------------------------

--지역 검색 쿼리

SELECT city_id, city FROM city ORDER BY city_id


--부서 검색 쿼리

SELECT buseo_id, buseo FROM buseo ORDER BY buseo_id


--직위 검색 쿼리

SELECT jikwi_id, jikwi FROM jikwi ORDER BY jikwi_id


--직위별 최소 기본급 검색 쿼리

SELECT min_basicpay FROM jikwi WHERE jikwi_id=9


--입력 쿼리

INSERT INTO emp (emp_id, name, ssn, ibsadate, city_id, tel, buseo_id, jikwi_id, basicpay, sudang) 

VALUES (empSeq.nextval

, '홍길동'

, '771212-1022432'

, '1998-10-11'

, 6

, '011-2356-4528'

, 7

, 9

, 2610000

, 200000)


--직원 명단 출력 쿼리(emp 테이블이 아니라 empView 이용)

SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate

, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay

, sudang, pay 

FROM empView 

ORDER BY emp_id ASC


--전체 직원수 출력 쿼리 (emp 테이블이나 empView나 결과 동일함)

SELECT COUNT(*) AS count 

FROM emp


--검색 쿼리(emp 테이블이 아니라 empView 이용)

SELECT emp_id, name, ssn, TO_CHAR(ibsadate, 'YYYY-MM-DD') AS ibsadate

, city_id, city, tel, buseo_id, buseo, jikwi_id, jikwi, basicpay

, sudang, pay 

FROM empView 

WHERE emp_id = 1001

ORDER BY emp_id ASC


--수정 쿼리

UPDATE emp

SET name='새로운 이름'

, ssn='새로운 주민번호'

, ibsadate='새로운 입사일'

, city_id=1

, tel='새로운 전화번호'

, buseo_id=1

, jikwi_id=1

, basicpay=1

, sudang=1

WHERE emp_id=1001


--삭제 쿼리

DELETE emp

WHERE emp_id=1001



--직원용 ID(이름), PW(주민번호 뒷자리) 검사 쿼리

SELECT COUNT(*) AS count 

FROM emp

WHERE name='이순신' AND SUBSTR(ssn, 8, 7)='1544236';


--직원 전용 employeeView

CREATE OR REPLACE VIEW employeeView

AS

SELECT emp_id, name, ibsadate, c.city_id AS city_id, city, tel, b.buseo_id AS buseo_id, buseo, j.jikwi_id AS jikwi_id, jikwi 

FROM emp e, city c, buseo b, jikwi j

WHERE e.city_id=c.city_id AND e.buseo_id=b.buseo_id AND e.jikwi_id=j.jikwi_id

ORDER BY emp_id ASC;



--------------------------------------

--관리자 전용 테이블


CREATE TABLE empAdmin (

id VARCHAR2(20) --PK

,pw VARCHAR2(20) --암호화. encrypt() 사용자 정의 함수 이용.

);


ALTER TABLE empAdmin

ADD CONSTRAINT empAdmin_id_pk PRIMARY KEY(id);


INSERT INTO empAdmin (id, pw) VALUES ('admin', encrypt('1234', 'admin'));

INSERT INTO empAdmin (id, pw) VALUES ('hong', encrypt('1234', 'hong'));

COMMIT;


SELECT id, pw FROM empAdmin;


--관리자용 ID, PW 검사 쿼리

SELECT COUNT(*) AS count FROM empAdmin

WHERE id='admin' AND pw=encrypt('1234', 'admin');




--------------------------------------


//DBConn.java


//EmployeeDTO.java


//CityDTO.java


//BuseoDTO.java


//JikwiDTO.java


//EmployeeDAO.java


//CityDAO.java


//BuseoDAO.java


//JikwiDAO.java


//City.jsp -> 지역관리. 입력, 출력, 수정, 삭제 기능.


//Buseo.jsp -> 부서관리. 입력, 출력, 수정, 삭제 기능.


//Jikwi.jsp -> 직위관리. 입력, 출력, 수정, 삭제 기능.


//BasicStyle.css -> CSS 스타일 시트 전용.


//Employee_Select.jsp -> 직원관리. 출력 기능.


//Employee_Search.jsp -> 직원관리. 검색 기능.


//Employee_InsertForm.jsp -> 직원관리. 입력 폼 화면 구성. Ajax 요청 기능. jQuery 달력 기능.


//Employee_Insert.jsp -> 직원관리. 입력 액션 처리.


//Employee_UpdateForm.jsp -> 직원관리. 수정 폼 화면 구성.


//Employee_Update.jsp -> 직원관리. 수정 액션 처리.


//Employee_DeleteForm.jsp -> 직원관리. 삭제 폼 화면 구성.


//Employee_Delete.jsp -> 직원관리. 삭제 액션 처리.


//MinBasicPayCheck.jsp -> 직원관리 입력 폼에서 직위 선택시 최소기본급을 리턴하는 전용 페이지. Ajax 요청 기능.


//LoginForm.jsp  -> 로그인 페이지. ID, PW 확인 및 세션 처리


//Logout.jsp -> 로그아웃 액션 처리.


//MainMenu.jsp -> 메인 메뉴 전용.


-------------------------------------------

//BasicStyle.css

@CHARSET "EUC-KR";


body {

color:#2f3743;

}


a { /* a 태그에만 적용 */

text-decoration: none; /* 글자의 장식 지정 없앰 */

color:gray; /* 글자색 */

}


a:hover { /* a 태그에 커서가 올려져 있을때만 적용 */

text-decoration: underline; /* 밑줄 장식 지정 */

color:red;

}


table.style00 td, table.style00 th 

{

padding: 3px;

border-right-style: solid;

border-bottom-style: solid;

border-width: 1px;

border-color: #6980b8;

}


table.style00 td:hover 

{

background-color:#d2d2d2;

}


.style1 {   /* class 속성의 값이 style1인 경우만 적용 */

text-align:center; /* 가운데 정렬 */

}


.style2 {   /* class 속성의 값이 style2인 경우만 적용 */

text-align:right; /* 오른쪽 정렬 */

}


#result {

overflow:auto;  /* DIV 태그 내부에 스크롤 생성 */ 

height:300px;

}



------------------------------------------------------

//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}



-------------------------------------------

//CityDTO.java

package com.test;


public class CityDTO {

private int city_id;

private String city;

public int getCity_id() {

return city_id;

}

public void setCity_id(int city_id) {

this.city_id = city_id;

}

public String getCity() {

return city;

}

public void setCity(String city) {

this.city = city;

}

}





//CityDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class CityDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String city)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO city (city_id, city) VALUES (citySeq.nextval, '%s')", city);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<CityDTO> lists()

throws SQLException  {

ArrayList<CityDTO> arrayList

= new ArrayList<CityDTO>();

String sql = String.format("SELECT city_id, city FROM city ORDER BY city_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int city_id = rs.getInt("city_id");

String city = rs.getString("city");

CityDTO dto = new CityDTO();

dto.setCity_id(city_id);

dto.setCity(city);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<CityDTO> search(String key, String value)

throws SQLException  {

ArrayList<CityDTO> arrayList

= new ArrayList<CityDTO>();

return arrayList;

}*/

public int modify(CityDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE city SET city='%s' WHERE city_id=%d", dto.getCity(), dto.getCity_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int city_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE city WHERE city_id=%d", city_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}





//City.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>

<%

request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


CityDAO dao = new CityDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

CityDTO dto = new CityDTO();

dto.setCity_id(Integer.parseInt(num));

dto.setCity(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (CityDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getCity_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function cityForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_지역관리</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

지역번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">지역번호를 입력해야 합니다.</span><br>

지역이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">지역이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:cityForm('insert')">지역추가</a>]

[<a href="javascript:cityForm('update')">지역수정</a>]

[<a href="javascript:cityForm('delete')">지역삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>지역</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>


-------------------------------------------

//지역관리 프로그램을 이용해서 부서관리로 만들 것.

//BuseoDTO.java

package com.test;


public class BuseoDTO {

private int buseo_id;

private String buseo;

public int getBuseo_id() {

return buseo_id;

}

public void setBuseo_id(int buseo_id) {

this.buseo_id = buseo_id;

}

public String getBuseo() {

return buseo;

}

public void setBuseo(String buseo) {

this.buseo = buseo;

}

}




//BuseoDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class BuseoDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String buseo)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO buseo (buseo_id, buseo) VALUES (buseoSeq.nextval, '%s')", buseo);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<BuseoDTO> lists()

throws SQLException  {

ArrayList<BuseoDTO> arrayList

= new ArrayList<BuseoDTO>();

String sql = String.format("SELECT buseo_id, buseo FROM buseo ORDER BY buseo_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int buseo_id = rs.getInt("buseo_id");

String buseo = rs.getString("buseo");

BuseoDTO dto = new BuseoDTO();

dto.setBuseo_id(buseo_id);

dto.setBuseo(buseo);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<BuseoDTO> search(String key, String value)

throws SQLException  {

ArrayList<BuseoDTO> arrayList

= new ArrayList<BuseoDTO>();

return arrayList;

}*/

public int modify(BuseoDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE buseo SET buseo='%s' WHERE buseo_id=%d", dto.getBuseo(), dto.getBuseo_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int buseo_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE buseo WHERE buseo_id=%d", buseo_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}





//Buseo.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>

<%

request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


BuseoDAO dao = new BuseoDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

BuseoDTO dto = new BuseoDTO();

dto.setBuseo_id(Integer.parseInt(num));

dto.setBuseo(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (BuseoDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getBuseo_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function buseoForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_부서관리</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

부서번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">부서번호를 입력해야 합니다.</span><br>

부서이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">부서이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:buseoForm('insert')">부서추가</a>]

[<a href="javascript:buseoForm('update')">부서수정</a>]

[<a href="javascript:buseoForm('delete')">부서삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>부서</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




-------------------------------------------

//지역관리 프로그램을 이용해서 직위관리로 만들 것.

//JikwiDTO.java

package com.test;


public class JikwiDTO {

private int jikwi_id;

private String jikwi;

public int getJikwi_id() {

return jikwi_id;

}

public void setJikwi_id(int jikwi_id) {

this.jikwi_id = jikwi_id;

}

public String getJikwi() {

return jikwi;

}

public void setJikwi(String jikwi) {

this.jikwi = jikwi;

}

}





//JikwiDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class JikwiDAO {

Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

conn = null;

}

public int add(String jikwi)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jikwi (jikwi_id, jikwi) VALUES (jikwiSeq.nextval, '%s')", jikwi);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<JikwiDTO> lists()

throws SQLException  {

ArrayList<JikwiDTO> arrayList

= new ArrayList<JikwiDTO>();

String sql = String.format("SELECT jikwi_id, jikwi FROM jikwi ORDER BY jikwi_id");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

int jikwi_id = rs.getInt("jikwi_id");

String jikwi = rs.getString("jikwi");

JikwiDTO dto = new JikwiDTO();

dto.setJikwi_id(jikwi_id);

dto.setJikwi(jikwi);

arrayList.add(dto);

}

rs.close();


return arrayList;

}

/*public ArrayList<JikwiDTO> search(String key, String value)

throws SQLException  {

ArrayList<JikwiDTO> arrayList

= new ArrayList<JikwiDTO>();

return arrayList;

}*/

public int modify(JikwiDTO dto)

throws SQLException  {

int result = 0;


String sql = String.format("UPDATE jikwi SET jikwi='%s' WHERE jikwi_id=%d", dto.getJikwi(), dto.getJikwi_id());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int jikwi_id)

throws SQLException  {

int result = 0;

String sql = String.format("DELETE jikwi WHERE jikwi_id=%d", jikwi_id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

}





//Jikwi.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>

<%

request.setCharacterEncoding("euc-kr");

String num = request.getParameter("num");

String name = request.getParameter("name");

String key = request.getParameter("key"); //액션 구분용 값


StringBuilder str = new StringBuilder();


JikwiDAO dao = new JikwiDAO();


try {

dao.connect();

if (key != null && key.equals("insert")) {

dao.add(name);

}

if (key != null && key.equals("update")) {

//수정 메소드 호출

JikwiDTO dto = new JikwiDTO();

dto.setJikwi_id(Integer.parseInt(num));

dto.setJikwi(name);

dao.modify(dto);

}

if (key != null && key.equals("delete")) {

//삭제 메소드 호출

dao.remove(Integer.parseInt(num));

}

for (JikwiDTO dto : dao.lists()) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getJikwi_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("</tr>"));

}

} catch(Exception e) {

System.out.println(e.toString());

} finally {

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">


function jikwiForm(status) {

var myForm = document.getElementById("myForm");

var num = document.getElementById("num");

var name = document.getElementById("name");

var key = document.getElementById("key");

var numMsg = document.getElementById("numMsg");

var nameMsg = document.getElementById("nameMsg");

numMsg.style.display = "none";

nameMsg.style.display = "none";

if (status == "insert") {

//이름 검사 (공백)

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

if (status == "delete") {

//번호 검사 (공백, 숫자)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

}

if (status == "update") {

//번호 검사 (공백, 숫자)

//이름 검사 (공백)

if(num.value == "" || num.value.match(/[^0-9]/)) {

numMsg.style.display = "inline";

return;

}

if(name.value == "") {

nameMsg.style.display = "inline";

return;

}

}

key.value = status;

myForm.submit();

}

</script>


</head>

<body>

<div>

<div>

<h2>직원관리_직위관리</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>

<div>

<form method="post" id="myForm">

<%-- 추가, 수정, 삭제 구분용 값을 서버로 전송 --%>

<input type="hidden" id="key" name="key" value="">

직위번호<input type="text" id="num" name="num"><span id="numMsg" style="color:red; display:none;">직위번호를 입력해야 합니다.</span><br>

직위이름<input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">직위이름을 입력해야 합니다.</span><br>

[<a href="">전체출력</a>]

[<a href="javascript:jikwiForm('insert')">직위추가</a>]

[<a href="javascript:jikwiForm('update')">직위수정</a>]

[<a href="javascript:jikwiForm('delete')">직위삭제</a>]<br><br>

</form>

<table style="width:400px;" class="style00">

<tbody>

<tr>

<th>번호</th><th>직위</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




-------------------------------------------

//Employee_Select.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>

<%


String order = request.getParameter("order");

if (order == null) {

order = "emp_id";

}

String direction = request.getParameter("direction");

if (direction == null) {

direction = "asc";

}

//제목을 기준으로 정렬시키기 위해서 추가한 부분

String urlEmp_id = "";

String urlName = "";

String urlSsn = "";

String urlIbsadate = "";

String urlCity = "";

String urlTel = "";

String urlBuseo = "";

String urlJikwi = "";

String urlBasicpay = "";

String urlSudang = "";

String urlPay = "";

//제목을 기준으로 정렬시키기 위해서 추가한 부분

if (order.equals("emp_id") && direction.equals("asc")) {

urlEmp_id = "Employee_Select.jsp?order=emp_id&direction=desc";

} else {

urlEmp_id = "Employee_Select.jsp?order=emp_id&direction=asc";

}

if (order.equals("name") && direction.equals("asc")) {

urlName = "Employee_Select.jsp?order=name&direction=desc";

} else {

urlName = "Employee_Select.jsp?order=name&direction=asc";

}

if (order.equals("ssn") && direction.equals("asc")) {

urlSsn = "Employee_Select.jsp?order=ssn&direction=desc";

} else {

urlSsn = "Employee_Select.jsp?order=ssn&direction=asc";

}

if (order.equals("ibsadate") && direction.equals("asc")) {

urlIbsadate = "Employee_Select.jsp?order=ibsadate&direction=desc";

} else {

urlIbsadate = "Employee_Select.jsp?order=ibsadate&direction=asc";

}

if (order.equals("city") && direction.equals("asc")) {

urlCity = "Employee_Select.jsp?order=city&direction=desc";

} else {

urlCity = "Employee_Select.jsp?order=city&direction=asc";

}

if (order.equals("tel") && direction.equals("asc")) {

urlTel = "Employee_Select.jsp?order=tel&direction=desc";

} else {

urlTel = "Employee_Select.jsp?order=tel&direction=asc";

}

if (order.equals("buseo") && direction.equals("asc")) {

urlBuseo = "Employee_Select.jsp?order=buseo&direction=desc";

} else {

urlBuseo = "Employee_Select.jsp?order=buseo&direction=asc";

}

if (order.equals("jikwi") && direction.equals("asc")) {

urlJikwi = "Employee_Select.jsp?order=jikwi&direction=desc";

} else {

urlJikwi = "Employee_Select.jsp?order=jikwi&direction=asc";

}

if (order.equals("basicpay") && direction.equals("asc")) {

urlBasicpay = "Employee_Select.jsp?order=basicpay&direction=desc";

} else {

urlBasicpay = "Employee_Select.jsp?order=basicpay&direction=asc";

}

if (order.equals("sudang") && direction.equals("asc")) {

urlSudang = "Employee_Select.jsp?order=sudang&direction=desc";

} else {

urlSudang = "Employee_Select.jsp?order=sudang&direction=asc";

}

if (order.equals("pay") && direction.equals("asc")) {

urlPay = "Employee_Select.jsp?order=pay&direction=desc";

} else {

urlPay = "Employee_Select.jsp?order=pay&direction=asc";

}


StringBuilder str = new StringBuilder();

String count = "0";

EmployeeDAO dao = new EmployeeDAO();

try {

dao.connect();

count = String.valueOf(dao.count());

String orders = String.format("ORDER BY %s %s", order, direction);

for (EmployeeDTO dto : dao.lists(orders)) {

str.append(String.format("<tr>"));

str.append(String.format("<td class=\"style1\">%d</td>", dto.getEmp_id()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getSsn()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getIbsadate()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getCity()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getBuseo()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getJikwi()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getBasicpay()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getSudang()));

str.append(String.format("<td class=\"style2\">%,d</td>", dto.getPay()));

str.append(String.format("</tr>"));

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>직원관리(JSP버전)</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


</head>

<body>

<div>

<div>

<h2>직원관리_직원출력</h2>

<div>

[<a href="Employee_Select.jsp">직원출력</a>]

[<a href="Employee_Search.jsp">직원검색</a>]

[<a href="Employee_InsertForm.jsp">직원입력</a>]

[<a href="Employee_UpdateForm.jsp">직원수정</a>]

[<a href="Employee_DeleteForm.jsp">직원삭제</a>]

[<a href="City.jsp">지역관리</a>]

[<a href="Buseo.jsp">부서관리</a>]

[<a href="Jikwi.jsp">직위관리</a>]

[<a href="Logout.jsp">로그아웃</a>]

</div>

<hr>

</div>


<div>

<h3>전체 직원수 : <%=count%>명</h3>

<div id="result">

<table style="width:900px;" class="style00">

<tbody>

<tr>

<th><a href="<%=urlEmp_id%>">사번</a></th>

<th><a href="<%=urlName%>">이름</a></th>

<th><a href="<%=urlSsn%>">주민번호</a></th>

<th><a href="<%=urlIbsadate%>">입사일</a></th>

<th><a href="<%=urlCity%>">지역</a></th>

<th><a href="<%=urlTel%>">전화번호</a></th>

<th><a href="<%=urlBuseo%>">부서</a></th>

<th><a href="<%=urlJikwi%>">직위</a></th>

<th><a href="<%=urlBasicpay%>">기본급</a></th>

<th><a href="<%=urlSudang%>">수당</a></th>

<th><a href="<%=urlPay%>">급여</a></th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</div>

</body>

</html>



--------------------------------------------



WRITTEN BY
빨강꼬마

,

-----------------------------------------

회원관리+성적처리 프로젝트


1. 성적 테이블, 회원 테이블 조인. FK 설정 필요.


2. 회원(회원번호-PK, 이름, 전화번호) -> 이전과 동일


3. 성적 (성적번호-PK, 회원번호-FK, 국어, 영어, 수학) 

-> 이름 대신 회원번호-FK 설정


4. 회원에 회원 등록을 먼저하고, 성적에 성적 입력을 나중에 한다.


----------------------------------------

CREATE TABLE member2 (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member2

ADD CONSTRAINT member2_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE member2Seq;


//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'hong', '111-1111');

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'park', '222-2222');

COMMIT;



----------------------------------------

CREATE TABLE score2 (

sid NUMBER --PK, 자동 번호 부여

,mid NUMBER --FK

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score2

ADD CONSTRAINT score2_sid_pk PRIMARY KEY (sid);

ALTER TABLE score2

ADD CONSTRAINT score2_kor2_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mat_ck CHECK (mat BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mid_fk FOREIGN KEY (mid)

REFERENCES member2(mid);



--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE score2Seq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score2 (sid, mid, kor, eng, mat)

VALUES (score2Seq.nextval, 1, 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+)


--SELECT 쿼리 전용 뷰 생성(scott 계정)

CREATE OR REPLACE VIEW member2Score2View

AS

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+);


--뷰를 이용한 SELECT 쿼리 실행

SELECT mid, sid, name, kor, eng, mat, tot, ave, grade 

FROM member2Score2View;



----------------------------------------------

회원관리 - 회원 입, 출력  (수정, 삭제)

성적처리 - 성적 입, 출력  (수정, 삭제)


//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}




//Member2DTO.java

package com.test;


public class Member2DTO {

private int mid;

private String name, tel;

public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}




//Score2DTO.java -> mid 컬럼

package com.test;


public class Score2DTO {

private int mid, sid; //추가

private String name;

private String kor, eng, mat; //int->String


private int tot;

private double ave;

private String grade;

//추가

public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public int getSid() {

return sid;

}

public void setSid(int sid) {

this.sid = sid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getKor() {

return kor;

}

public void setKor(String kor) {

this.kor = kor;

}

public String getEng() {

return eng;

}

public void setEng(String eng) {

this.eng = eng;

}

public String getMat() {

return mat;

}

public void setMat(String mat) {

this.mat = mat;

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public double getAve() {

return ave;

}

public void setAve(double ave) {

this.ave = ave;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}

}





//Member2DAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class Member2DAO {


private Connection conn;

public void connect()

throws SQLException, ClassNotFoundException {

//연결 전용 메소드

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

//연결 해제 전용 메소드

DBConn.close();

conn = null;

}

public int add(Member2DTO dto)

throws SQLException {

//INSERT 쿼리 실행

int result = 0;

String sql = String.format("INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, '%s', '%s')", dto.getName(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int count() 

throws SQLException {

//SELECT 쿼리 실행

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM member2");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) { //row 단위 접근

result = rs.getInt("count"); //column 단위 접근

}

rs.close();

return result;

}

public ArrayList<Member2DTO> lists()

throws SQLException {

//SELECT 쿼리 실행


ArrayList<Member2DTO> arrayList

= new ArrayList<Member2DTO>();

String sql = String.format("SELECT mid, name, tel FROM member2 ORDER BY mid");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

//결과집합(ResultSet)을 리턴해야 된다. 

//결과집합은 특성상 이 메소드를 벗어날 수 없다.

//결과집합을 컬렉션에 저장

//컬렉션을 리턴.

while(rs.next()) { //row 단위 접근

int mid = rs.getInt("mid"); //column 단위 접근

String name = rs.getString("name");

String tel = rs.getString("tel");

Member2DTO dto = new Member2DTO();

dto.setMid(mid);

dto.setName(name);

dto.setTel(tel);

arrayList.add(dto);

}

rs.close();

return arrayList;

}


public int remove(int mid)

throws SQLException {

//DELETE 쿼리 실행

int result = 0;

String sql = String.format("DELETE member2 WHERE mid=%d", mid);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public Member2DTO search(int mid)

throws SQLException {

Member2DTO dto = null;

//문제) mid 를 전달받아서 Member2DTO를 리턴하는 프로그램 작성.

//SELECT mid, name, tel FROM member2 WHERE mid=2

String sql = String.format("SELECT mid, name, tel FROM member2 WHERE mid=%d", mid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) { //row 단위 접근

String name = rs.getString("name");

String tel = rs.getString("tel");

dto = new Member2DTO();

dto.setMid(mid);

dto.setName(name);

dto.setTel(tel);

}

rs.close();


return dto;

}

}





//Score2DAO.java -> mid 컬럼. null 값 처리.

package com.test;


import java.sql.*;

import java.util.*;


public class Score2DAO {

private Connection conn;


public void connect()

throws SQLException, ClassNotFoundException{

conn = DBConn.getConnection();

}


public void close() 

throws SQLException{

DBConn.close();

conn = null;

}



public int add(Score2DTO dto) 

throws SQLException{

int rowCount =0;


String sql = String.format("INSERT INTO score2 (sid, mid, kor, eng, mat) VALUES (score2Seq.nextval, %d, %s, %s, %s)", dto.getMid(), dto.getKor(), dto.getEng(), dto.getMat()); //%d->%s

Statement stmt = conn.createStatement();

rowCount = stmt.executeUpdate(sql);


return rowCount;

}


public ArrayList<Score2DTO> lists() 

throws SQLException{

ArrayList<Score2DTO> arrayList = new ArrayList<Score2DTO>();


String sql = String.format("SELECT mid, sid, name, kor, eng, mat, tot, ave, grade FROM member2Score2View");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

//sid, kor, eng, mat, tot, ave 등은

//null을 받을 수도 있다.

//null인 경우 getInt()는 0을 리턴한다.

int mid = rs.getInt("mid");

int sid = rs.getInt("sid");

String name = rs.getString("name");

String kor = rs.getString("kor"); //int->String

String eng = rs.getString("eng"); //int->String

String mat = rs.getString("mat"); //int->String

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");


Score2DTO dto = new Score2DTO();

dto.setMid(mid);

dto.setSid(sid);

dto.setName(name);

dto.setKor(kor);

dto.setEng(eng);

dto.setMat(mat);

dto.setTot(tot);

dto.setAve(ave);

dto.setGrade(grade);


arrayList.add(dto);

}


rs.close();


return arrayList;


}

}




//BasicStyle.css

@CHARSET "EUC-KR";

body {

color:#2f3743;

font-size:10pt;

}


a {

text-decoration:none;

color:gray;

}


a:hover {

text-decoration:underline;

color:red;

}


table.style00 td, table.style00 th 

{

padding: 3px;

border-right-style: solid;

border-bottom-style: solid;

border-width: 1px;

border-color: #6980b8;

}


table.style00 td:hover 

{

background-color:#d2d2d2;

}






//Member2List.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>    

<%@ page import="com.test.*" %>    

<%

StringBuilder str = new StringBuilder();

Member2DAO dao = new Member2DAO();

try {

dao.connect();

for (Member2DTO dto : dao.lists()) {

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td>", dto.getMid()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getTel()));

str.append("</tr>");

}

}catch(Exception e){

}finally{

dao.close();

}


%>    

<!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=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">

<style type="text/css">

.style1 {

text-align: center;

}

</style>


</head>

<body>

<div>

<div>

[<a href="Member2List.jsp">회원관리</a>]

[<a href="Score2List.jsp">성적관리</a>]

<hr>

</div>

<div>

<p>[<a href="Member2InsertForm.jsp">회원등록</a>]</p>

<table style="width:300px;" class="style00">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//Member2InsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈 칸 검사

if (name.value == ""

|| tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="Member2List.jsp">회원관리</a>]

[<a href="Score2List.jsp">성적관리</a>]

<hr>

</div>

<div>

<h3>-회원 등록-</h3>

<form action="Member2Insert.jsp" method="post" id="myForm">

<table>

<tbody>

<tr>

<td>이름</td>

<td><input type="text" name="name" id="name"></td>

</tr>

<tr>

<td>전화</td>

<td><input type="text" name="tel" id="tel"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">등록</a>]

[<a href="Member2List.jsp">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>





//Member2Insert.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>    

<%@ page import="com.test.*" %>     

<%

request.setCharacterEncoding("euc-kr");

String name = request.getParameter("name");

String tel = request.getParameter("tel");

Member2DAO dao = new Member2DAO();

try {

dao.connect();

Member2DTO dto = new Member2DTO();

dto.setName(name);

dto.setTel(tel);

dao.add(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


String url = String.format("Member2List.jsp");

response.sendRedirect(url);

%>




//Score2List.jsp -> 회원 명단 및 성적 출력 페이지

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>    

<%@ page import="com.test.*" %>      

<%

StringBuilder str = new StringBuilder();


Score2DAO dao = new Score2DAO();

try {

dao.connect();


for (Score2DTO dto : dao.lists()) {

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td>", dto.getMid()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"style2\">%s</td>", (dto.getKor()==null)?"x":dto.getKor())); //%d->%s

str.append(String.format("<td class=\"style2\">%s</td>", (dto.getEng()==null)?"x":dto.getEng())); //%d->%s

str.append(String.format("<td class=\"style2\">%s</td>", (dto.getMat()==null)?"x":dto.getMat())); //%d->%s

str.append(String.format("<td class=\"style2\">%d</td>", dto.getTot()));

str.append(String.format("<td class=\"style2\">%.1f</td>", dto.getAve()));

str.append(String.format("<td class=\"style1\">%s</td>", dto.getGrade()));

if (dto.getKor() != null) {

str.append(String.format("<td class=\"style1\">[입력]</td>"));

} else {

//입력 폼 화면으로 전환시

//mid(회원의 고유 번호)를 반드시 전달해야 한다.

//성적 입력시 필요한 중요 정보임.

str.append(String.format("<td class=\"style1\">[<a href=\"Score2InsertForm.jsp?mid=%d\">입력</a>]</td>", dto.getMid()));

}

str.append("</tr>");

}

}catch(Exception e){

}finally{

dao.close();

}

%>     

<!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=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">

<style type="text/css">

.style1 {

text-align: center;

}

.style2 {

text-align: right;

}

</style>


</head>

<body>

<div>

<div>

[<a href="Member2List.jsp">회원관리</a>]

[<a href="Score2List.jsp">성적관리</a>]

<hr>

</div>

<div>

<table style="width:500px;" class="style00">

<tbody>

<tr><th>번호</th><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th><th>판정</th><th></th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//Score2InsertForm.jsp -> 회원별 성적 입력 화면 페이지

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>    

<%@ page import="com.test.*" %>     

<%

String mid = request.getParameter("mid");


String name = "";

//문제) mid를 가지고 이름을 검색하는 쿼리 작성

//Member2DAO dao = new Member2DAO();

//Member2DTO dto = dao.search(Integer.parseInt(mid));

Member2DAO dao = new Member2DAO();

try {

dao.connect();

Member2DTO dto = dao.search(Integer.parseInt(mid));

name = dto.getName();

}catch(Exception e){

}finally{

dao.close();

}

%>    

<!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=EUC-KR">

<title>회원 관리+성적 관리</title>


<link rel="stylesheet" type="text/css" href="BasicStyle.css">


<script type="text/javascript">

function myFunc() {

obj = document.getElementById("myForm");

//문제) 데이터 검사 과정 추가

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(kor.value == "" || eng.value ==""|| mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}


//데이터 전송

obj.submit();

}

</script>


</head>

<body>

<div>

<div>

[<a href="Member2List.jsp">회원관리</a>]

[<a href="Score2List.jsp">성적관리</a>]

<hr>

</div>

<div>

<h3>-성적 입력-</h3>

<form action="Score2Insert.jsp" method="post" id="myForm">

<%-- 성적 입력을 위해서 반드시 전송해야 되는 값 --%>

<input type="hidden" name="mid" value="<%=mid%>">

<table>

<tbody>

<tr>

<td>이름</td>

<td><span style="font-weight: bold;"><%=name%></span></td>

</tr>

<tr>

<td>국어</td>

<td><input type="text" name="kor" id="kor"></td>

</tr>

<tr>

<td>영어</td>

<td><input type="text" name="eng" id="eng"></td>

</tr>

<tr>

<td>수학</td>

<td><input type="text" name="mat" id="mat"></td>

</tr>

<tr>

<td></td>

<td>

[<a href="javascript:myFunc()">등록</a>]

[<a href="Score2List.jsp">취소</a>]<br>

<span id="msg" style="font-size:10pt; color:red; display:none;">국어, 영어, 수학 점수를 0~100 사이의 숫자로 입력해야 합니다.</span>

</td>

</tr>

</tbody>

</table>

</form>

</div>

</div>

</body>

</html>




//Score2Insert.jsp -> 회원의 성적 입력 액션 처리

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>    

<%@ page import="com.test.*" %>     

<%

String mid = request.getParameter("mid");

String kor = request.getParameter("kor");

String eng = request.getParameter("eng");

String mat = request.getParameter("mat");

Score2DAO dao = new Score2DAO();

try {

dao.connect();

Score2DTO dto = new Score2DTO();

dto.setMid(Integer.parseInt(mid));

dto.setKor(kor);

dto.setEng(eng);

dto.setMat(mat);

dao.add(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


String url = String.format("Score2List.jsp");

response.sendRedirect(url);

%>




------------------------------------

회원관리+성적처리 프로젝트 완성됨.


WRITTEN BY
빨강꼬마

,

JSP & Servlet


1. JSP 작성시 이클립스에서 JDBC 연동 을 하기 위해서는

다이나믹 웹 프로젝트 생성 후에 WebContent > WEB-INF > lib 폴더에 ojdbc14.jar 파일을 넣어야 함.






DBConn 클래스를 이용한 오라클 연결 테스트



//DBConn.java -> Java Resources > src 폴더에 패키지 생성 후 복사할 것.

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}






SQL 쿼리 전송 테스트1 (scott 계정)


//회원 테이블 생성. 회원번호, 이름, 전화번호. 시퀀스 객체 생성.

CREATE TABLE member (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member

ADD CONSTRAINT member_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE memberSeq;



//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, 'hong', '111-1111')


//DBConn.java

//Oracle02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String str = "";


try {

//연결

Connection conn = DBConn.getConnection();

//쿼리 준비

//쿼리 작성시 끝에 ; 표시하지 말것.

String sql = String.format("INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, 'lee', '123-1234')");

//쿼리 실행

//Java에서 쿼리를 실행하면 

//내부적으로 COMMIT은 자동 실행됨.

//executeUpdate() 메소드는 DML문인 경우만 실행.

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(sql);

//결과 출력

str = String.format("%d개의 행이 입력되었습니다.<br>", count);

}catch(Exception e) {

str = e.toString();

}

%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<h2>SQL 쿼리 전송 테스트1</h2>

<div><%=str%></div>

</body>

</html>






회원 테이블 자료 출력 테스트. SELECT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//SELECT mid, name, tel FROM member ORDER BY mid



//DBConn.java

//Oracle03.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


StringBuilder str = new StringBuilder();


try {

Connection conn = DBConn.getConnection();

String sql = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

str.append("<table border=\"1\"><tbody><tr><th align=\"center\">mid</th><th align=\"center\">name</th><th align=\"center\">tel</th></tr>");

while(rs.next()) { //row 단위 접근

int mid = rs.getInt("mid"); //column 단위 접근

String name = rs.getString("name");

String tel = rs.getString("tel");

str.append(String.format("<tr><td align=\"center\">%d</td><td align=\"center\">%s</td><td align=\"center\">%s</td></tr>", mid, name, tel));

}

str.append("</tbody></table>");

//ResultSet 객체 소멸->필수

rs.close();

} catch(Exception e) {

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<h2>SQL 쿼리 전송 테스트2</h2>

<div><%=str%></div>

</body>

</html>





문제) member 테이블의 회원수를 출력하는 프로그램 작성.

//SELECT COUNT(*) AS count FROM member


//DBConn.java

//Oracle04.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String str = "";

try {

Connection conn = DBConn.getConnection();

String sql = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) { //row 단위 접근

int count = rs.getInt("count");

str = String.format("회원수 : %d 명<br>", count);

}

//ResultSet 객체 소멸->필수

rs.close();

} catch(Exception e) {

str = e.toString();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<h2>SQL 쿼리 전송 테스트3</h2>

<div><%=str%></div>

</body>

</html>








문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성. 오라클, JSP 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [        ]

전화번호 [         ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------




//DBConn.java

//Oracle05.jsp -> 입력, 출력 화면 구성용 페이지. 액션 처리 겸용.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


int rowcount = 0;

String count = "";

String insert_check = "";

StringBuilder str = new StringBuilder();

try {

//데이터 베이스 연결

Connection conn = DBConn.getConnection();

//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_tel = request.getParameter("tel");

//submit 되기전 각 항목을 입력받기 전이라면 아래의 제어문 이 실행되지 않음.

if (r_name != null && r_tel != null) {

String sql0 = String.format("INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, '%s', '%s')", r_name, r_tel);

Statement stmt0 = conn.createStatement();

rowcount = stmt0.executeUpdate(sql0);

if (rowcount == 1) {

insert_check = "정상적으로 입력이 완료되었습니다.";

}

}

String sql1 = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt1 = conn.createStatement();

ResultSet rs1 = stmt1.executeQuery(sql1);

while(rs1.next()) { //row 단위 접근

count = rs1.getString("count");

}

String sql2 = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

Statement stmt2 = conn.createStatement();

ResultSet rs2 = stmt2.executeQuery(sql2);

while(rs2.next()) { //row 단위 접근

int mid = rs2.getInt("mid"); //column 단위 접근

String name = rs2.getString("name");

String tel = rs2.getString("tel");

str.append(String.format("<tr><td align=\"center\">%d</td><td align=\"center\">%s</td><td align=\"center\">%s</td></tr>", mid, name, tel));

}


rs1.close();

rs2.close();

} catch(Exception e) {

count = e.toString();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

if (name.value == "") {

msg.style.display = "inline";

name.value = "";

name.focus();

return;

}

if (tel.value == "") {

msg.style.display = "inline";

tel.value = "";

tel.focus();

return;

}

obj.form.submit();

}


</script>

</head>

<body>

<h2>이름 전화번호 저장 JDBC 프로그램</h2>

<form method="post">

이름 <input type="text" name="name" id="name"><br>

전화번호 <input type="text" name="tel" id="tel"><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="display:none; color:red;">모든 항목을 입력해야함</span>

<font color="blue"><%=insert_check%></font>

</form>

<h3>출력 -------------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<%=str%>

</tbody>

</table>

</div>

</body>

</html>







문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성. 오라클, JSP 이용. JSP 파일 분할 / forward() 메소드 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [        ]

전화번호 [         ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------


//DBConn.java


//Oracle06.jsp -> 입력, 출력 화면 구성 페이지 및 데이터 베이스 select 액션 처리

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String count = "";

StringBuilder str = new StringBuilder();

try {

//데이터 베이스 연결

Connection conn = DBConn.getConnection();

//Insert와 관련된 액션은 Oracle06_Insert.jsp에서 구현

String sql1 = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt1 = conn.createStatement();

ResultSet rs1 = stmt1.executeQuery(sql1);

while(rs1.next()) { //row 단위 접근

count = rs1.getString("count");

}

String sql2 = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

Statement stmt2 = conn.createStatement();

ResultSet rs2 = stmt2.executeQuery(sql2);

while(rs2.next()) { //row 단위 접근

int mid = rs2.getInt("mid"); //column 단위 접근

String name = rs2.getString("name");

String tel = rs2.getString("tel");

str.append(String.format("<tr><td align=\"center\">%d</td><td align=\"center\">%s</td><td align=\"center\">%s</td></tr>", mid, name, tel));

}


rs1.close();

rs2.close();

} catch(Exception e) {

count = e.toString();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

if (name.value == "") {

msg.style.display = "inline";

name.value = "";

name.focus();

return;

}

if (tel.value == "") {

msg.style.display = "inline";

tel.value = "";

tel.focus();

return;

}

obj.form.submit();

}


</script>

</head>

<body>

<h2>이름 전화번호 저장 JDBC 프로그램</h2>

<form action="Oracle06_Insert.jsp" method="post">

이름 <input type="text" name="name" id="name"><br>

전화번호 <input type="text" name="tel" id="tel"><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="display:none; color:red;">모든 항목을 입력해야함</span>

</form>

<h3>출력 -------------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<%=str%>

</tbody>

</table>

</div>

</body>

</html>


//Oracle06_Insert.jsp -> 데이터 베이스 insert 액션 처리

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_tel = request.getParameter("tel");

try {

//데이터 베이스 연결

Connection conn = DBConn.getConnection();

String sql0 = String.format("INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, '%s', '%s')", r_name, r_tel);

Statement stmt0 = conn.createStatement();

stmt0.executeUpdate(sql0);

} catch (Exception e) {

}

//입력이 끝나면 Oracle06.jsp로 자동 이동해야 함.

//sendRedirect() 메소드 이용.

String url = String.format("Oracle06.jsp");

response.sendRedirect(url);


%>





문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성. 오라클, JSP 이용. JSP 파일 분할 / forward() 메소드 이용.

데이터 입력과 출력을 동시 실행.  삭제 기능 추가.


실행 예)

이름 [        ]

전화번호 [         ]

[ 등록 ]


---------------------------------

전체 회원수 : 2명

---------------------------------

회원번호 이름   전화번호     삭제

---------------------------------

1        홍길동 010-123-1234 삭제

2        김길동 010-222-3333 삭제

---------------------------------


//DBconn.java

//Oracle07.jsp -> 입력, 출력 화면 구성 페이지. 출력 액션만 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String count = "";

StringBuilder str = new StringBuilder();

try {


Connection conn = DBConn.getConnection();


String sql1 = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt1 = conn.createStatement();

ResultSet rs1 = stmt1.executeQuery(sql1);

while(rs1.next()) { //row 단위 접근

count = rs1.getString("count");

}

String sql2 = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

Statement stmt2 = conn.createStatement();

ResultSet rs2 = stmt2.executeQuery(sql2);

while(rs2.next()) { //row 단위 접근

int mid = rs2.getInt("mid"); //column 단위 접근

String name = rs2.getString("name");

String tel = rs2.getString("tel");

str.append(String.format("<tr><td align=\"center\">%d</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td><input type=\"button\" value=\"삭제\" onclick=\"myDel(%d)\"></td></tr>", mid, name, tel, mid));

}


rs1.close();

rs2.close();

} catch(Exception e) {

count = e.toString();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

if (name.value == "") {

msg.style.display = "inline";

name.value = "";

name.focus();

return;

}

if (tel.value == "") {

msg.style.display = "inline";

tel.value = "";

tel.focus();

return;

}

obj.form.submit();

}

function myDel(num) {

if (confirm("선택한 자료를 삭제하시겠습니까?")) {

//URL 요청 명령

window.location.href = "Oracle07_Delete.jsp?mid="+num;

}

}


</script>

</head>

<body>

<h2>이름 전화번호 저장 JDBC 프로그램3</h2>

<form action="Oracle07_Insert.jsp" method="post">

이름 <input type="text" name="name" id="name"><br>

전화번호 <input type="text" name="tel" id="tel"><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="display:none; color:red;">모든 항목을 입력해야함</span>

</form>

<h3>출력 -------------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th><th>삭제</th></tr>

<%=str%>

</tbody>

</table>

</div>

</body>

</html>



//Oracle07_Insert.jsp  -> 입력 액션만 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_tel = request.getParameter("tel");

try {

//데이터 베이스 연결

Connection conn = DBConn.getConnection();

String sql0 = String.format("INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, '%s', '%s')", r_name, r_tel);

Statement stmt0 = conn.createStatement();

stmt0.executeUpdate(sql0);

} catch (Exception e) {

}

//입력이 끝나면 Oracle07.jsp로 자동 이동해야 함.

//sendRedirect() 메소드 이용.

String url = String.format("Oracle07.jsp");

response.sendRedirect(url);


%>



//Oracle07_Delete.jsp  -> 삭제 액션만 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String mid = request.getParameter("mid");


if (mid != null) {

try {

Connection conn = DBConn.getConnection();

String sql = String.format("DELETE member WHERE mid=%s", mid);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch (Exception e) {

}

}


//삭제처리후 메인 페이지 자동 이동

String url = String.format("Oracle07.jsp");

response.sendRedirect(url);


%>





문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 오라클 이용. JSP 이용.

총점 기준 정렬(내림차순) 출력.


판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 -------------------------

이름 [        ]

국어 [        ]

영어 [        ]

수학 [        ]

[ 등록 ]



---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------



---------------------------------------------

--오라클에 성적 저장용 테이블 생성

CREATE TABLE score (

sid NUMBER --PK, 자동 번호 부여

,name VARCHAR2(10)

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score

ADD CONSTRAINT score_sid_pk PRIMARY KEY (sid);

ALTER TABLE score

ADD CONSTRAINT score_kor_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_mat_ck CHECK (mat BETWEEN 0 AND 100);


--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE scoreSeq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score (sid, name, kor, eng, mat)

VALUES (scoreSeq.nextval, 'hong', 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave


--, 조건검사 쿼리 추가 ->합격, 불합격, 과락 출력

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade


FROM score

ORDER BY tot DESC


--scoewView를 이용한 select 쿼리

SELECT sid, name, kor, eng, mat, tot, ave, grade

FROM score

ORDER BY tot DESC;




//DBConn.java

//Oracle08.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


StringBuilder str = new StringBuilder();


try {

Connection conn = DBConn.getConnection();

String sql = String.format ("SELECT name, kor, eng, mat, tot, ave, grade FROM scoreView ORDER BY tot DESC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

int rank = 1;

while (rs.next()) {

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");

str.append (String.format("<tr><td align=\"center\">%d등</td><td align=\"center\">%s</td><td align=\"right\">%d</td><td align=\"right\">%d</td><td align=\"right\">%d</td><td align=\"right\">%d</td><td align=\"right\">%.1f</td><td align=\"center\">%s</td></tr>", rank++, name, kor, eng, mat, tot, ave, grade));

}

} catch(Exception e) {

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var kor = document.getElementById("kor");

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var korVal = parseInt(kor.value);

var engVal = parseInt(eng.value);

var matVal = parseInt(mat.value);

var msg1 = document.getElementById("msg1");

var msg2 = document.getElementById("msg2");

msg1.style.display = "none";

msg2.style.display = "none";

if (name.value == "") {

msg1.style.display = "inline";

name.focus();

return;

}

if (kor.value.match(/[^0-9]/) || korVal > 100 || kor.value == "") {

msg2.style.display = "inline";

kor.value = "";

kor.focus();

return;

}

if (eng.value.match(/[^0-9]/) || engVal > 100 || eng.value == "") {

msg2.style.display = "inline";

eng.value = "";

eng.focus();

return;

}

if (mat.value.match(/[^0-9]/)|| matVal > 100 || mat.value == "") {

msg2.style.display = "inline";

mat.value = "";

mat.focus();

return;

}

//모든 데이터 확인 후 서브밋

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h2>성적 처리</h2>

<form action="Oracle08_Insert.jsp" method="post">

이름 <input type="text" style="width:80px;" name="name" id="name"><br>

국어(0~100) <input type="text" style="width:80px;" name="kor" id="kor"><br>

영어(0~100) <input type="text" style="width:80px;" name="eng" id="eng"><br>

수학(0~100) <input type="text" style="width:80px;" name="mat" id="mat"><br>

<input type="button" value="등록" onclick="myFunc(this)"><br>

<span id="msg1" style="color:red; display:none;">모든 항목을 입력해야 합니다.</span><br>

<span id="msg2" style="color:red; display:none;">반드시 국어, 영어, 수학은 0~100 사이 점수를 입력해야 합니다.</span><br>

</form>

<h3>출력 -------------</h3>

<div>

<table border="1" style="width:500px;">

<tbody>

<tr><th>등수</th><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th><th>판정</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>



//Oracle08_Insert.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_kor = request.getParameter("kor");

String r_eng = request.getParameter("eng");

String r_mat = request.getParameter("mat");

try {

//데이터 베이스 연결

Connection conn = DBConn.getConnection();

String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %s, %s, %s)", r_name, r_kor, r_eng, r_mat);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch (Exception e) {

}


String url = String.format("Oracle08.jsp");

response.sendRedirect(url);


%>






문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성4. 오라클, JSP 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [        ]

전화번호 [         ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------


//DBConn.java

//MemberDTO.java -> 자료 처리 전용 클래스. 멤버변수. getter, setter

package com.test;


public class MemberDTO {

private int mid;

private String name, tel;

public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}





//MemberDAO.java -> 데이터베이스 액세스 담당 클래스. 입력, 출력, 연결용 메소드.

package com.test;


import java.util.*;

import java.sql.*;


public class MemberDAO {

private Connection conn;

//연결 전용 메소드

public void connect() throws SQLException, ClassNotFoundException{

conn  = DBConn.getConnection();

}

//연결 해제 전용 메소드

public void close() throws SQLException{

DBConn.close();

conn = null;

}

//입력 메소드 즉, INSERT 쿼리 실행

public int add(MemberDTO dto) throws SQLException{

int result = 0;

String sql = String.format("INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, '%s', '%s')", dto.getName(), dto.getTel());


//쿼리 실행

//Java에서 쿼리를 실행하면 

//내부적으로 COMMIT은 자동 실행됨.

//executeUpdate() 메소드는 DML문인 경우만 실행.

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

//회원수 출력 전용 메소드

public int count() throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql); //결과집합

while(rs.next()) { //row 단위 접근

int count = rs.getInt("count"); //column 단위 접근

result = count;

}

rs.close();

return result;

}

//출력 메소드 즉, SELECT 쿼리 실행

public ArrayList<MemberDTO> lists() throws SQLException{

ArrayList<MemberDTO> arrayList = new ArrayList<MemberDTO>();

//SELECT 쿼리 준비

String sql = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

//쿼리 실행

//executeQuery() 메소드는 DQL문인 경우만 실행.

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql); //결과집합

//결과 집합(ResultSet)을 리턴해야 된다.

//결과 집합은 특성상 이 메소드를 벗어날 수 없다. 왜냐하면 ResultSet은 메소드 빠져나가기 전에 반드시 클로즈하기 때문.

//결과 집합을 -> 결렉션 저장

//컬렉션을 리턴.

while(rs.next()) { //row 단위 접근

int mid = rs.getInt("mid"); //column 단위 접근

String name = rs.getString("name");

String tel = rs.getString("tel");

MemberDTO dto = new MemberDTO();

dto.setMid(mid);

dto.setName(name);

dto.setTel(tel);

arrayList.add(dto);

}

rs.close();

return arrayList;

}


}





//Oracle09.jsp -> 입력, 출력 화면구성. 출력 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String count = "";

StringBuilder str = new StringBuilder();

MemberDAO dao = new MemberDAO();

try {


//데이터 베이스 연결 구문

dao.connect();


//회원수를 돌려주는 메소드 호출.

count = String.format("%d", dao.count());

//회원 명단을 돌려주는 메소드 호출.

for (MemberDTO dto : dao.lists()) {

str.append("<tr>");

str.append(String.format("<td align=\"center\">%d</td><td align=\"center\">%s</td><td align=\"center\">%s</td><td><input type=\"button\" value=\"삭제\" onclick=\"myDel(%d)\"></td>", dto.getMid(), dto.getName(), dto.getTel(), dto.getMid()));

str.append("</tr>");

}

} catch(Exception e) {

count = e.toString();

} finally {

dao.close();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

if (name.value == "") {

msg.style.display = "inline";

name.value = "";

name.focus();

return;

}

if (tel.value == "") {

msg.style.display = "inline";

tel.value = "";

tel.focus();

return;

}

obj.form.submit();

}

function myDel(num) {

if (confirm("선택한 자료를 삭제하시겠습니까?")) {

//URL 요청 명령

window.location.href = "Oracle09_Delete.jsp?mid="+num;

}

}


</script>

</head>

<body>

<div>

<h2>이름 전화번호 저장 JDBC 프로그램4</h2>

<form action="Oracle09_Insert.jsp" method="post">

이름 <input type="text" name="name" id="name"><br>

전화번호 <input type="text" name="tel" id="tel"><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="display:none; color:red;">모든 항목을 입력해야함</span>

</form>

<h3>출력 -------------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th><th>삭제</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//Oracle09_Insert.jsp -> 입력 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_tel = request.getParameter("tel");

MemberDAO dao = new MemberDAO();

try {

//데이터 베이스 연결

dao.connect();


MemberDTO dto = new MemberDTO();

dto.setName(r_name);

dto.setTel(r_tel);

dao.add(dto);

} catch (Exception e) {

} finally {

dao.close();

}

//입력이 끝나면 Oracle09.jsp로 자동 이동해야 함.

//sendRedirect() 메소드 이용.

String url = String.format("Oracle09.jsp");

response.sendRedirect(url);


%>



//Oracle09_Delete.jsp -> 삭제 액션 처리.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


String num = request.getParameter("num");


MemberDAO dao = new MemberDAO();


if (num != null) {

try {

dao.connect();

dao.remove(Integer.parseInt(num));

} catch (Exception e) {

}

}


//삭제처리후 메인 페이지 자동 이동

String url = String.format("Oracle09.jsp");

response.sendRedirect(url);


%>








문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 오라클 이용. JSP 이용. DAO / DTO 분할구현 후 이용하는 방식사용.

총점 기준 정렬(내림차순) 출력.


판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 -------------------------

이름 [        ]

국어 [        ]

영어 [        ]

수학 [        ]

[ 등록 ]



---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------



//DBConn.java

//ScoreDTO.java

package com.test;


public class ScoreDTO {

private int sid, kor, eng, mat, tot;

private String name;

private String grade;

private double avg;

public int getSid() {

return sid;

}

public void setSid(int sid) {

this.sid = sid;

}

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 String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}

public double getAvg() {

return avg;

}

public void setAvg(double avg) {

this.avg = avg;

}


}






//ScoreDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class ScoreDAO {


private Connection conn;

public void connect () throws SQLException, ClassNotFoundException{

conn = DBConn.getConnection();

}


public void close() throws SQLException{

DBConn.close();

conn = null;

}


public int add(ScoreDTO dto) throws SQLException{

int result = 0; // 1행이 입력되었습니다. 에서 1을 반환받기 위해 사용.

String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %d, %d, %d)", dto.getName(), dto.getKor(), dto.getEng(), dto.getMat());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int remove(int num) throws SQLException{

int result = 0; // 1행이 입력되었습니다. 에서 1을 반환받기 위해 사용.

String sql = String.format("DELETE score WHERE sid=%s", num);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}


public ArrayList<ScoreDTO> lists() throws SQLException {

ArrayList<ScoreDTO> arrayList = new ArrayList<ScoreDTO>();

//쿼리 준비

String sql = String.format("SELECT sid, name, kor, eng, mat, (kor+eng+mat) as tot, (kor+eng+mat)/3 as ave, case when ((kor+eng+mat)/3 >= 60) and (kor<40 or eng<40 or mat<40) then '과락' when ((kor+eng+mat)/3 >= 60) then '합격' else '불합격' end as grade FROM score ORDER BY (kor+eng+mat) DESC");

//쿼리 실행

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) { //row 단위 접근

int sid = rs.getInt("sid"); //column 단위 접근

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double avg = rs.getDouble("ave");

String grade = rs.getString("grade");

ScoreDTO dto = new ScoreDTO();

dto.setSid(sid);

dto.setName(name);

dto.setKor(kor);

dto.setEng(eng);

dto.setMat(mat);

dto.setTot(tot);

dto.setAvg(avg);

dto.setGrade(grade);

arrayList.add(dto);

}

rs.close();

return arrayList;

}

}





//Oracle10.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<%


StringBuilder str = new StringBuilder();

ScoreDAO dao = new ScoreDAO();


try {

dao.connect();

int rank = 1;

for (ScoreDTO dto :dao.lists()) {

str.append (String.format("<tr><td class=\"style01\">%d등</td><td class=\"style01\">%s</td><td class=\"style02\">%d</td><td class=\"style02\">%d</td><td class=\"style02\">%d</td><td class=\"style02\">%d</td><td class=\"style02\">%.1f</td><td class=\"style01\">%s</td><td class=\"style01\"><input type=\"button\" value=\"삭제\" onclick=\"myDel(%s)\"></td></tr>", rank++, dto.getName(), dto.getKor(), dto.getEng(), dto.getMat(), dto.getTot(), dto.getAvg(), dto.getGrade(), dto.getSid()));

}

} catch(Exception e) {

} finally {

dao.close();

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<style type="text/css">

.style01 {

text-align: center;

}

.style02 {

text-align: right;

}



</style>

<script type="text/javascript">


function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var kor = document.getElementById("kor");

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var korVal = parseInt(kor.value);

var engVal = parseInt(eng.value);

var matVal = parseInt(mat.value);

var msg1 = document.getElementById("msg1");

var msg2 = document.getElementById("msg2");

msg1.style.display = "none";

msg2.style.display = "none";

if (name.value == "") {

msg1.style.display = "inline";

name.focus();

return;

}

if (kor.value.match(/[^0-9]/) || korVal > 100 || kor.value == "") {

msg2.style.display = "inline";

kor.value = "";

kor.focus();

return;

}

if (eng.value.match(/[^0-9]/) || engVal > 100 || eng.value == "") {

msg2.style.display = "inline";

eng.value = "";

eng.focus();

return;

}

if (mat.value.match(/[^0-9]/)|| matVal > 100 || mat.value == "") {

msg2.style.display = "inline";

mat.value = "";

mat.focus();

return;

}

//모든 데이터 확인 후 서브밋

obj.form.submit();

}

function myDel(num) {

if (confirm("선택한 자료를 삭제하시겠습니까?")) {

//URL 요청 명령

window.location.href = "Oracle10_Delete.jsp?sid="+num;

}

}


</script>

</head>

<body>

<div>

<h2>성적 처리</h2>

<form action="Oracle10_Insert.jsp" method="post">

이름 <input type="text" style="width:80px;" name="name" id="name"><br>

국어(0~100) <input type="text" style="width:80px;" name="kor" id="kor"><br>

영어(0~100) <input type="text" style="width:80px;" name="eng" id="eng"><br>

수학(0~100) <input type="text" style="width:80px;" name="mat" id="mat"><br>

<input type="button" value="등록" onclick="myFunc(this)"><br>

<span id="msg1" style="color:red; display:none;">모든 항목을 입력해야 합니다.</span><br>

<span id="msg2" style="color:red; display:none;">반드시 국어, 영어, 수학은 0~100 사이 점수를 입력해야 합니다.</span><br>

</form>

<h3>출력 -------------</h3>

<div>

<table border="1" style="width:500px;">

<tbody>

<tr><th>등수</th><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th><th>판정</th><th>삭제</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//Oracle10_Insert.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String r_name = request.getParameter("name");

String r_kor = request.getParameter("kor");

String r_eng = request.getParameter("eng");

String r_mat = request.getParameter("mat");

ScoreDAO dao = new ScoreDAO();

ScoreDTO dto = new ScoreDTO();

try {

//데이터 베이스 연결

dao.connect();

dto.setName(r_name);

dto.setKor(Integer.parseInt(r_kor));

dto.setEng(Integer.parseInt(r_eng));

dto.setMat(Integer.parseInt(r_mat));

dao.add(dto);

} catch (Exception e) {

} finally {

dao.close();

}


String url = String.format("Oracle10.jsp");

response.sendRedirect(url);


%>




//Oracle10_Delete.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.sql.*" %>

<%@ page import="com.test.*" %>

<% 


//데이터 수신

request.setCharacterEncoding("euc-kr");

String sid = request.getParameter("sid");

ScoreDAO dao = new ScoreDAO();

ScoreDTO dto = new ScoreDTO();

try {

//데이터 베이스 연결

dao.connect();

dao.remove(Integer.parseInt(sid));

} catch (Exception e) {

} finally {

dao.close();

}


String url = String.format("Oracle10.jsp");

response.sendRedirect(url);


%>



WRITTEN BY
빨강꼬마

,

문제) 임의의 수를 입력 받아서 3의 배수, 4의 배수로 구분해서 출력.


실행 예)

임의의 정수(3 또는 4의 배수) [3  ] [결과]


입력받은 숫자 : 3

구분 : 3의 배수



//Send_Receive07.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%


String number = request.getParameter("number");


StringBuilder str = new StringBuilder();

if (number != null) {

int numInt = Integer.parseInt(number);

str.append(String.format("입력받은 숫자 : %s<br>구분 : ", number));

String numStr = "3또는 4의 배수가 아닌 수";

if (numInt%3 == 0) {

numStr = "3의 배수";

}

if (numInt%4 == 0) {

numStr = "4의 배수";

}

if (numInt%12 == 0) {

numStr = "3과 4의 공배수";

}

str.append(numStr);

}

%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var num = document.getElementById("number");

var msg = document.getElementById("msg");

var msg1 = document.getElementById("msg1");


msg.style.display = "none";

msg1.style.display = "none";

if (num.value.match(/[^0-9]/)) {

msg.style.display = "inline";

num.value = "";

num.focus();

} else if (num.value == "") {

msg1.style.display = "inline";

num.value = "";

num.focus();

} else {

obj.form.submit();

}

}


</script>

</head>

<body>

<div>

<h2>데이터 송수신 테스트</h2>

<form method="post">

임의의 정수(3 또는 4의 배수) <input type="text" style="width:80px;" name="number" id="number">

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">숫자만 입력하세요</span>

<span id="msg1" style="color:red; display:none;">항목을 입력하세요</span>

</form>

<h3>출력----------------------</h3>

<div><%=str%></div>

</div>

</body>

</html>







문제) 국어, 영어, 수학 점수를 입력 받아서 판정 결과 출력. JSP 이용.

판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

국어(0~100) [XX  ]

영어(0~100) [YY  ]

수학(0~100) [ZZ  ]

[ 결과 ]


입력받은 점수 : 국어 XX, 영어 YY, 수학 ZZ

판정 결과 : 합격


//Send_Receive08.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%


String korData = request.getParameter("kor");

String engData = request.getParameter("eng");

String matData = request.getParameter("mat");


StringBuilder str = new StringBuilder();

if (korData != null) {

int korInt = Integer.parseInt(korData);

int engInt = Integer.parseInt(engData);

int matInt = Integer.parseInt(matData);

str.append(String.format("입력받은 점수 : 국어 %s, 영어 %s, 수학 %s<br>판정 결과 : ", korData, engData, matData));

String msg = "불합격";

                

        double avg = (korInt + engInt + matInt) / 3.0;

        

        if (avg>=60) {

            if (korInt>=40 && engInt>=40 && matInt>=40) {

                msg = "합격";

            } else {

                msg = "과락";

            }

        }        

        str.append(msg);

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

var kor = document.getElementById("kor");

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var korVal = parseInt(kor.value);

var engVal = parseInt(eng.value);

var matVal = parseInt(mat.value);

var msg1 = document.getElementById("msg1");

var msg2 = document.getElementById("msg2");

msg1.style.display = "none";

msg2.style.display = "none";

//숫자 검사 - 음수도 걸러짐

if (kor.value.match(/[^0-9]/)) {

msg2.style.display = "inline";

kor.value = "";

kor.focus();

return;

}

if (eng.value.match(/[^0-9]/)) {

msg2.style.display = "inline";

eng.value = "";

eng.focus();

return;

}

if (mat.value.match(/[^0-9]/)) {

msg2.style.display = "inline";

mat.value = "";

mat.focus();

return;

}

//범위 및 빈칸 검사

if (kor.value == "" || korVal > 100) {

msg1.style.display = "inline";

kor.value = "";

kor.focus();

return;

}

if (eng.value == "" || engVal > 100) {

msg1.style.display = "inline";

eng.focus();

return;

}

if (mat.value == "" || matVal > 100) {

msg1.style.display = "inline";

mat.focus();

return;

}

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h2>데이터 송수신 테스트</h2>

<form method="post">

국어(0~100) <input type="text" style="width:80px" name="kor" id="kor"><br>

영어(0~100) <input type="text" style="width:80px" name="eng" id="eng"><br>

수학(0~100) <input type="text" style="width:80px" name="mat" id="mat"><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg1" style="color:red; display:none;">모든 항목을 입력해야 합니다.</span>

<span id="msg2" style="color:red; display:none;">0~100사이의 숫자만 입력하세요.</span>

</form>

<h3>출력----------------------</h3>

<div><%=str%></div>

</div>

</body>

</html>






문제) 만년달력. JSP 이용.


//Send_Receive09.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>

<%


String syear = request.getParameter("year");

String smonth = request.getParameter("month");


StringBuilder yearLists = new StringBuilder();

StringBuilder monthLists = new StringBuilder();

//현재 년도를 얻은 후 +10, -10년 정도를 <option> 태그에 등록

Calendar calendar = new GregorianCalendar();

int cyear = calendar.get(Calendar.YEAR);

int cmonth = calendar.get(Calendar.MONTH) + 1;

//전달받은 년도, 월이 없는 경우 현재 년도, 월로 셋팅

if (syear == null && smonth == null) {

syear = String.valueOf(cyear);

smonth = String.valueOf(cmonth);

}

//전달 받는 년도, 월을 정수형으로 형 변환

int iyear = Integer.parseInt(syear);

int imonth = Integer.parseInt(smonth);

for (int a=(cyear-10) ; a<=(cyear+10) ; a++) {

if (a == iyear) {

yearLists.append(String.format("<option value=\"%d\" selected=\"selected\">%d</option>", a, a));

} else {

yearLists.append(String.format("<option value=\"%d\">%d</option>", a, a));

}

}

for (int a=1; a<=12; a++) {

if (a == imonth) {

monthLists.append(String.format("<option value=\"%d\" selected=\"selected\">%d</option>", a, a));

} else {

monthLists.append(String.format("<option value=\"%d\">%d</option>", a, a));

}

}

//만년달력 생성 과정 추가

int total = (iyear-1)*365 + ((iyear-1)/4 - (iyear-1)/100 + (iyear-1)/400);

int[] m = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

for (int a=0; a<imonth-1; a++) {

total += m[a];

}

//올해가 윤년이면서 2월 이상인 경우 +1

if (imonth>=3 && (iyear%4==0 && iyear%100!=0 || iyear%400==0)) {

total++;

}

//특정 일까지의 날짜수 더하기

total += 1;

//요일 계산

int week = total%7; //0 일요일, 1 월요일, 2 화요일, ...


//해당 월의 마지막 날짜 구하기

int lastDay = m[imonth-1];

if (imonth==2 && (iyear%4==0 && iyear%100!=0 || iyear%400==0)) {

lastDay = 29;

}

//요일, 마지막 날짜를 얻은 후 달력 출력.

/* StringBuilder sb = new StringBuilder();

sb.append(String.format("----- %d년 %d월 -----<br>", iyear, imonth));

sb.append(String.format(" 일 월 화 수 목 금 토<br>"));

for (int count=1; count<=week; count++) {

sb.append(String.format("%s", ""));

}

for (int day=1; day<=lastDay; day++) {

sb.append(String.format("%d", day));

if ((day+week)%7 == 0) {

sb.append(String.format("<br>"));

}

} */

//테이블 태그를 포함한 결과 출력


String str = "";

str += "<table><tbody>";

str += "<tr><th>일</th><th>월</th><th>화</th><th>수</th><th>목</th><th>금</th><th>토</th></tr>";

str += "<tr>";

//해당월 1일의 특정 요일에 해당하는 빈 칸 출력

for (int a=1; a<=week; a++) {

str += "<td></td>";

}

//해당월 1일부터 마지막 날까지 출력

for(int a=1; a<=lastDay; a++) {

str += "<td style=\"text-align:center\">"+a+"</td>";

//일주일 단위로 행 변경

if (((a+week)%7)==0) {

str += "</tr><tr>";

}

}

str += "</tr></tbody></table>";

%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">

function myFunc(obj) {

obj.form.submit();

}

</script>

</head>

<body>

<div>

<h2>만년달력 출력</h2>

<form method="get">

년 <select name="year" id="year" onchange="myFunc(this)"><%=yearLists%></select>

월 <select name="month" id="month" onchange="myFunc(this)"><%=monthLists%></select>

</form>

<h3>출력 ---------------</h3>

<div><%=str%></div>

</div>

</body>

</html>






POST, GET 전송 방식



1. 클라이언트가 서버에 데이터를 전송하는 방식. 2가지.

 - 인코딩 방식이 다름.


2. POST 방식 특성

- 주소 요청시 헤더 부분에 데이터를 포함해서 전송하는 방식.

- 대용량 데이터 전송 가능

- 전송되는 데이터가 외부에 노출되지 않는다.

- 편지와 같은 특성을 가진다.

- 중요한 정보는 POST 방식으로 전송하는 것이 안전함.

- 한글 전송시 POST 방식으로 보내는 것이 안전함.

- 특수문자가 포함된 문자열 전송시 POST 방식으로 전송하는 것이 안전함.


형식

<form action="주소" method="post">

<input ...>

</form>



3. GET 방식 특성

- 주소 요청시 주소 부분에 데이터를 포함해서 전송하는 방식.

- 한정된 용량 범위의 데이터 전송 가능 (4Kb 정도 (4000자))

- 전송되는 데이터가 화면에 노출된다.

- 엽서와 같은 특성을 가진다.


형식1

<form action="주소" method="get">

<input ...>

</form>


형식2

<a href="주소?식별자=값&식별자=값&...">메시지</a>






구구단 출력 (GET 방식 전송 이용)


실행 예)

1단 2단 3단 4단 ... 9단       -> 하이퍼링크


-----------------------------

5 * 1 = 5

5 * 2 = 10

...

5 * 9 = 45





//Send_Receive10.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%


String num = request.getParameter("num");

StringBuilder str = new StringBuilder();


if (num != null) {

int data = Integer.parseInt(num);

for (int a=1; a<=9 ; a++) {

str.append(String.format("%d * %d = %d<br>", data, a, (data*a)));

}

}


%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">

</script>

<style type="text/css">

 a {text-decoration: none; color:grey;}

 a:hover {text-decoration: underline; color:red;}

</style>

</head>

<body>

<div>

<h2>데이터 송수신(GET 전송방식) 테스트</h2>

<div>

<a href="Send_Receive10.jsp?num=1">1단</a> 

<a href="Send_Receive10.jsp?num=2">2단</a> 

<a href="Send_Receive10.jsp?num=3">3단</a> 

<a href="Send_Receive10.jsp?num=4">4단</a> 

<a href="Send_Receive10.jsp?num=5">5단</a> 

<a href="Send_Receive10.jsp?num=6">6단</a> 

<a href="Send_Receive10.jsp?num=7">7단</a> 

<a href="Send_Receive10.jsp?num=8">8단</a> 

<a href="Send_Receive10.jsp?num=9">9단</a>

</div>

<h3>출력 ----------------------</h3>

<div><%=str%></div>

</div>

</body>

</html>





forward() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


- 특징

. 재전송 (서버차원에서 URL을 다른 페이지로 변경해버린다)

. 입력(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 출력 전용 페이지(HTML이 포함된 JSP 페이지)

. request.setAttribute() 메소드를 이용해서 데이터를 재전송시킬 수 있다.

. 받을 때는 request.getAttribute() 메소드 이용.

. 재전송 데이터는 객체 형태의 데이터 모두 가능.

. 서버 차원에서 URL을 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 없다.



//Send11.jsp  -> 입력 전용

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

//빈칸검사

//숫자검사

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h3>데이터 송수신 테스트11(재전송)</h3>

<form action="Redirect11.jsp" method="post">

숫자1 <input type="text" name="num1" id="num1"><br>

숫자2 <input type="text" name="num2" id="num2"><br>

연산자 <select name="op"><option value="add">더하기</option>

<option value="sub">빼기</option><option value="mul">곱하기</option>

<option value="div">나누기</option></select><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">모든 항목을 입력해야 합니다.</span>

</form>

</div>

</body>

</html>


//Redirect11.jsp  -> 처리 전용. 데이터 재전송 과정 추가. JSP 코드만 존재

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//데이터 수신

String num1 = request.getParameter("num1");

String num2 = request.getParameter("num2");

String op = request.getParameter("op");


//처리

int n1 = Integer.parseInt(num1);

int n2 = Integer.parseInt(num2);

double result = 0;

if (op.equals("add")) {

result = n1 + n2;

}

if (op.equals("sub")) {

result = n1 - n2;

}

if (op.equals("mul")) {

result = n1 * n2;

}

if (op.equals("div")) {

result = n1 / (double)n2;

}

//결과 재전송 과정-> Receive11.jsp

//request.setAttribute()는

//forward() 메소드로 페이지 재전송시

//데이터를 보내는 방법

request.setAttribute("result", Double.valueOf(result));

RequestDispatcher dispatcher

= request.getRequestDispatcher("Receive11.jsp");

dispatcher.forward(request, response);

%>




//Receive11.jsp -> 출력 전용

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String num1 = request.getParameter("num1");

String num2 = request.getParameter("num2");

String op = request.getParameter("op");


//forward() 메소드로 페이지 재전송될 때

//request.setAttribute()에 의해서 전달된 데이터를

//받는 방법


Double result = (Double)request.getAttribute("result");

StringBuilder str = new StringBuilder();

str.append(String.format("전달받는 숫자 : %s, %s<br>", num1, num2));

str.append(String.format("전달받는 연산자 : %s<br>", op));

str.append(String.format("결과 : %s<br>", result.toString()));


%>    

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트11(재전송)</h2>

<h3>출력 --------------------</h3>

<div><%=str%></div>

</div>

</body>

</html>






sendRedirect() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


- 특징

. 재전송 (서버차원에서 URL을 다른 페이지로 변경해버린다)

. 요청페이지(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 결과페이지(HTML이 포함된 JSP 페이지)

. 클라이언트 차원에서 URL을 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 있다.

. 재전송 데이터는 GET 방식으로만 전송 가능.

. 재전송 가능한 데이터는 문자열 형태의 데이터만 가능.




//Send12.jsp  -> 입력 전용

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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=EUC-KR">

<title>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

//빈칸검사

//숫자검사

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h3>데이터 송수신 테스트12(재전송)</h3>

<form action="Redirect12.jsp" method="post">

숫자1 <input type="text" name="num1" id="num1"><br>

숫자2 <input type="text" name="num2" id="num2"><br>

연산자 <select name="op"><option value="add">더하기</option>

<option value="sub">빼기</option><option value="mul">곱하기</option>

<option value="div">나누기</option></select><br>

<input type="button" value="결과" onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">모든 항목을 입력해야 합니다.</span>

</form>

</div>

</body>

</html>


//Redirect12.jsp  -> 처리 전용. 데이터 재전송 과정 추가. JSP 코드만 존재

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//데이터 수신

String num1 = request.getParameter("num1");

String num2 = request.getParameter("num2");

String op = request.getParameter("op");


//처리

int n1 = Integer.parseInt(num1);

int n2 = Integer.parseInt(num2);

double result = 0;

if (op.equals("add")) {

result = n1 + n2;

}

if (op.equals("sub")) {

result = n1 - n2;

}

if (op.equals("mul")) {

result = n1 * n2;

}

if (op.equals("div")) {

result = n1 / (double)n2;

}

//결과 재전송 과정-> Receive12.jsp

//sendRedirect() 메소드 이용

String url = String.format("Receive12.jsp?num1=%s&num2=%s&op=%s&result=%s", num1, num2, op, String.valueOf(result));

response.sendRedirect(url);

%>



//Receive12.jsp  -> 출력 전용

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String num1 = request.getParameter("num1");

String num2 = request.getParameter("num2");

String op = request.getParameter("op");

if (op.equals("add")) {

op = "더하기";

}

if (op.equals("sub")) {

op = "빼기";

}

if (op.equals("mul")) {

op = "곱하기";

}

if (op.equals("div")) {

op = "나누기";

}


//sendRedirect() 메소드로 보낸 결과 값 받는 부분

String result = request.getParameter("result");

StringBuilder str = new StringBuilder();

str.append(String.format("전달받는 숫자 : %s, %s<br>", num1, num2));

str.append(String.format("전달받는 연산자 : %s<br>", op));

str.append(String.format("결과 : %s<br>", result));


%>    

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트12(재전송)</h2>

<h3>출력 --------------------</h3>

<div><%=str%></div>

</div>

</body>

</html>






게시판 작성시


글쓰기 페이지(Write.jsp)

-> 글쓰기 버튼

-> 글쓴 내용을 전달받은 페이지는 데이터베이스 입력 과정 실행(Insert.jsp)

-> 글 목록 페이지(List.jsp)로 이동(자동-sendRedirect()) 

-> 글 목록 페이지(List.jsp) 출력

-> 주소창의 주소가 List.jsp로 변경



글쓰기 페이지(Write.jsp)

-> 글쓰기 버튼

-> 글쓴 내용을 전달받은 페이지는 데이터베이스 입력 과정 실행(Insert.jsp)

-> 글 목록 페이지(List.jsp)로 이동(자동-forward()) 

-> 글 목록 페이지(List.jsp) 출력

-> 주소창의 주소가 Insert.jsp로 변경






문제) 국어, 영어, 수학 점수를 입력 받아서 판정 결과 출력. JSP 이용. forward() 메소드 이용한 재전송 처리

판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

국어(0~100) [XX  ]

영어(0~100) [YY  ]

수학(0~100) [ZZ  ]

[ 결과 ]


입력받은 점수 : 국어 XX, 영어 YY, 수학 ZZ

판정 결과 : 합격



//Send13.jsp -> 입력 전용 화면



//Redirect13.jsp -> 처리 전용 화면. 판정 결과만 얻는다.



//Receive13.jsp -> 출력 전용 화면


WRITTEN BY
빨강꼬마

,