'servlet'에 해당하는 글 2건

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

재전송 방법


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
빨강꼬마

,

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

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



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


- 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
빨강꼬마

,