'전체 글'에 해당되는 글 384건

  1. 2019.08.30 3일차 실습
  2. 2019.08.29 CSS - display속성, 배경속성
  3. 2019.08.28 15일차
  4. 2019.08.28 CSS - 선택자
  5. 2019.08.27 14일차
  6. 2019.08.27 10일차
  7. 2019.08.26 13일차
  8. 2019.08.26 게시판
  9. 2019.08.19 12일차
  10. 2019.08.14 11일차

3일차 실습

|
<!--
1. 전체 background를 이미지(img_tree.png)는 한번 조회되고
이미지는 top left 에 위치, div는 이미지를 제외한 영역의 80%를 차지하고
div의 양옆의 margin은 10%씩 할당시키시오 사용 컬러(#d0f0f6)

6. 아래 그림처럼 스타일을 적용하시오. (적용색상: gray)
 -->
<!DOCTYPE html>
<html>
<head>
	<style>

		body{
			background-image:url('img_tree.png');
			margin-left:250px;
			background-repeat:no-repeat;
			background-position:top left;
		}
		
		.center_div{
			border: 1px solid gray;
		    margin-right: 10%;
			margin-left: 10%;
		    background-color:#d0f0f6;
		    size: 80%;
		    text-align: left;
		    padding: 8px;
		}
		
		div{
			border: 2px solid gray;
			width:320px;
			padding: 10px;
			margin: 0;
		}
		
	</style>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<div class="center_div">
	 <h1>1번 - Hello World!</h1>
	 <p>This example contains some advanced CSS methods you may nothave learned yet. But,
	             we will explain these methods in alater chapter in the tutorial.</p>
	</div>
	
	<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
	
	<h2>6번 - Calculate the totalwidth:</h2>
	<img src="flower_big.jpg"width="350" height="263" alt="flower">
	<div>The picture above is350px wide. The total width of this element is also 350px.</div>
	
</body>
</html>

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

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<style>
/*2. <h1>의 배경색은 lightblue, 넓이는 300px,padding은없고 margin은 right/left에만 동일하게 부여하시오*/
	div{
    	border: 1px solid gray;
        width: 300px;
        margin-right: 10%;
        margin-left: 10%;
    }
    
    h1{
    	background-color: lightblue;
        width: 300px;
        margin: auto;
    }

/*3. div2 에 Text가 아래 그림처럼 브라우저의 size가 변경되더라도 가로 400px, 세로 100px 영역 이상 커지지 않도록 스타일을 적용하시오 (적용색상: powderblue)*/
	div2{
    	display: block;
        max-width: 400px;
        min-height:100px;
    	background-color: powderblue;
    }

/*4. 두개의 div는 모두 width가 300px이다. 하단의 div의 총 요소의 넓이를 350px로 만드시오(적용색상:yellow, lightblue)*/

    .ex1{
    	display: block;
    	width:300px;
    	background-color: yellow;
    }
    
    .ex2{
    	display: block;
        width:300px;
        padding: 25px;
    	background-color: lightblue;
    }

/*5. 그림처럼 스타일을 적용하시오. (적용색상: lightgrey, green)*/
	div4{
    	display: inline-block;
    	border: 10px solid green;
        background-color: lightgrey;
		padding: 50px;
        margin: 20px;
    }

/*6. 그림처럼 스타일을 적용하시오. (적용색상: gray)*/
	

</style>
<body>

<div>
  <h1>This is a Heading</h1>
  <p>This is a paragraph.</p>
</div>

<h2>Set the max-width andmin-width of an element</h2>
<p>Resize the browser windowto see the effect.</p>
<div2>This is some text. Thisis some text. This is some text.
This is some text. This is sometext. This is some text.
This is some text. This is sometext. This is some text.</div2>


<h2>Padding and elementwidth</h2>
<div3 class="ex1">This div is 300px wide.</div3>
<br>
<div3 class="ex2">The width of this div is 350px, even though it isdefined as 300px in the CSS.</div3>


<h2>Demonstrating the BoxModel</h2>
<p>The CSS box model isessentially a box
that wraps around every HTMLelement.
It consists of: borders, padding,
margins, and the actualcontent.</p>
<div4>This text is the contentof the box. We have added a 50px padding, 20px margin and a 15px green border.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div4>


</body>
</html>

 

'Bitcamp > BITCAMP - Front Web' 카테고리의 다른 글

5일차  (0) 2019.09.03
4일차 실습  (0) 2019.09.02
3일차  (0) 2019.08.30
CSS - display속성, 배경속성  (0) 2019.08.29
CSS - 선택자  (0) 2019.08.28
And

CSS - display속성, 배경속성

|
<!DOCTYPE html>
<html>
<head>
<style>

/*display 예제 : 태그를 안보이게 하는 선택자*/
  .display-none{display:none}
  .invisible{visibility:hidden}
    
.inline1{
	display: inline-block;
	width: 300px;
	border: 3px solid #999;
}

</style>
<title>Page Title</title>
</head>
<body>

<div class="display-none">1</div> /*display-none 은 visibility:hidden 과 같다.*/
<div>2</div>
<div class="invisible">3</div>
<div>4</div>

<p>pogba<span class="inline1">zidane</span></p>

</body>
</html>
--------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<style>

p{
	border-top:4px dotted red; // style width color를 한줄로 표현
}

p2{
	display:block;
	border:10px solid green;
}

</style>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>

<p>This is aparagraph.</p>

<p2>This is aparagraph.</p2>

</body>
</html>

--------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<style>

div{
    border: 1px solid red;
    margin-top: 100px;
    margin-right: 150px;
    margin-bottom: 100px;
	margin-left: 150px;
    background-color:lightblue;
}

img{
	max-width: 100%; /*요소최대 넓이, 부모넓이만큼*/
    max-height: auto;
    
    /*
    -- 전체화면의 20%이지만 500px이상 커지지 않게 처리
    width: 20%;
    max-width: 500px;
    */
}

</style>
<title>Page Title</title>
</head>
<body>
<div>111111111111111</div>

</body>
</html>

--------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<style>

div{
    border: 1px solid red;
	margin-left: 150px;
}

p.ex1{
	margin-left: inherit; /*부모의 style을 상속받음.*/
}

/*margin Collapse - 중요★★★★★★★★★★★★★★★★★★★★★★★
블록의 top/bottom의 인접 마진은 크기가 큰 마진으로
상회된다.(가장 큰 마진이 작은 마진을 먹어버림 - 서로 붙어있을 경우.)
*/
h1{
	margin : 0 0 50px 0;
}

h2{
	margin : 20px 0 0 0;
}

</style>
<title>Page Title</title>
</head>
<body>
<div>
<p class="ex1">드록바</p>
</div>

<h1>동팡저우</h1>
<h2>날강두</h2>

</body>
</html>

--------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<style>

/*padding만큼 요소 넓이가 넓어진다.*/
div.ex1{
    width: 300px;
	background-color: green
}

div.ex2{
	width: 300px;
    padding: 25px;
    background-color: lightblue;
}

/*요소의 넓이를 고정
padding 설정 시 content의 size가 줄어든다.
*/
div.ex3{
	width: 300px;
    background-color: yellow;
}

div.ex4{
	width: 300px;
    padding: 25px; /*보더 안쪽이므로 영향을 안줌.*/
    box-sizing: border-box; /*테두리(border) 기준*/
    background-color: lightblue;
}

</style>
<title>Page Title</title>
</head>
<body>
<div class="ex1">드록바</div>
<br>
<div class="ex2">동팡저우</div>
<br>
<div class="ex3">날강두</div>
<bR>
<div class="ex4">긱스</div>

</body>
</html>

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  body{
  /*
  	전체 background를 이미지(img_tree.png)는 한번 조회되고
	이미지는 top right 에 위치하도록 처리
  */
    background-image:url('img_tree.png');
    background-repeat:no-repeat;
    background-position: top right ;
    margin-right: 200px;
    /*
    background-position: 20% 80%;
    background-position: 10px 100px;
    */
  }
  
  /*
  body{
    background-image:url('rabbit.png'), url('umbrella.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position: left top, right bottom;
  }  
  */
</style>
<title>Insert title here</title>
</head>
<body>
	<h1>Hello World!</h1>
	<p>background no-repeat, setposition example.</p>
	<p>Now the background imageis only shown once, and positioned away from the text.</p>
	<p>In this example we havealso added a margin on the right side, so the background image will neverdisturb the text.</p>
</body>
</html>

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
div
{
	width:300px;
	height:300px;
	border:1px solid green;
	
	background-image:url('flower.png'); /*300X250*/
	background-repeat:no-repeat;
	background-size:auto; /*이미지 크기 유지*/
	
	/*
	background-size:100px 100px; 세로크기 가로크기
	background-size:50% 50%; 
	background-size:cover; 배경을 모두 Cover위해 확대/축소
	background-size:contain; 이미지 비율유지하면서 배경을 벗어나지 않게
	*/
}
</style>
<title>Insert title here</title>
</head>
<body>
<div>
	산토끼 토끼야 어디를 가느냐 깡총
</div>
</body>
</html>

 

 

 

 

 

'Bitcamp > BITCAMP - Front Web' 카테고리의 다른 글

5일차  (0) 2019.09.03
4일차 실습  (0) 2019.09.02
3일차  (0) 2019.08.30
3일차 실습  (0) 2019.08.30
CSS - 선택자  (0) 2019.08.28
And

15일차

|
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"  />          
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>고객번호 조회 및 출력</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
		function fn_process(){
			var _id=$("#cust_id").val(); // 하단 input의 id의 cust_id를 var _id에 넣는다.
		    if(_id=='' || _id == null){ // var _id 널값 체크
		   	 alert("고객번호를 입력하세요");
		   	 return;
		    }
			$.ajax({
				type: "post",
				async:false, 
	            url:"${contextPath}/cus",
	            dataType : "text",
	            data: {cust_id: _id}, // 넘길 data를 set
				success: function (data, textStatus){
					var jsonInfo = JSON.parse(data);
					$("#output_cust_id").html(jsonInfo.cust_id);
					$("#output_cust_name").html(jsonInfo.cust_name);
					$("#output_cust_address").html(jsonInfo.cust_address);
					$("#output_cust_state").html(jsonInfo.cust_state);
					$("#output_cust_zip").html(jsonInfo.cust_zip);
					$("#output_cust_country").html(jsonInfo.cust_country);
					$("#output_cust_contact").html(jsonInfo.cust_contact);
					$("#output_cust_email").html(jsonInfo.cust_email);
				},
				error: function(data, textStatus){
					alert("고객이 존재하지 않습니다.");
				}
			});
		}
	</script>
</head>
<body>
	고객번호<input type="text" id="cust_id" >
	<input type="button" id="checkJson" value="조회" onClick="fn_process()"><br><br>
    
	<table border=1 align=left>
		<tr>
			<td>고객번호</td>
			<td><div id="output_cust_id"></div></td>
		</tr>
		
		<tr>
			<td>고객이름</td>
			<td><div id="output_cust_name"></div></td>
		</tr>
		
		<tr>
			<td>고객주소</td>
			<td><div id="output_cust_address"></div></td>
		</tr>
		
		<tr>
			<td>고객주</td>
			<td><div id="output_cust_state"></div></td>
		</tr>
		
		<tr>
			<td>고객우편번호</td>
			<td><div id="output_cust_zip"></div></td>
		</tr>
		
		<tr>
			<td>고객국가</td>
			<td><div id="output_cust_country"></div></td>
		</tr>
		
		<tr>
			<td>고객담당자</td>
			<td><div id="output_cust_contact"></div></td>
		</tr>
		
		<tr>
			<td>고객메일주소</td>
			<td><div id="output_cust_email"></div></td>
		</tr>
	</table>
</body>
</html>

---------------------------------------
package day0828;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class JsonServlet3
 */
@WebServlet("/cus")
public class Customer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter writer = response.getWriter();
		
		JSONObject customerInfo = new JSONObject();
		
		CustomerDAO dao = new CustomerDAO();
		
		
		String input_id = request.getParameter("cust_id");
		
		List customerList = dao.listCustomers(input_id);
		
		CustomerVO vo = (CustomerVO) customerList.get(0);
		
        customerInfo.put("cust_id", vo.getCust_id());
        customerInfo.put("cust_name", vo.getCust_name());
        customerInfo.put("cust_address", vo.getCust_address());
        customerInfo.put("cust_state", vo.getCust_state());
        customerInfo.put("cust_zip", vo.getCust_zip());
        customerInfo.put("cust_country", vo.getCust_country());
        customerInfo.put("cust_contact", vo.getCust_contact());
        customerInfo.put("cust_email", vo.getCust_email());
        
		String jsonInfo = customerInfo.toJSONString();
		System.out.println(jsonInfo);
		writer.print(jsonInfo);
		
	}

	
	
}



---------------------------------------
package day0828;

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

public class CustomerDAO {
	
	private static final String driver= "oracle.jdbc.driver.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String user ="scott";
	private static final String pwd = "tiger";
	private Connection con;
	private PreparedStatement pstmt; // 실무에선 PreparedStatement를 더 많이씀.
	
	public List listCustomers(String input_id)
	{
		List list = new ArrayList();
		try
		{
			connDB(); // 네가지 정보로 데이터베이스를 연결
			String query = "SELECT cust_id, cust_name, cust_address, cust_state, cust_zip, cust_country, cust_contact, cust_email "
					+ "FROM customers "
					+ "where cust_id = '" + input_id + "'";
			System.out.println("preparedStatement : " + query);
			pstmt = con.prepareStatement(query); // 파생된 SQL 재사용. preparedStatement 메소드에 sql문을 전달해 prepareStatement객체를 생성. 
			ResultSet rs = pstmt.executeQuery(); // sql문으로 회원 정보를 조회
			while(rs.next())
			{
				// 조회한 레코드의 각 컬럼 값을 받아옴.
				String cust_id = rs.getString("cust_id"); // " " 안에는 컬럼명이 와야함.!!!!!!!!!!!!!!
				String cust_name =rs.getString("cust_name");
				String cust_address =rs.getString("cust_address");
				String cust_state =rs.getString("cust_state");
				String cust_zip =rs.getString("cust_zip");
				String cust_country =rs.getString("cust_country");
				String cust_contact =rs.getString("cust_contact");
				String cust_email =rs.getString("cust_email");
				// 각 컬럼 값을 다시 MemberVO 객체의 속성에 설정.
				CustomerVO vo = new CustomerVO();
				vo.setCust_id(cust_id);
				vo.setCust_name(cust_name);
				vo.setCust_address(cust_address);
				vo.setCust_state(cust_state);
				vo.setCust_zip(cust_zip);
				vo.setCust_country(cust_country);
				vo.setCust_contact(cust_contact);
				vo.setCust_email(cust_email);
				list.add(vo); // 설정된 MemberVO 객체를 다시 ArrayList에 저장.
			}
			rs.close();
			pstmt.close();
			con.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return list; // 조회한 레코드의 개수만큼 MemberVO객체를 저장한 ArrayList를 반환.
	}

	private void connDB()
	{
		try
		{
			Class.forName(driver);
			System.out.println("Oracle 드라이버 로딩 성공");
			con = DriverManager.getConnection(url, user, pwd);
			System.out.println("Connection 생성 성공");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}



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

package day0828;

public class CustomerVO {
	
	private String cust_id;
	private String cust_name;
	private String cust_address;
	private String cust_state;
	private String cust_zip;
	private String cust_country;
	private String cust_contact;
	private String cust_email;
	
	public String getCust_id() {
		return cust_id;
	}
	public void setCust_id(String cust_id) {
		this.cust_id = cust_id;
	}
	public String getCust_name() {
		return cust_name;
	}
	public void setCust_name(String cust_name) {
		this.cust_name = cust_name;
	}
	public String getCust_address() {
		return cust_address;
	}
	public void setCust_address(String cust_address) {
		this.cust_address = cust_address;
	}
	public String getCust_state() {
		return cust_state;
	}
	public void setCust_state(String cust_state) {
		this.cust_state = cust_state;
	}
	public String getCust_zip() {
		return cust_zip;
	}
	public void setCust_zip(String cust_zip) {
		this.cust_zip = cust_zip;
	}
	public String getCust_country() {
		return cust_country;
	}
	public void setCust_country(String cust_country) {
		this.cust_country = cust_country;
	}
	public String getCust_contact() {
		return cust_contact;
	}
	public void setCust_contact(String cust_contact) {
		this.cust_contact = cust_contact;
	}
	public String getCust_email() {
		return cust_email;
	}
	public void setCust_email(String cust_email) {
		this.cust_email = cust_email;
	}

}


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

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

17일차  (0) 2019.09.03
16일차  (0) 2019.08.30
14일차  (0) 2019.08.27
13일차  (0) 2019.08.26
게시판  (0) 2019.08.26
And

CSS - 선택자

|
<!DOCTYPE html>
<html>
<head>
<style>
/* { 전체선택자 : html 내부의 모든태그를 선택
  font-weight: bold;
}*/
gg { /*특정태그에 적용*/
	color : green;
}
#header { /*#아이디 : 아이디를 가지고 태그를 선택. 유일*/
	color : blue;
}
.select { /* .클래스 : 특정클래스 가지고 태그를 선택*/
	color : orange;
}
li.select { /* ~.클래스 : 앞에 ~가 추가된 클래스 가지고 태그를 선택*/
	color : red;
}
.c1{
	color : gray;
}
.c2{
	background-color : red;
}
input[type=text]{background:blue;} /*속성선택자 : 특정한 속성이 있는 태그를 선택*/

#header g1{color:red;}/* 후손선택자 : 특정한 태그 아래에 있는 후손 선택. 모든 후손*/
#section g1, #section g2{color:orange;}

#header > d1{color:green;}/* 자손선택자 : 특정한 태그 바로 아래에 있는 후손 선택.*/
#section > d1, #section > d2{color:gray;}
</style>
</head>
<body>

<gg>포그바1</gg>

<div id="header"> 포그바2</div>

<li class="select">포그바3</li>

<h1 class="select">포그바4</h1>

<h1 class="c1, c2"> 포그바5<h1> <!-- c1, c2스타일 모두 적용 -->

<h1 class="c1"> 포그바6<h1> <!-- c1스타일 모두 적용 --> 

<p>포그바7</p>

<input type="text" value="포그바8"/>

<div id="header">
	<g1 class="rr">포그바9</g1>
</div>
<div id="section">
	<g2 class="dd">댄스바1</g2>
</div>

<div id="header">
	<d1 class="rr">댄스바2</g1>
</div>
<div id="section">
	<d2 class="dd">드록바</g2>
</div>

</body>
</html>

===========================================

<!DOCTYPE html>
<html>
<head>
<style>

option:checked{background-color:yellow}
input[type="checkbox"]:checked{width: 20px; height: 20px;}
input[type="radio"]:checked{margin-left: 25px;}

</style>
</head>
<body>

<h3>option 요소</h3>
<select>
	<option value="20">20대</option>
    <option value="30">30대</option>
    <option value="40">40대</option>
</select>
	<form action="url" method="post">
    	<h3> Type="checkbox"</h3>
        <input type="checkbox" name="food" value="fruit">과일<br>
        <input type="checkbox" name="food" value="sea">해조류<br>
        <input type="checkbox" name="food" value="meat">육류<br>
        
        <h3> Type="radio"</h3>
        <input type="radio" name="media" value="ie">익스<br>
        <input type="radio" name="media" value="gc">크롬<br>
        <input type="radio" name="media" value="ff">파폭<br>
	</form>
</body>
</html>

===========================================

<!DOCTYPE html>
<html>
<head>
<style>

/*동위선택자, h1 태그 바로 뒤에 위치하는 h2태그의 color 속성에 적용*/
h1 + h2 { color :red;}

/*h3 태그 바로 뒤에 위치하는 h4태그의 color 속성에 적용*/
h3 ~ h4 { color :blue;}

/* hover : 사용자가 마우스를 올린 태그를 선택 */
h5:hover { color :white;}

/* active : 사용자가 마우스로 클릭한 태그를 선택 */
h6:active { color :orange;}

/* checked : 체크상태의 input태그를 선택
focus : 초점이 맞추어진 input태그를 선택
enabled : 사용가능한 input 태그를 선택
disabled : 사용 불가능한 input 태그를 선택 */
input:enabled{color:gray;}
input:disabled{color:orange;}
input:focus{color:blue;}

</style>
</head>
<body>

	<h1>Header - 1</h1>
    <h2>Header - 2</h2>
    <h3>Header - 3</h3>
    <h4>Header - 4</h4>
    
    <h5>Header - 5</h5>
    <h6>Header - 6</h6>
    
    <input focus><h8>Enabled</h8></input><br>
    

</body>
</html>
===========================================

구조선택자

<!DOCTYPE html>
<html>
<head>
<style>

/* :first-child - 형제 관계 중에서 첫번째 위치하는 태그를 선택
:last-child - 형제 관계 중에서 마지막 위치하는 태그를 선택
:ntn-child(수열) - 형제 관계 중에서 앞에서 수열번째 위치하는 태그를 선택
:ntn-last-child(수열) - 형제 관계 중에서 뒤에서 수열번째 위치하는 태그를 선택*/
ul{overflow:hidden;}
li{
	list-style: none;
    float: left; padding: 15px;
}
li:first-child {border-radius: 10px 0 0 10px;}
li:last-child {border-radius: 0 10px 10px 0;}
li:nth-child(2n) {background-color: blue;}
li:nth-child(2n+1) {background-color: red;}

/*first-of-type : 형제 관계 중에서 첫번째로 등장하는 태그유형을 선택
last-of-type : 형제 관계 중에서 마지막으로 등장하는 태그유형을 선택
nth-of-type(수열) : 형제 관계 중에서 앞에서 수열번째 위치하는 태그유형을 선택
nth-last-of-type(수열) : 형제 관계 중에서 뒤에서 수열번째 위치하는 태그유형을 선택

*/
h1:first-of-type{color:red;}
h2:first-of-type{color:red;}
h3:first-of-type{color:red;}

</style>
</head>
<body>

	<ul>
    	<li>first</li>
        <li>Seventh</li>
        <li>Seventh</li>
        <li>Seventh</li>
        <li>Seventh</li>
        <li>Seventh</li>
        <li>Seventh</li>
	</ul>        
    
    <h1>Header-1</h1>
    <h2>Header-2</h2>
    <h3>Header-3</h3>
    <h2>Header-2</h2>
    <h1>Header-1</h1>

</body>
</html>

=================================

<!DOCTYPE html>
<html>
<head>
<style>

/* ::first-letter - 첫번째 글자를 선택
::first-line - 첫번째 줄을 선택
::selection - 블록 영역 지정한 글자를 선택
*/
p::first-letter {color: white;}
p::first-line {background-color: blue;}
p::selection {background-color: black;}

/* :link - href속성을 가지고 있는 a태그를 선택
:visited - 방문했던 링크를 가지고 있는 a태그를 선택
*/
a {text-decoration: none;}
a:visited{color:red;}
/*href속성을 가지고 있는 a태그 뒤의 공간에 "-(href속성)"을 추가합니다.*/
a:link::after{content: '-' attr(href);}

/*not(선택자) - 선택자를 반대로 적용*/
input:not([type=password]){
	background:red;
}

</style>
</head>
<body>

	<p>1111111111111111111111111ㅁㄴㅇㄻㄴㅇㄻㄴㄹ111111111111ㅁㄴㅇㄻㄴㅇㄹㄴㅁㅇㄻㄴㅇㄹㅇㄴㅁ111111111111111111111111111111111111111</p>
    
    <h1><a>Nothing</a></h1>
    <h1><a href="http://naver.com">네이버</a></h1>
    
    <input type="password" />
    <input type="text" />

</body>
</html>

 

 

 

 

'Bitcamp > BITCAMP - Front Web' 카테고리의 다른 글

5일차  (0) 2019.09.03
4일차 실습  (0) 2019.09.02
3일차  (0) 2019.08.30
3일차 실습  (0) 2019.08.30
CSS - display속성, 배경속성  (0) 2019.08.29
And

14일차

|

주요내용 : 세션, 쿠키, jQuery, json

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>ID 선택자 연습1</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function(){ // jQuery의 시작점. 외워야함(약어 version : $(function(){}))
			alert($("#unique2").html()); // id 명으로 tag를 검색해서 해당내용을 리턴. #은 id선택자
            // page로드시 id가 unique2인 태그를 검색한 후 html()메소드를 이용해 태그의 값을 가져옴.
		});
	</script>
</head>
<body>
	<div class="class1">안녕하세요.</div>
	<div id="unique2">제이쿼리입니다!</div>
	<div id="unique3">
		<p>제이쿼리는 아주 쉽습니다!!!</p>
	</div>
</body>

</html>

-----------------------------------------
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>ID 선택자 연습2</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript">
		function addHtml(){
			$("#article").html('안녕하세요' + '<br>'); // id명으로 tag를 검색해서 해당내용을 등록
		}
	</script>
</head>
<body>
	<div>
		<p id="article"></p>
	</div>
	<input type="button" value="추가하기" onClick="addHtml()"/>
</body>

</html>
-----------------------------------------
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>ID 선택자 연습5</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script type="text/javascript">
		function fn_process(){
			var value=$("#t_input").val(); // html : tag 내에 textNode를 가져오거나 변경
            // 제이쿼리에서 id로 텍스트 박스에 접근하여 val()메소드를 이용해서 입력값을 가져옴.
			$("#t_output").val(value);  // val : formtag 내에 textNode를 가져오거나 변경
            // 제이쿼리에서 id로 텍스트 박스에 접근하여 val()메소드를 이용해서 값을 출력함.
		}
	</script>
</head>
<body>
	<input type="text" id="t_input" />
	<input type="button" value="입력하기" onClick="fn_process()" /><br><br>
	<div>
		결과 : <br>
	<input type="text" id="t_output" disabled /> <!-- output에 결과가 찍힘 -->
	</div>
</body>

</html>
-----------------------------------------
package sec01.ex01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxTest1
 */
@WebServlet("/ajaxTest1")
public class AjaxTest1 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandler(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandler(request, response);
	}

	private void doHandler(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		String param = (String) request.getParameter("param");
		System.out.println("param = " + param);
		PrintWriter writer = response.getWriter();
		writer.print("안녕하세요! 서버입니다.");
	}

}
-----------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>ajax 연습1</title>
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript">
      function fn_process(){
       $.ajax({
         type:"get", //get방식으로 전송
         dataType:"text", // 응답데이터를 텍스트로 지정
         async:false,   // false인 경우 동기식으로 처리
         url:"http://localhost:8090/pro15/ajaxTest1", // 전송할 서블릿을 지정
         data: {param:"Hello,jquery"}, // 서버로 매개변수와 값을 설정
         // 전송과 응답이 성공했을 경우의 작업을 설정
         success:function (data,textStatus){
            $('#message').append(data); // 서버 응답 메세지를 div 엘리먼트에 표시
         },
         // 작업 중 오류가 발생했을 경우에 수행할 작업을 설정
         error:function(data,textStatus){
            alert("에러가 발생했습니다.");
         },
         // 완료시 수행할 작업을 설정.
         complete:function(data,textStatus){
            alert("작업을 완료했습니다");
         }
      });	
   }		
</script>
</head>
<body>
<input type="button" value="전송하기" onClick="fn_process()" /><br><br>
<div id="message"></div>
</body>
</html>
-----------------------------------------
package sec02.ex01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MemberServlet
 */
@WebServlet("/mem")
public class MemberServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter writer = response.getWriter();
		String id = (String)request.getParameter("id");
		System.out.println("id = " + id);
		MemberDAO memberDAO = new MemberDAO();
		boolean overlappedId = memberDAO.overlappedID(id); // id중복 여부 체크
		
        // 결과를 메세지로 전송.
		if(overlappedId == true) {
			writer.print("not_usable");
		} else {
			writer.print("usable");
		}
	}

}
-----------------------------------------
package sec02.ex01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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

public class MemberDAO {
	
	private Connection con;
	private PreparedStatement pstmt; // 실무에선 PreparedStatement를 더 많이씀.
	private DataSource dataFactory;
	
	public MemberDAO()
	{
		try
		{
			Context ctx = new InitialContext();
			Context envContext = (Context)ctx.lookup("java:/comp/env");
			dataFactory = (DataSource)envContext.lookup("jdbc/oracle");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	
	public boolean overlappedID(String id)
	{
		boolean result = false;
		try
		{
			con  = dataFactory.getConnection();
            // 오라클의 decode 함수를 이용해 id가 존재하면 true, 존재하지 않으면 false를 문자열로 조회.
			String query = "select decode(count(*),1,'true','false') as result from t_member";
			query += " where id=?";
			System.out.println("prepareStatement: " + query);
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, id);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
            // 문자열을 boolean 자료형으로 변환.
			result = Boolean.parseBoolean(rs.getString("result"));
			pstmt.close();
		} catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}

}
-----------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>아이디 중복 체크</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
 function fn_process(){
    var _id=$("#t_id").val(); // 텍스트 박스에 입력한 id를 가져옴.
    if(_id==''){
   	 alert("ID를 입력하세요"); // id를 입력하지 않으면 오류 메세지를 출력.
   	 return;
    }
    $.ajax({
       type:"post",
       async:false,  
       url:"http://localhost:8090/pro15/mem",
       dataType:"text",
       data: {id:_id}, // id를 서블릿으로 전송.
       success:function (data,textStatus){
          if(data=='usable'){
       	   $('#message').text("사용할 수 있는 ID입니다.");
       	   $('#btnDuplicate').prop("disabled", true); // 사용할 수 있는 id면 버튼을 비활성화시킴.
          }else{
       	   $('#message').text("사용할 수 없는 ID입니다.");
          }
       },
       error:function(data,textStatus){
          alert("에러가 발생했습니다.");
       },
       complete:function(data,textStatus){
          //alert("작업을완료 했습니다");
       }
    });  //end ajax	 
 }		
</script>
</head>
<body>
   <input  type="text" id="t_id"/>
   <input type="button" id="btn_duplicate" value="ID 중복체크하기" onClick="fn_process()" /><br><br>
   <div id="message"></div> // 결과를 표시
</body>
</html>
-----------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON 테스트</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script>
		$(function (){
			$("#checkJson").click(function(){
				var jsonStr = '{"name":"박지성","age":25,"gender":"남자","nickname":"날쌘돌이"}';
				var jsonObj = JSON.parse(jsonStr); // parse 메소드로 JSON 데이터를 가져옴.
				var output = "회원정보<br>";
				output += "======<br>";
                // 문자열에서 JSON 객체의 속성을 가져옴.
				output += "이름 : " + jsonObj.name + "<br>";
				output += "나이 : " + jsonObj.age + "<br>";
				output += "이름 : " + jsonObj.gender + "<br>";
				output += "이름 : " + jsonObj.nickname + "<br>";
				$("#output").html(output);
			});
		});
	</script>
</head>
<body>
	<a id="checkJson" style="cursor:pointer">출력</a><br><br>
    <div id="output"></div>
</body>
</html>
-----------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>        
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON 테스트2</title>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script>
		$(function (){
			$("#checkJson").click(function(){
            	// members 배열에 회원정보를 객체의 name/value 쌍으로 저장
				var jsonStr = '{"members":[{"name":"박지성","age":25,"gender":"남자","nickname":"날쌘돌이"}' + ',{"name":"손흥민","age":"30","gender":"남자","nickname":"탱크"}]}';
				var jsonInfo = JSON.parse(jsonStr);
				var output = "회원정보<br>";
				output += "======<br>";
				for(var i in jsonInfo.members){
                // 각 배열 요소에 접근하여 객체의 name으로 value를 출력.
				output += "이름 : " + jsonInfo.members[i].name + "<br>";
				output += "나이 : " + jsonInfo.members[i].age + "<br>";
				output += "이름 : " + jsonInfo.members[i].gender + "<br>";
				output += "이름 : " + jsonInfo.members[i].nickname + "<br><br><br>";
				}
				$("#output").html(output);
			});
		});
	</script>
</head>
<body>
	<a id="checkJson" style="cursor:pointer">출력</a><br><br>
    <div id="output"></div>
</body>
</html>
-----------------------------------------
package sec03.ex01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class JsonServlet3
 */
@WebServlet("/json3")
public class JsonServlet3 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter writer = response.getWriter();
		
		JSONObject totalObject = new JSONObject(); // 배열을 최종적으로 저장할 JSONObject 객체를 생성
		JSONArray membersArray = new JSONArray();
		JSONObject memberInfo = new JSONObject();
		memberInfo.put("name", "박지성");
		memberInfo.put("age", "25");
		memberInfo.put("gender", "남자");
		memberInfo.put("nickname", "두개의 심장");
		membersArray.add(memberInfo);
		
		memberInfo = new JSONObject();
		memberInfo.put("name", "김연아");
		memberInfo.put("age", "21");
		memberInfo.put("gender", "여자");
		memberInfo.put("nickname", "KB손해보험");
		membersArray.add(memberInfo);
		totalObject.put("members", membersArray); // 회원 정보를 저장한 배열을 배열 이름 members로 totalObject에 저장
		
		JSONArray bookArray = new JSONArray(); // JSONArray 객체를 생성.
		JSONObject bookInfo = new JSONObject();
        // JSONArray 객체를 생성한 후 책정보를 저장.
		bookInfo.put("title", "초보자를 위한 자바 프로그래밍");
		bookInfo.put("writer", "이병승");
		bookInfo.put("price", "30000");
		bookInfo.put("gerne", "IT");
		bookInfo.put("image", "http://localhost:8090/pro15/image/image1.jpg");
		bookArray.add(bookInfo); // bookArray에 객체를 저장.
		
		bookInfo = new JSONObject();
		bookInfo.put("title", "모두의 파이썬");
		bookInfo.put("writer", "이승찬");
		bookInfo.put("price", "12000");
		bookInfo.put("gerne", "IT");
		bookInfo.put("image", "http://localhost:8090/pro15/image/image1.jpg");
		bookArray.add(bookInfo);
		
		totalObject.put("books", bookArray); // 도서 정보를 저장한 배열을 배열이름 books로 totalObject에 저장.
		String jsonInfo = totalObject.toJSONString(); // String 포맷으로 데이터를 바꿔줌.
		System.out.println(jsonInfo);
		writer.print(jsonInfo);
	}

	
	
}
-----------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"  />          
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON 테스트3</title>
	<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
	<script>
		$(function (){
			$("#checkJson").click(function(){
				$.ajax({
					type: "post",
					async:false, 
		            url:"${contextPath}/json3",
					success: function (data, textStatus){
						var jsonInfo = JSON.parse(data);
						var memberInfo = "회원정보<br>";
						memberInfo += "======<br>"
						for(var i in jsonInfo.members){ // 배열이름 members로 회원 정보를 출력.
							memberInfo += "이름 : " + jsonInfo.members[i].name + "<br>";
							memberInfo += "나이 : " + jsonInfo.members[i].age + "<br>";
							memberInfo += "성별 : " + jsonInfo.members[i].gender + "<br>";
							memberInfo += "별명 : " + jsonInfo.members[i].nickname + "<br>";
						}
						var booksInfo = "<br><br><br>도서 정보";
						booksInfo += "==========<br>";
						for(var i in jsonInfo.books){
							console.log("ddd"); // 크롬 개발자도구에 결과값 찍히게 하는 방법 ★★★★★
							memberInfo += "제목 : " + jsonInfo.books[i].title + "<br>";
							memberInfo += "저자 : " + jsonInfo.books[i].writer + "<br>";
							memberInfo += "가격 : " + jsonInfo.books[i].price + "<br>";
							memberInfo += "장르: " + jsonInfo.books[i].genre + "<br>";
                            // 이미지 URL을 구해 <img> 태그의 src속성에 설정.
							imageURL = jsonInfo.books[i].image;
							booksInfo += "<img src=" + imageURL + "/>" +"<br><br><br>";
						}
						$("#output").html(memberInfo + "<br>" + booksInfo);
					},
					error: function(data, textStatus){
						alert("에러가 발생했습니다.");
					}
				});
			});
		});
	</script>
</head>
<body>
	<a id="checkJson" style="cursor:pointer">데이터 수신하기</a><br><br>
    <div id="output"></div>
</body>
</html>

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

16일차  (0) 2019.08.30
15일차  (0) 2019.08.28
13일차  (0) 2019.08.26
게시판  (0) 2019.08.26
12일차  (0) 2019.08.19
And

10일차

|
/*0827 실습
1. 제품정보에서 공급업체번호가 'BRS01', 'DLL01' 이 아닌 제품이름과 제품가격을 다음의 Format으로 추출하시오
Format = 제품이름'['제품가격']' */
select trim(prod_name) ||'['||prod_price||']' as Format
from products
where vend_id not in('BRS01', 'DLL01');

-- 2. 고객의 고객이름과 고객주소정보를 추출하시오
-- 고객주소정보 : 고객주소 중에 Drive는 Car로 변경
select trim(cust_name) as 고객이름, trim(replace(cust_address, 'Drive', 'Car')) as 고객주소정보
from customers;

-- 3. 고객주문에서 주문일에 +1일을 한 날짜가 // 해당 주문월의 마지막 날짜와 같은 // 주문번호를 오름차순으로 추출한다.
select order_num
from Orders
where (order_date + 1) = Last_day(order_date)
Order by order_num asc;

-- 4. 제품이름과 // 제품설명에 'king'이라는 단어가 들어가고 제품가격의 소수점 1자리가 9가 아닌 // 제품번호를 추출하시오
select prod_name, prod_id
from products
where prod_desc LIKE '%king%'
and substr(trunc(prod_price,1), length(trunc(prod_price,1)),1) <> '9';

-- 5. 주문에서 1월 중 주문한 주문중에 // 고객별 가장 늦게 주문한 주문일자를 추출
-- 결과 : 고객번호, 주문일자(YYYY-MM-DD)
select cust_id, MIN(TO_char(order_date, 'YYYY-MM-DD'))
from Orders
WHERE TO_CHAR(order_date, 'MM') = 01 group by cust_id;

-- 6. 고객별로 주문한 상품중에 가장 높은 금액을 가지는 상품을 추출하시오
-- 결과 : 고객번호, 고객이름, 제품번호, 제품이름, 항목가격
SELECT C.cust_id, C.cust_name, P.prod_id, P.prod_name, OI.item_price
FROM   CUSTOMERS C, ORDERS O, ORDERITEMS OI, PRODUCTS P,
        (SELECT OO.cust_id, MAX (OII.item_price) max_price
         FROM   ORDERITEMS OII, ORDERS OO
         WHERE  OII.order_num = OO.order_num
         GROUP BY OO.cust_id
        ) t
               WHERE  C.cust_id = O.cust_id
               AND    O.order_num = OI.order_num
               AND    OI.prod_id = P.prod_id
               AND    C.cust_id = t.cust_id
               AND    OI.item_price = t.max_price;

SELECT C.cust_id, C.cust_name, OI.prod_id, TRIM(P.prod_name), OI.item_price
FROM CUSTOMERS C, PRODUCTS P, ORDERS O, ORDERITEMS OI
WHERE C.cust_id = O.cust_id
AND O.order_num = OI.order_num
AND P.prod_id = OI.prod_id
AND OI.item_price = (SELECT MAX(item_price)
                     FROM ORDERITEMS);

-- 7. 상품중에 3$ ~ 10$대의 상품수를 아래와 같이 추출하시오.
SELECT SUM(CASE WHEN TRUNC(prod_price) = '3' THEN 1  ELSE 0 END) AS "3$",
       SUM(CASE WHEN TRUNC(prod_price) = '4' THEN 1  ELSE 0 END) AS "4$",
       SUM(CASE WHEN TRUNC(prod_price) = '5' THEN 1  ELSE 0 END) AS "5$",
       SUM(CASE WHEN TRUNC(prod_price) = '6' THEN 1  ELSE 0 END) AS "6$",
       SUM(CASE WHEN TRUNC(prod_price) = '7' THEN 1  ELSE 0 END) AS "7$",
       SUM(CASE WHEN TRUNC(prod_price) = '8' THEN 1  ELSE 0 END) AS "8$",
       SUM(CASE WHEN TRUNC(prod_price) = '9' THEN 1  ELSE 0 END) AS "9$",
       SUM(CASE WHEN TRUNC(prod_price) = '10' THEN 1  ELSE 0 END) AS "10$"
FROM products;





'Bitcamp > BITCAMP - SQL' 카테고리의 다른 글

9일차  (0) 2019.08.14
8일차  (0) 2019.08.12
7일차  (0) 2019.08.02
6일차  (0) 2019.07.31
5일차  (0) 2019.07.30
And

13일차

|

주요내용 :  Formatting Tag Library, 문자열 처리 Tag Library, CustomTag

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.Date"
    pageEncoding="UTF-8"
    isELIgnored="false"%>
    // 포매팅 태그라이브러리를 사용하기 위해 반드시 선언해야함.
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>   
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>포매팅 태그 라이브러리 예제</title>
</head>
<body>
	<h2>fmt의 number 태그를 이용한 숫자 포맷팅 예제.</h2>
   	<c:set var="price" value="100000000" />
   	<fmt:formatNumber  value="${price}" type="number" var="priceNumber" />
   	통화로 표현 시 :
    // 숫자를 원화로 표시
    // groupingUsed="true" -> 세자리 숫자마다 콤마로 표시. 설정하지 않으면 기본값이 true. false 이면 콤마가가 표시되지 않음.
    <fmt:formatNumber type="currency" currencySymbol="₩"   value="${price}" groupingUsed="true"/><br>
   	퍼센트로 표현 시 : 
    <fmt:formatNumber value="${price}" type="percent"   groupingUsed="false" /><br>
   	일반 숫자로 표현 시 : ${priceNumber}<br>
    // fmt:formatNumber 태그에서 var 속성에 정한 변수이름으로 표현 언어에서 출력함.
	<h2>formatDate 예제</h2>
	<c:set var="now" value="<%=new Date() %>" />
	<fmt:formatDate value="${now }" type="date" dateStyle="full" /><br>
	<fmt:formatDate value="${now }" type="date" dateStyle="short" /><br>
	<fmt:formatDate value="${now }" type="time" /><br>
	<fmt:formatDate value="${now }" type="both" dateStyle="full" timeStyle="full" /><br>
    // fmt:formatDate 태그의 pattern 속성에 출력한 날짜 포맷을 지정함.
	<fmt:formatDate value="${now }" pattern="YYYY-MM-dd :hh:mm:ss" /><br>
	
	<br><br>
	한국 현재 시간:
	<fmt:formatDate value="${now }" type="both" dateStyle="full" timeStyle="full"/><br><br>
	<fmt:timeZone value="America/New York"> // 뉴욕 시간대로 변경.
	뉴욕 현재시간 : 
	<fmt:formatDate value="${now }" type="both" dateStyle="full" timeStyle="full"/><br><br>
	</fmt:timeZone>
</body>
</html>

------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>함수 사용</title>
</head>
<body>
<c:set var="str1" value="Functions <태그>를 사용합니다." />
<c:set var="str2" value="사용" />
<c:set var="tokens" value="1, 2, 3, 4, 5, 6, 7, 8, 9, 10" />
<c:set var="str3" value="<b><i>This is html text.</i></b>" />

length(str1) = ${fn:length(str1)}<br> <!-- 22 -->
toUpperCase(str1) = "${fn:toUpperCase(str1)}"<br> <!-- FUNCTIONS <태그>를 사용합니다.  -->
toLowerCase(str1) = "${fn:toLowerCase(str1)}"<br> <!-- functions <태그>를 사용합니다.  -->
substring(str1, 3, 6) = "${fn:substring(str1, 3, 6)}"<br> <!-- cti  -->
substringAfter(str1, str2) = "${fn:substringAfter(str1, str2)}"<br> <!-- 합니다.  -->
substringBefore(str1, str2) = "${fn:substringBefore(str1, str2)}"<br> <!-- Functions <태그>를  -->
trim(str1) = "${fn:trim(str1)}"<br> <!-- Functions <태그>를 사용합니다.  -->
replace(str1, src, dest) = "${fn:replace(str1, " ", "-")}"<br> <!-- Functions-<태그>를-사용합니다.  -->
indexOf(str1, str2) = "${fn:indexOf(str1, str2)}"<br> <!--  16 -->
startsWith(str1, str2) = "${fn:startsWith(str1,'Fun')}"<br> <!--  true -->
endsWith(str1, str2) = "${fn:endsWith(str1, "합니다.")}"<br> <!-- true  -->
contains(str1, str2) = "${fn:contains(str1, str2) }"<br> <!--  true -->
containsIgnoreCase(str1, str2) = "${fn:containsIgnoreCase(str1, str2)}"<br><!--  true -->
<c:set var="array" value="${fn:split(tokens,',')}" />
join(array, "-") = "${fn:join(array, "-")}"<br>
<!-- 1- 2- 3- 4- 5- 6- 7- 8- 9- 10  -->

<!-- html과 escapeXml 과의 차이 -->
<p>just html:${str3}</p><!-- 기울임체 -->
escapeXml(str3) = "${fn:escapeXml(str3)}"<br><!-- 그냥 글씨체 -->
</body>
</html>

------------------------------------------
<!-- TAG 잘활용하면 개발 퍼포먼스가 좋아진다!!! -->
<!-- TAG를 개발시작전에 만들어놓고 시작함. -->
<!-- 내용을 출력하는 단순 태그파일 구현 -->
<!-- body-content를 empty로 주어 Tag File이 나타내는 CustomTag의 몸체내용이 없다고 설정 -->
<%@ tag body-content="empty" pageEncoding="UTF-8"%>
<%@ tag import="java.util.Calendar" %>
<!-- Tag File에서 실핼할 작업을 코딩 -->
<%
	Calendar cal = Calendar.getInstance();
%>
<%= cal.get(Calendar.YEAR) %>년
<%= cal.get(Calendar.MONTH)+1 %>월
<%= cal.get(Calendar.DATE) %>일
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>now</title>
</head>
<body>

오늘은<b><tf:now/></b>입니다.

</body>
</html>
------------------------------------------
<!-- 실습: 속성을 사용하는 태그파일 구현 -->
<%@ tag body-content="empty" pageEncoding="UTF-8"%>
<%@ tag trimDirectiveWhitespaces="true" %><!-- 소스보기할때 빈칸없어지게함. -->
<%@ attribute name="title" required="true" %>
<%@ attribute name="level" type="java.lang.Integer" %>
<%
	String headStartTag = null ;
	String headEndTag = null ;
	if(level == null){
		headStartTag = "<h1>";
		headEndTag = "</h1>";
	} else if(level == 1) {
		headStartTag = "<h1>";
		headEndTag = "</h1>";
	} else if(level == 2) {
		headStartTag = "<h2>";
		headEndTag = "</h2>";
	} else if(level == 3) {
		headStartTag = "<h3>";
		headEndTag = "</h3>";
	}
%>
<%= headStartTag %> <!--  실제 tag를 통해 표시되는 부분 -->
${title}
<%= headEndTag %>
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>제목 출력</title>
</head>
<body>

<tf:header title="텍스트제목" level="2"/>

<tf:header title="${'EL제목'}" level="3"/>

<tf:header title='<%= "표현식 제목" %>' />

</body>
</html>
------------------------------------------
<!--tag 디렉티브의 dynamic-attributes 속성에 동적속성을 저장할 변수명을 입력해주어서 처리
	모든 동적 속성은 java.util.Map 타입의 EL변수에 저장된다  -->
<%@ tag body-content="empty" pageEncoding="UTF-8"%>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ tag dynamic-attributes="optionMap" %>
<%@ attribute name="name" required="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="${name }">
	<c:forEach items="${optionMap}" var="option">
		<option value="${option.key}">${option.value}</option>
	</c:forEach>
</select>
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>      
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>동적속성전달</title>
</head>
<body>
	<tf:select name="code" rgb="RGB모드" wb="흑백 모드"/>
	<tf:select name="genre" rock="락" ballad="발라드" metal="메탈"/>
</body>
</html>
------------------------------------------
<!-- 몸체내용에서 HTML태그를 제거해주는 태그 -->
<%@ tag body-content="scriptless" pageEncoding="UTF-8"%>
<%@ attribute name="length" type="java.lang.Integer" %>
<%@ attribute name="trail" %>
<%@ attribute name="trim" %>
<jsp:doBody var="content" scope="page"/>
<!-- 몸체 내용을 context 변수에 저장, content이름으로 setAttribute 됨. -->
<%
	String content = (String)jspContext.getAttribute("content");
	if(trim != null && trim.equals("true")){
		content = content.trim();
	}
	// 정규식 - 앞단의 모든 것들을 없애라.
	content = content.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?>", "");
	if(length != null && length.intValue() > 0 &&
		content.length() > length.intValue()){ // length 이상인 content 는 자른다.
		content = content.substring(0, length.intValue());
		if(trail != null){
			content = content + trail;
		}
	}
%>
<%= content %>
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.Date"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>   
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>       
<!DOCTYPE html>
<html>
<head>
<c:set var="dateEL" value="<%=new Date() %>"/>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<tf:removeHtml trim="true">
		<font size="10">현재 <style>시간</style>은${dateEL }입니다.</font>
		<!--  현재 시간은Mon Aug 26 15:48:25 KST 2019입니다.  -->
	</tf:removeHtml>
	<br>
	<tf:removeHtml length="15" trail="..." trim="true">
		<u>현재 시간</u>은<b>${dateEL }</b>입니다.
		<!-- 현재 시간은Mon Aug 2...   -->
	</tf:removeHtml>
	<br>
	<tf:removeHtml length="15">
		<jsp:body><u>현재 시간</u>은<b>${dateEL }</b>입니다.</jsp:body>
		<!--  현재 시간은Mon Aug 2 -->
	</tf:removeHtml>
</body>
</html>
------------------------------------------
<!-- variable 디렉티브와 name-given을 이용한 변수추가  -->
<%@ tag language="java" pageEncoding="UTF-8"%>
<%@ tag trimDirectiveWhitespaces="true" %>
<%@ attribute name="begin" required="true" type="java.lang.Integer" %>
<%@ attribute name="end" required="true" type="java.lang.Integer" %>
<%@ variable name-given="sum" variable-class="java.lang.Integer" scope="NESTED" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="sum" value="${0 }"/>
<c:forEach var="num" begin="${begin }" end="${end}">
	<c:set var="sum" value="${sum + num }" />
</c:forEach>
<jsp:doBody/> <!-- body를 출력 -->
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sum 사용</title>
</head>
<body>

<tf:sum begin="1" end="10">
	1-10까지 합 : ${sum } <!-- 55 -->
</tf:sum>

</body>
</html>
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />

<%
  request.setCharacterEncoding("UTF-8");
%>    
<html>
<head>
<meta charset="UTF-8">
 <head>
   <title>파일 업로드창</title>
 </head> <body>
	<!-- 서블릿에 요청해 파일을 업로드함 // 파일 업로드 시 반드시 enctype을 multipart-form-data로 설정해야함.-->
	<form action="${contextPath }/upload.do" method="post" enctype="multipart/form-data" >
      파일1: <input type="file" name="file1" ><br>
      파일2: <input type="file" name="file2" > <br>
      파라미터1: <input type="text" name="param1" > <br>
      파라미터2: <input type="text" name="param2" > <br>
      파라미터3: <input type="text" name="param3" > <br>
 <input type="submit" value="업로드" >
</form>
 </body>
</html>
------------------------------------------
package sec01.ex01;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/upload.do")
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		String encoding = "utf-8";
		File currentDirPath = new File("C:\\Users\\bit\\Documents\\카카오톡 받은 파일"); // 업로드할 파일 경로를 지정
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(currentDirPath);// 파일 경로를 설정(임시 디렉토리)
		factory.setSizeThreshold(1024*1024); // 최대 업로드 가능한 파일 크기를 설정. 단위 byte
		ServletFileUpload upload = new ServletFileUpload(factory);
		try { // list로 input 된것들을 다 받음.
			List items = upload.parseRequest(request); // request 객체에서 매개변수를 List로 가져옴.
			for(int i=0; i<items.size(); i++) {
				FileItem fileItem = (FileItem) items.get(i); // 파일업로드 창에서 업로드된 항목들을 하나씩 가져옴.
				if(fileItem.isFormField()) { //// 단순 form file인지 여부, false이면 File.  폼필드이면 전송된 매개변수 값을 출력.
					System.out.println(fileItem.getFieldName()+ "=" + fileItem.getString(encoding));
				} else { // 파일일경우(폼필드가 아니면) 파일 업로드 기능을 수행.
					System.out.println("매개변수이름 : " + fileItem.getFieldName());
					System.out.println("파일이름 : " + fileItem.getName());
					System.out.println("파일크기 : " + fileItem.getSize() + "bytes");
					// 업로드한 파일 이름을 가져옴.
					if(fileItem.getSize() > 0) {
						int idx = fileItem.getName().lastIndexOf("\\"); // 마지막 " " 부터 찾는다.
						if(idx == -1) {
							idx = fileItem.getName().lastIndexOf("/");
						}
						String fileName = fileItem.getName().substring(idx+1);
						// 업로드한 파일 이름으로 저장소에 파일을 업로드함.
						File uploadFile = new File(currentDirPath + "\\" + fileName);
						fileItem.write(uploadFile);
					} // end if
				} // end if
			}// end for
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>       

<%
  request.setCharacterEncoding("utf-8");
%>
<html>
<head>
<meta charset="UTF-8">
<title>파일 다운로드 요청하기</title>
</head>
<body>
	<form method="post" action="result.jsp">
	<!-- 다운로드할 파일 이름을 매개변수로 전달. -->
		<input type=hidden name="param1" value="duke.png"/><br>
		<input type=hidden name="param2" value="duke2.jpg"/><br>
		<input type="submit" value="이미지 다운로드">
	</form>
</body>
</html>
------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />
<%
  request.setCharacterEncoding("UTF-8");
%>    
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<!-- 다운로드할 파일 이름을 가져옴 -->
	<c:set var="file1" value="${param.param1}"  />    
<c:set var="file2" value="${param.param2}"  />
 
<title>이미지 파일 출력하기</title>
</head>
<body>
파라미터 1 :<c:out value="${file1}"  /><br>
파라미터 2 :<c:out value="${file2}"  /><br>
<c:if test="${not empty file1 }">
	 <!--  파일 이름으로 서블릿에서 이미지를 다운로드해 표시함. -->
	 <img src="${contextPath}/download.do?fileName=${file1}"  width=300 height=300 /><br>
	</c:if>
	<br>
	<c:if test="${not empty file2 }">
	 <!--  파일 이름으로 서블릿에서 이미지를 다운로드해 표시함. -->
	 <img src="${contextPath}/download.do?fileName=${file2}"  width=300 height=300 /><br>
	</c:if>
	파일 내려받기 :<br>
	 <!-- 이미지를 파일로 다운로드함. -->
	<a href="${contextPath}/download.do?fileName=${file2}" >파일 내려받기</a><br>
</body>
</html>
------------------------------------------
package sec01.ex01;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileDownload
 */
@WebServlet("/download.do")
public class FileDownload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
		doHandle(request, response);
	}

	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		String file_repo="C:\\Users\\bit\\Documents\\카카오톡 받은 파일";
		String fileName = (String)request.getParameter("fileName"); // 매개변수로 전송된 파일 이름을 읽어옴.
		System.out.println("fileName=" + fileName);
		OutputStream out = response.getOutputStream(); // response에서 OutputStream 객체를 가져옴.
		String downFile = file_repo + "\\" + fileName;
		File f = new File(downFile);
		// 파일을 다운로드 할수 있음.
		response.setHeader("Cache-Control", "no-cache"); // 파일 다운로드는 캐싱안되도록 설정
		response.addHeader("Content-disposition", "attachment; fileName=" + fileName); // file download처리 시 attachmemt 로 설정
		// attachment: 파일 다운로드 대상상자가 뜸.
        // inline: 바로 다운로드 됨(pdf 다운로드 누르면 크롬에서 바로 뜨는 형식을 생각하면 됨.)
		FileInputStream in = new FileInputStream(f);
		byte[] buffer = new byte[1024 * 8];
		while (true) {
			int count = in.read(buffer);
			if (count == -1)
				break;
			out.write(buffer, 0, count);
		}
		in.close();
		out.close();
	}

}


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

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

15일차  (0) 2019.08.28
14일차  (0) 2019.08.27
게시판  (0) 2019.08.26
12일차  (0) 2019.08.19
11일차  (0) 2019.08.14
And

게시판

|

주요 기능 : 회원가입, 로그인, 방명록, 글쓰기, 글수정, 글삭제, 페이징

============================= 0. 프로퍼티즈, web.xml, 통합 핸들러, 유틸 ============================= 
/viewArticle.do=command.ViewHandler
/modArticle.do=command.ModHandler
/removeArticle.do=command.RemoveHandler
/writeForm.do=com.action.WriteFormAction
/writePro.do=com.action.WriteProAction
/list.do=com.action.ListAction
/join.do=member.command.JoinHandler
/login.do=member.command.LoginHandler
/logout.do=member.command.LogoutHandler
/changepw.do=member.command.ChangePwHandler
/addGuest.do=guestbook.command.AddGuestbookHandler
/pwdCheck.do=guestbook.command.PwdCheckHandler
/modifyCheck.do=guestbook.command.ModifyCheckHandler
/modify.do=guestbook.command.ModifyHandler
---------------------------------------------
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<!-- <security-constraint>
<web-resource-collection>
<web-resource-name>PreventViewingJSPs</web-resource-name>
            <description>브라우저로 접속한 사용자가 JSP파일로 직접 접근할 수 없도록 한다.</description>
            <url-pattern>*.do</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
</auth-constraint>
</security-constraint>--> 

	<display-name>BBS</display-name>
	
  <servlet>
    <servlet-name>ControllerUsingURI</servlet-name>
    <servlet-class>controller.ControllerUsingURI</servlet-class>
    <init-param>
         <param-name>configFile</param-name>
         <param-value>/WEB-INF/commandHandlerURI.properties</param-value>
	     </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>ControllerUsingURI</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
   <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>

</web-app>

---------------------------------------------
package controller;


import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import command.NullHandler;

public class ControllerUsingURI extends HttpServlet {

	//
	private Map<String, CommandHandler> commandHandlerMap = new HashMap<>();

	public void init() throws ServletException {
		String configFile = getInitParameter("configFile");
		Properties prop = new Properties();

		String configFilePath = getServletContext().getRealPath(configFile);
		try (FileReader fis = new FileReader(configFilePath)) {
			prop.load(fis);
		} catch (IOException e) {
			throw new ServletException(e);
		}

		Iterator keyIter = prop.keySet().iterator();
		while (keyIter.hasNext()) {
			String command = (String) keyIter.next();
			String handlerClassName = prop.getProperty(command);
			try {
				Class<?> handlerClass = Class.forName(handlerClassName);
				CommandHandler handlerInstance = (CommandHandler) handlerClass.newInstance();
				commandHandlerMap.put(command, handlerInstance);
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
				throw new ServletException(e);
			}
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

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

	private void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String command = request.getRequestURI(); // BBS/...
		if (command.indexOf(request.getContextPath()) == 0) { // ServletContext로 시작된 URI이면
			command = command.substring(request.getContextPath().length()); // ServletContext다음부터가 Command
		}

		CommandHandler handler = commandHandlerMap.get(command); // Handler 객체를 가져온다.
		if (handler == null) {
			handler = new NullHandler(); // 존재하지 않는 command 이면 Not Found Error를 Client에게 전송
		}

		String viewPage = null;
		try {
			viewPage = handler.process(request, response); // handler에서 작업을 처리 후 viewPage를 리턴
		} catch (Throwable e) {
			throw new ServletException(e);
		}
		if (viewPage != null) {
			RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage); // viewPage로 forward처리
			dispatcher.forward(request, response);
		}
	}
}
---------------------------------------------
package command;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface CommandHandler {
	public String process(HttpServletRequest req, HttpServletResponse res) throws Exception;
}

---------------------------------------------
package command;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NullHandler implements CommandHandler {

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws Exception {
		res.sendError(HttpServletResponse.SC_NOT_FOUND);
		return null;
	}
}
---------------------------------------------

package util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharacterEncodingFilter implements Filter {

	private String encoding;
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		req.setCharacterEncoding(encoding);
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		encoding = config.getInitParameter("encoding");
		if (encoding == null) {
			encoding = "UTF-8";
		}
	}

	@Override
	public void destroy() {
	}

}
---------------------------------------------

package jdbc.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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


public class ConnectionProvider {

	public static Connection getConnection() throws SQLException, NamingException {
		
		Context ctx = new InitialContext(); 
		Context envContext = (Context) ctx.lookup("java:/comp/env");
		DataSource dataFactory = (DataSource) envContext.lookup("jdbc/oracle");		
		
		return dataFactory.getConnection();
	}
}

---------------------------------------------
package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtil {

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException ex) {
			}
		}
	}

	public static void close(Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException ex) {
			}
		}
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException ex) {
			}
		}
	}

	public static void rollback(Connection conn) {
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException ex) {
			}
		}
	}
}

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

============================= 1. 메인페이지, 로그인, 회원가입 ============================= 
<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>메인 페이지(초기화면)</title>
</head>
<body>
<a href = "/BBS/view/guestbook.jsp">방명록</a><br>
<a href = "list.do">게시판</a><br>
<a href = "login.do">로그인</a><br>
<a href = "join.do">회원가입</a><br>
</body>
</html>
---------------------------------------------
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<title>가입</title>
</head>
<body>
<form action="join.do" method="post">
<p>
	아이디:<br/><input type="text" name="id" value="${param.id}">
	<c:if test="${errors.id}">ID를 입력하세요.</c:if>
	<c:if test="${errors.duplicateId}">이미 사용중인 아이디입니다.</c:if>
</p>
<p>
	이름:<br/><input type="text" name="name" value="${param.name}">
	<c:if test="${errors.name}">이름을 입력하세요.</c:if>
</p>
<p>
	암호:<br/><input type="password" name="password">
	<c:if test="${errors.password}">암호를 입력하세요.</c:if>
</p>
<p>
	확인:<br/><input type="password" name="confirmPassword">
	<c:if test="${errors.confirmPassword}">확인을 입력하세요.</c:if>
	<c:if test="${errors.notMatch}">암호와 확인이 일치하지 않습니다.</c:if>
</p>
<input type="submit" value="가입">
<input type="button" value="메인으로" onClick="location.href='/BBS/main.jsp'">
</form>
</body>
</html>
---------------------------------------------
<%@ page contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>가입 완료</title>
</head>
<body>
&nbsp;&nbsp;${param.name}님, 회원 가입에 성공했습니다.
<br><br>
<a href ="/BBS/login.do">로그인 창으로 가기</a>
<br/>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
	session ="true"
    pageEncoding="UTF-8"
    import="member.*"
    isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 화면</title>
</head>
<body>
<form method="post" action="login.do" >
<p>
아이디 : <br><input type ="text" name="id" value="${param.id }"><br><br>
</p>
<p>
비밀번호 : <br><input type="password" name="password"><br>
<c:if test="${errors.result}">일치하지 않습니다</c:if>
</p>
<input type="submit" value="로그인">
<input type="button" value="메인으로" onClick="location.href='/BBS/main.jsp'">

</form>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
	session="true"
	import ="java.util.*"
    pageEncoding="UTF-8"
    isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
%>

<%
	String name = (String)request.getAttribute("name");
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
	function fn_logout(){
		var frmLogout = document.frm;
		frmLogout.method = "post";
		frmLogout.action = "BBS/logout.do";
		frmLogout.submit();
	}

</script>
<title>로그인 후 초기화면</title>
</head>
<body>
	<form name = "frm" method="post">
	&nbsp;${name}님 안녕하세요. <a href="logout.do" onclick="fn_logout()">[로그아웃하기]</a>
	<a href = "/BBS/changepw.do">[암호변경하기]</a><br><br>
	&nbsp;<a href = "/BBS/view/guestbook.jsp">방명록</a><br>
	&nbsp;<a href = "list.do">게시판</a>
	</form>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    session="true"
    import="java.util.*"
    isELIgnored="false"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");
%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>암호 변경</title>
</head>
<body>
	<form method="post" action="changepw.do">
	현재 암호:<br><input type = "password" name="old_pwd"><br>
	새 암호:<br><input type = "password" name="new_pwd"><br>
	<input type="submit" value="암호 변경">
	<input type="button" value="메인으로" onClick="location.href='/BBS/loginafter.jsp'">
	</form>
</body>
</html>
---------------------------------------------
package member.command;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import member.service.DuplicateIdException;
import member.service.JoinRequest;
import member.service.JoinService;

public class JoinHandler implements CommandHandler {

	private static final String FORM_VIEW = "/join.jsp";
	private JoinService joinService = new JoinService();

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		
		req.setCharacterEncoding("utf-8");
		
		JoinRequest joinReq = new JoinRequest();
		joinReq.setId(req.getParameter("id"));
		joinReq.setName(req.getParameter("name"));
		joinReq.setPassword(req.getParameter("password"));
		joinReq.setConfirmPassword(req.getParameter("confirmPassword"));

		Map<String, Boolean> errors = new HashMap<>();
		req.setAttribute("errors", errors);

		joinReq.validate(errors);

		if (!errors.isEmpty()) {
			return FORM_VIEW;
		}

		try {
			joinService.join(joinReq);
			return "/joinsuccess.jsp";
		} catch (DuplicateIdException e) {
			errors.put("duplicateId", Boolean.TRUE);
			return FORM_VIEW;
		}
	}

}
---------------------------------------------
package member.command;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import command.CommandHandler;
import member.dao.MemberDao;
import member.model.Member;
import member.service.DuplicateIdException;
import member.service.LoginRequest;
import member.service.LoginService;

public class LoginHandler implements CommandHandler {

	private static final String FORM_VIEW = "/login.jsp";
	private static final String FORM_VIEW2 = "/loginafter.jsp";
	private LoginService loginService = new LoginService();

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws SQLException, NamingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws SQLException, NamingException {
		LoginRequest loginreq = new LoginRequest();
		loginreq.setId(req.getParameter("id"));
		loginreq.setPassword(req.getParameter("password"));
		MemberDao dao = new MemberDao();
		Map<String, Boolean> errors = new HashMap<>();
		req.setAttribute("errors", errors);
		
		Connection conn = null;
		String name = dao.name(conn, loginreq.getId());
		
		HttpSession session = req.getSession();
		session.setAttribute("input_id", loginreq.getId());
		session.setAttribute("input_pwd", loginreq.getPassword());
		session.setAttribute("name", name);
		
		loginreq.validate(errors);
		
		if(!errors.isEmpty()) {
			return FORM_VIEW;
		}
		try {
			loginService.login(loginreq, req, errors);;
			return FORM_VIEW2;
			
		}catch(DuplicateIdException e) {
			errors.put("duplicateId", Boolean.TRUE);
			return FORM_VIEW;
		}
		
		
		}
	}
---------------------------------------------
package member.command;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import command.CommandHandler;
import member.service.DuplicateIdException;

public class LogoutHandler implements CommandHandler {

	private static final String FORM_VIEW = "/main.jsp";

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) {
		System.out.println("logout : ");
			HttpSession session = req.getSession();
			session.invalidate();
						
			
			return FORM_VIEW;
	}

}
---------------------------------------------
package member.command;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import command.CommandHandler;
import member.dao.MemberDao;
import member.model.Member;
import member.service.DuplicateIdException;
import member.service.ChangePwRequest;

public class ChangePwHandler implements CommandHandler {

	private static final String FORM_VIEW = "/changepw.jsp";
	private static final String LOGIN_AFTER = "/loginafter.jsp";

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws SQLException, NamingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws SQLException, NamingException {
		ChangePwRequest changereq = new ChangePwRequest();
		changereq.setOld_pwd(req.getParameter("old_pwd"));
		changereq.setNew_pwd(req.getParameter("new_pwd"));
		String old_pwd = changereq.getOld_pwd();
		MemberDao dao = new MemberDao();
		Connection conn = null;
		HttpSession session = req.getSession();
		
		String id = (String) session.getAttribute("input_id");
		String pwd = (String) session.getAttribute("input_pwd");
		String name = dao.name(conn, id);
		req.setAttribute("name", name);;
		System.out.println("id:"+id);
		System.out.println("pw:"+pwd);
		if (old_pwd.equals(pwd)) {
			session.setAttribute("input_pwd", changereq.getNew_pwd());
			dao.changepw(conn, new Member(id, changereq.getOld_pwd(), changereq.getNew_pwd()));
			return LOGIN_AFTER;
		} else {
				return FORM_VIEW;
		}
	}
}
---------------------------------------------
package member.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import javax.naming.NamingException;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;
import member.dao.MemberDao;
import member.model.Member;

public class JoinService {
	private MemberDao memberDao = new MemberDao();

	public void join(JoinRequest joinReq) {
		Connection conn = null;
		try {
			conn = ConnectionProvider.getConnection(); 
			conn.setAutoCommit(false);

			Member member = memberDao.selectById(conn, joinReq.getId());
			if (member != null) {
				JdbcUtil.rollback(conn);
				throw new DuplicateIdException();
			}

			memberDao.insert(conn, new Member(joinReq.getId(), joinReq.getName(), joinReq.getPassword(), new Date()));
			conn.commit();
		} catch (NamingException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} catch (SQLException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.close(conn);
		}
	}
}
---------------------------------------------
package member.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;
import member.dao.MemberDao;
import member.model.Member;

public class LoginService {
	private MemberDao dao = new MemberDao();
	
	

	public void login(LoginRequest loginreq, HttpServletRequest req, Map<String, Boolean> errors) {
		boolean result = false;
		Connection conn = null;
		try {
			conn = ConnectionProvider.getConnection(); 
			Member bean = dao.selectById(conn, loginreq.getId());
					
			
			result =  dao.isExisted(conn, new Member(loginreq.getId(),loginreq.getPassword()));
			System.out.println("1111:"+ result);
			check(errors, result, "result");
			System.out.println("2222:" + result);
			if (!result) {
				JdbcUtil.rollback(conn);
				throw new DuplicateIdException();		
			}
			HttpSession session = req.getSession();
	        session.setAttribute("isLogon", true);
			
		} catch (NamingException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} catch (SQLException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.close(conn);
		}
	}
	
	private void check(Map<String, Boolean> errors, boolean result, String fieldName) {
		if(!result) {
			errors.put(fieldName, Boolean.TRUE);
			throw new DuplicateIdException();
		}
		System.out.println("333333:" + result);
	}
	
}
---------------------------------------------
package member.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import javax.naming.NamingException;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;
import member.dao.MemberDao;
import member.model.Member;

public class ChangePwService {
	private MemberDao memberDao = new MemberDao();

	public void join(JoinRequest joinReq) {
		Connection conn = null;
		try {
			conn = ConnectionProvider.getConnection(); 
			conn.setAutoCommit(false);

			Member member = memberDao.selectById(conn, joinReq.getId());
			if (member != null) {
				JdbcUtil.rollback(conn);
				throw new DuplicateIdException();
			}

			memberDao.insert(conn, new Member(joinReq.getId(), joinReq.getName(), joinReq.getPassword(), new Date()));
			conn.commit();
		} catch (NamingException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} catch (SQLException e) {
			JdbcUtil.rollback(conn);
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.close(conn);
		}
	}
}
---------------------------------------------
package member.service;

import java.util.Map;

public class JoinRequest {

	private String id;
	private String name;
	private String password;
	private String confirmPassword;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public boolean isPasswordEqualToConfirm() {
		return password != null && password.equals(confirmPassword);
	}

	public void validate(Map<String, Boolean> errors) {
		checkEmpty(errors, id, "id");
		checkEmpty(errors, name, "name");
		checkEmpty(errors, password, "password");
		checkEmpty(errors, confirmPassword, "confirmPassword");
		if (!errors.containsKey("confirmPassword")) {
			if (!isPasswordEqualToConfirm()) {
				errors.put("notMatch", Boolean.TRUE);
			}
		}
	}

	private void checkEmpty(Map<String, Boolean> errors, 
			String value, String fieldName) {
		if (value == null || value.isEmpty())
			errors.put(fieldName, Boolean.TRUE);
	}
}
---------------------------------------------
package member.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.naming.NamingException;

import member.dao.MemberDao;
import member.model.Member;


public class LoginRequest {
	private String id;
	private String password;
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getId() {
		return id;
	}
	
	public void setId(String id) {
		this.id = id;	
	}
	
	//패스워드 일치 여부

	   public void validate(Map<String, Boolean> errors) throws SQLException{
	      checkEmpty(errors, id, "id");
	      checkEmpty(errors, password, "password");
	      
	      
	   }
   
	
	   private void checkEmpty(Map<String, Boolean> errors, 
	         String value, String fieldName) {
	      if (value == null || value.isEmpty())
	         errors.put(fieldName, Boolean.TRUE);
	   }
	
	

}
---------------------------------------------
package member.service;

public class ChangePwRequest {
	
	private String old_pwd;
	private String new_pwd;
	
	
	public String getOld_pwd() {
		return old_pwd;
	}
	public void setOld_pwd(String old_pwd) {
		this.old_pwd = old_pwd;
	}
	public String getNew_pwd() {
		return new_pwd;
	}
	public void setNew_pwd(String new_pwd) {
		this.new_pwd = new_pwd;
	}
	
	
}
---------------------------------------------

package member.service;

public class DuplicateIdException extends RuntimeException {

}
---------------------------------------------

package member.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;
import member.model.Member;
import member.service.LoginRequest;

public class MemberDao {

	public Member selectById(Connection conn, String id) throws SQLException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(
					"select * from member where member_id = ?");
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			Member member = null;
			if (rs.next()) {
				member = new Member(
						rs.getString("member_id"), 
						rs.getString("name"), 
						rs.getString("password"),
						toDate(rs.getTimestamp("regdate")));
			}
			return member;
		} finally {
			JdbcUtil.close(rs);
			JdbcUtil.close(pstmt);
		}
	}

	private Date toDate(Timestamp date) {
		return date == null ? null : new Date(date.getTime());
	}

	public void insert(Connection conn, Member mem) throws SQLException {
		try (PreparedStatement pstmt = 
				conn.prepareStatement("insert into member values(?,?,?,?)")) {
			pstmt.setString(1, mem.getId());
			pstmt.setString(2, mem.getName());
			pstmt.setString(3, mem.getPassword());
			pstmt.setTimestamp(4, new Timestamp(mem.getRegDate().getTime()));
			pstmt.executeUpdate();
		}
	}

	public void changepw(Connection conn, Member bean) throws SQLException {
		 	PreparedStatement pstmt = null;
		 	String old_pwd = bean.getPassword();
		 	String new_pwd = bean.getNewPwd();
		 	System.out.println("old_pwd:" + old_pwd);
		 	System.out.println("new_pwd:" + new_pwd);
		 	try {
		 	 conn = ConnectionProvider.getConnection();
		 	 String query = "update member set password = ? where member_id = ?";
			 System.out.println(query);
	    	 pstmt = conn.prepareStatement(query);
	         pstmt.setString(1, bean.getNewPwd());
	         pstmt.setString(2, bean.getId());
	         pstmt.executeUpdate();
	         pstmt.close();
	         conn.close();
	      }catch(Exception e) {
	    	  e.printStackTrace();
	      }
}
	
	public String name(Connection conn, String id) throws SQLException, NamingException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
	 	try {
	 	 conn = ConnectionProvider.getConnection();
	 	 String query = "select name from member where member_id=?";
		 System.out.println(query);
    	 pstmt = conn.prepareStatement(query);
         pstmt.setString(1, id);
         rs = pstmt.executeQuery();
         Member member = null;
         String name= null;
         if(rs.next()) {
        	 member = new Member(rs.getString("name"));
        	 name = member.getName();
         }
         	rs.close();
         	conn.close();
         	pstmt.close();
			return name;
		} finally {
			JdbcUtil.close(rs);
			JdbcUtil.close(pstmt);
		}
	}
	public boolean isExisted(Connection conn, Member bean) {
		boolean result = false;	
		PreparedStatement pstmt = null;
		String id = bean.getId();
		String pwd = bean.getPassword();
		try {
			conn = ConnectionProvider.getConnection(); 
			String query = "SELECT DECODE(COUNT(*),1,'true','false') AS result FROM member WHERE member_id ='" + id +"' AND password ='" + pwd +"'";
			System.out.println(query);
			pstmt = conn.prepareStatement(query);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			result = Boolean.parseBoolean(rs.getString("result"));
			rs.close();
			conn.close();
			pstmt.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println(result);
		return result;
	}
	
}
---------------------------------------------
package member.model;

import java.util.Date;

public class Member {

	private String id;
	private String name;
	private String password;
	private Date regDate;
	private String new_pwd;
	
	public Member(String id, String name, String password, Date regDate) {
		this.id = id;
		this.name = name;
		this.password = password;
		this.regDate = regDate;
	}
		
	public Member(String id, String password) {
		this.id = id;
		this.password = password;
	}
		
	public Member(String id, String password, String new_pwd) {
		super();
		this.id = id;
		this.password = password;
		this.new_pwd = new_pwd;
	}

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

	public Member(String name) {
		super();
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getPassword() {
		return password;
	}
	
	public Date getRegDate() {
		return regDate;
	}
	
	public String getNewPwd() {
		return new_pwd;
	}
	
	public boolean matchPassword(String pwd) {
		return password.equals(pwd);
	}

	public void changePassword(String newPwd) {
		this.password = newPwd;
	}

}

============================= 2. 게시판 ============================= 
<%@ page import="member.model.Member" %>
<%@page import="dao.ArticleVO"%>
<%@page import="dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
	request.setCharacterEncoding("utf-8");
	String name = (String)request.getAttribute("name");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>글목록</title>

</head>
<body>

<marquee behavior="alternate" scrolldelay="100" direction="right">
      3조의 게시판입니다.</marquee>

<c:if test="${page.count == 0}">
<table width="70%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr>
    <td bgcolor="#e9e9e9">
   
    </td>
</table>
</c:if>


<table width="70%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr><td colspan="6" align="center"><h1>게시판</h1></td></tr>
<tr bgcolor="gray">
    <td width="70">번호</td>
    <td width="70">글제목</td>
    <td width="120">작성자</td>
    <td width="70">조회수</td>
   <td width="120">작성일 </td>
</tr>
<c:set var="number" value="${page.number}"/>
<c:forEach var="article" items="${articleList}">

<tr> 
    
    <td>${article.article_no}</td>    
    <td><a href="viewArticle.do?article_no=${article.article_no}">${article.title}</a></td>
    <td>${article.writer_name}</td>
     <td>${article.read_cnt}</td>
    <td><fmt:formatDate value="${article.regdate}" pattern="yyyy년MM월dd일"/></td>
</tr>
</c:forEach>
</table>

 <form action="list.do" name="search" method="get" onsubmit="return searchMessage()">
 
<table width="70%" border="1" align="center" cellpadding="4" cellspacing="0">
  
  <tr><td width="200"><a href="writeForm.do">글쓰기</a></td>
  
    <td align="center" valign="bottom">
      <select name="keyField">
          <option value="title">제목</option>      
          <option value="name">이름</option>
          <option value="content">내용</option>
      </select></td>
        <td><input type="text" size=16 name="keyWord"><input type="submit" value="찾기"></td>
   </tr> 
   <tr><td colspan="3" align="center">
   
<c:if test="${page.count > 0}">
   <c:set var="pageCount" value="${(page.count - 1) / page.pageSize + 1}"/>
   <c:set var="pageBlock" value="${10}"/>
   <fmt:parseNumber var="rs" value="${(currentPage - 1) / pageBlock}" integerOnly="true" />
   <c:set var="startPage" value="${rs*pageBlock+1}"/>
   <c:set var="endPage" value="${startPage + pageBlock-1}"/>
   <c:if test="${endPage > pageCount}">
        <c:set var="endPage" value="${pageCount}"/>
   </c:if> 
          
   <c:if test="${startPage > pageBlock}">
        <a href="list.do?pageNum=${startPage - pageBlock }&keyField=${page.keyField}&keyWord=${page.keyWord}">[이전]</a>
   </c:if>
	<input type="button" value="메인으로" onClick="location.href='/BBS/loginafter.jsp'">
   <c:forEach var="i" begin="${startPage}" end="${endPage}">
   
       <c:if test="${i == page.currentPage}">
          [${i}]
       </c:if>
       <c:if test="${i != page.currentPage}">
           <a href="list.do?pageNum=${i}&keyField=${page.keyField}&keyWord=${page.keyWord}">[${i}]</a>
       </c:if>
       
   </c:forEach>

   <c:if test="${endPage < pageCount}">
        <a href="list.do?pageNum=${startPage + pageBlock}&keyField=${page.keyField}&keyWord=${page.keyWord}">[다음]</a>
   </c:if>
</c:if>
   </td></tr>
</table>
</form>
</body>
</html>
---------------------------------------------
<%@page import="com.domain.Article2"%>
<%@page import="com.dao.ArticleDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    request.setCharacterEncoding("utf-8");
   String name = request.getParameter("name");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>게시판</title>

<script type="text/javaScript">
function writeSave(){
   
  
   if(writeform.title.value==""){
     alert("제목을 입력하십시요.");
     return false;
   }
   
   if(writeform.content.value==""){
     alert("내용을 입력하십시요.");
     return false;
   }
   
   if(writeform.password.value==""){
        alert(" 비밀번호를 입력하십시요.");        
        return false;
      }
   
   writeform.action="writePro.do";
   writeform.submit();
        
   return true;
 }    
</script>
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />
</head>
<body>
<center><b>글쓰기</b></center>
<br>
<form method="post" name="writeform">
<input type="hidden" name="name" value="${sessionScope.name}">
<table width="400" border="1" cellspacing="0" cellpadding="0" align="center">
   <tr>
    <td align="right" colspan="2">
       <a href="list.do"> 글목록</a> 
   </td>
   </tr>
   <tr>
    <td  width="70" align="center">이 름</td>
    <td  width="330">
       <input type="text" size="10" maxlength="10" name="writer_name" value="${sessionScope.name }" disabled="disabled" /></td>
  </tr>
  <tr>
    <td  width="70" align="center" >제 목</td>
    <td  width="330">
      <input type="text" size="40" maxlength="50" name="title" value="${article2.title }">
    </td>
  </tr>
 
  <tr>
    <td  width="70" align="center" >내 용</td>
    <td  width="330" >
     <textarea name="content" rows="13" cols="40">${article2.content }</textarea> </td>
  </tr>
    <tr>
    <td  width="70" align="center" >비밀번호</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" name="password" value="${article2.password }"> 
    </td>
  </tr>

<tr>      
 <td colspan=2 align="center"> 
  <input type="button" value="글쓰기" onclick ="writeSave()">  
  <input type="reset" value="다시작성">
  <input type="button" value="목록보기" onClick="location.href='list.do'">
</td></tr></table>
</form>            
</body>
</html>      
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<script type="text/javaScript">
alert("게시판에 글을 등록하였습니다.");
location.href = "list.do";
</script>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
%>
<%
	String name = (String)request.getAttribute("name");
%>
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />
<head>
<meta charset="UTF-8">
   <title>게시글 보기</title>
   <script type="text/javascript">
   
      <!--목록으로 이동-->
      function move(url) {
  		location.href=url;
  	  }
      
	</script>
</head>
<body>
  <form name="frmArticle" method="post"   enctype="multipart/form-data">
  <h2 align=center>글 상세보기</h2>
  <table border solid align = center>
  <tr>
   <td>글번호</td>
    <td><input type="text" name="article_no" value="${article.article_no }"  disabled />
    <input type="hidden" name="article_no" value="${article.article_no}"  /></td>
     <!--글 수정시 글 번호를 컨트롤러로 전송하기 위해 미리 hidden 태그를 이용해 글 번호를 저장-->
  </tr>
  
  <tr>
   <td>작성자</td>
   <td width = 100><input type="text" value="${article.writer_name }" name="writer_name" disabled/></td>
  </tr>
  
  <tr>
   <td>등록일자</td>
 	<td width = 100><input type=text value="<fmt:formatDate value="${article.regdate}" />" name="regdate" disabled/></td>
  </tr>
  
    <tr>
	   <td>수정일자</td>
	    <td width = 100><input type=text value="<fmt:formatDate value="${article.moddate}" />" name="moddate" disabled /></td>
  </tr>
  
      <tr>
	   <td>조회수</td>
	    <td width = 100><input type=text value="${article.read_cnt}" name="read_cnt" disabled /></td>
  </tr>
  
  <tr>
   <td>제목</td>
    <td width = 100><input type="text" value="${article.title }"  name="title"  id="i_title" disabled /></td>
  </tr>
  
  <tr>
   <td>내용</td>
	<td width = 100 height = 100><textarea id=content name="content" rows = "20" cols = "50" disabled >${article.content}</textarea></td>
  </tr>
    
  <tr  id="tr_btn"    >
   <td colspan=2 align="center">
	  <input type=button value="게시글수정" onClick="location.href='contentdelalterChk.jsp?mode=alter&article_no=${article.article_no }'">
	  <input type=button value="게시글삭제" onClick="location.href='contentdelalterChk.jsp?mode=del&article_no=${article.article_no }'">
	  <input type=button value="목록"  onClick="move('list.do');">
   </td>
  </tr>
 </table>
 </form>
</body>
</html>
---------------------------------------------
<%@page import="dao.ArticleVO"%>
<%@page import="dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("utf-8");
	String mode = request.getParameter("mode");
	String password = request.getParameter("password");
	int article_no = Integer.parseInt(request.getParameter("article_no"));
%>
<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />

<html>
<head>
<meta charset="UTF-8">
<title>암호 확인</title>
<script type="text/javascript">
	
	function passChkProcBtn(){
		frm.method='post';
		frm.action='passChkProc.jsp';
		frm.submit();
	}
	
	function move(url) {
  		location.href=url;
  	}
	
	
</script>
</head>

<body>
<%
	if("del".equals(mode)){
%>
	<h2 align=center>글 삭제</h2>
	<form id = frm method="post" action="passChkProc.jsp?mode=del&article_no=<%=article_no %>"
		encType="UTF-8">
		<table border 1 align = center>
			<tr>
				<th>비밀번호를 입력해주세요</th>
			</tr>
 	<tr>
     	<td>비밀번호 : <input type=password name=password>
		<input type = hidden name =password value=password>
		</td>
    </tr>
    <tr>
		<td align=center>
		<input type=submit value="게시글 삭제하기" >
		<input type=button value="뒤로" onClick="history.back()">
		</td>
	</tr>
<% 	} %>
<%
	if("alter".equals(mode)){
%> 
	<h2 align=center>글 수정</h2>
	<form id = frm method="post" action="passChkProc.jsp?mode=alter&article_no=<%=article_no %>"
		encType="UTF-8">
		<table border 1 align = center>
			<tr>
				<th>비밀번호를 입력해주세요</th>
			</tr>
 	<tr>
     	<td>비밀번호 : <input type=password name=password>
		<input type = hidden name = password value=password>
		</td>
    </tr>
    <tr>
		<td align=center>
		<input type=submit value="게시글 수정하기" >
		<input type=button value="뒤로" onClick="history.back()">
		</td>
	</tr>
<% 	} %>
	</form> 
</body>
</html>
---------------------------------------------
<%@page import="dao.ArticleVO"%>
<%@page import="dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 수정</title>
<%
   request.setCharacterEncoding("utf-8");
   int article_no = Integer.parseInt(request.getParameter("article_no"));
   BoardDAO dao = BoardDAO.getInstance();
   ArticleVO bb = dao.selectArticle(article_no, 0);
%>

<script>
   function updateBtn(){
   
      if(frm.title.value==""){
         alert("제목을 입력해주세요");
         return false;
      }
      if(frm.content.value==""){
         alert("내용을 입력해주세요");
         return false;
      }
      frm.action="modArticle.do?article_no=<%=bb.getArticle_no() %>";
      frm.submit();
   }
   
   function move(url) {
         location.href=url;
   }

</script>

<c:set var="contextPath"  value="${pageContext.request.contextPath}"  />
</head>
<body>
<h2 align=center >글 수정</h2>
   <form name="frm" method="post">
      <table border solid align = center>
         <tr>
            <td>글번호</td>
            <td><input type = text name="article_no" value="<%=bb.getArticle_no() %>" disabled/></td>
         </tr>
         <tr>
            <td>제목</td>
            <td><input type=text name="title" size = 20 value ="<%=bb.getTitle() %>"></td>
         </tr>
         <tr>
            <td>내용</td>
            <td width = 100 height = 100><textarea name="content" rows = "20" cols = "50" ><%=bb.getContent() %></textarea></td>
         </tr>
          </tr>
         <tr>
            <td colspan=2 align=center>
            <input type=button value="수정" onclick ="updateBtn()">
               <input type="button" value="뒤로" onclick="javascript:location.href='/BBS/viewArticle.do?article_no=<%=bb.getArticle_no() %>'"></td>
         </tr>
      </table>
   </form>
</body>
</html>
---------------------------------------------
<%@page import="dao.ModRequest"%>
<%@page import="dao.ArticleVO"%>
<%@page import="dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("utf-8");
String mode = request.getParameter("mode");
String password = request.getParameter("password");
int article_no = Integer.parseInt(request.getParameter("article_no"));
BoardDAO dao = BoardDAO.getInstance();
Boolean result = dao.PwdCheck(article_no, password);
if("alter".equals(mode) && result==true){
	System.out.println("수정 - 비번확인완료");
	response.sendRedirect("/BBS/contentalter.jsp?article_no=" + article_no);
}else if("del".equals(mode) && result==true){
	System.out.println("삭제 - 비번확인완료");
	response.sendRedirect("/BBS/removeArticle.do?article_no=" + article_no);
}else{
	%>
	<script>
	alert("비밀번호가 맞지 않습니다.")
	history.back();
	</script>
	<%
};
%>
---------------------------------------------
package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.ArticleDao;
import com.domain.Article;
import com.domain.ArticlePage;

import command.CommandHandler;


public class ListAction implements CommandHandler{
    
	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws IOException {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws IOException {
    
    try {
		req.setCharacterEncoding("utf-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
    HttpSession session = req.getSession();
    if(session.getAttribute("isLogon")==null) {
       return "/main.jsp";
    }else {
       boolean isLogon = (boolean)session.getAttribute("isLogon");
       if(!isLogon) {
          return "/main.jsp";
       }
    }

    String keyField =req.getParameter("keyField");
    String keyWord =req.getParameter("keyWord");
    if(keyField==null){
        keyField="";
    }
    if(keyWord==null){
        keyWord="";
    }    
    
    String pageNum =req.getParameter("pageNum");
    
    if(pageNum ==null){
        pageNum = "1";
    }    
    
    int pageSize = 10;
    int currentPage = Integer.parseInt(pageNum);
    int startRow =(currentPage-1)*pageSize +1;
    int endRow =currentPage * pageSize;
    int count = 0;
    int number = 0;
    
    List<Article> articleList =null;
    ArticleDao manager = ArticleDao.getInstance();
    try {
		count =manager.getArticleCount(keyField,keyWord);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
    if(count>0){
       try {
		articleList = manager.getArticles(startRow, endRow, keyField, keyWord);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }
    //가짜 글번호
    number=count-(currentPage-1)*pageSize;

    ArticlePage page= new ArticlePage();
    page.setCount(count);
    page.setCurrentPage(currentPage);
    page.setNumber(number);
    page.setPageSize(pageSize);    
    page.setKeyField(keyField);    
    page.setKeyWord(keyWord);    
    
    req.setAttribute("page", page);
    req.setAttribute("articleList", articleList);

    return "/view/list.jsp";
    }
}
---------------------------------------------
package com.action;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.ArticleDao;
import com.domain.Article2;

import command.CommandHandler;
import member.model.Member;


public class WriteProAction  implements CommandHandler{

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws Exception {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws Exception {

    	 req.setCharacterEncoding("utf-8");
        
        Article2 article = new Article2();
        
        article.setWriter_id(req.getParameter("writer_id")); 
        article.setWriter_name(req.getParameter("name")); 
        article.setTitle(req.getParameter("title"));   
        article.setContent(req.getParameter("content")); 
        article.setPassword(req.getParameter("password"));

        ArticleDao manager = ArticleDao.getInstance();
        
        manager.insertArticle1(article);
        manager.insertArticle2(article);
       
        return "/view/writePro.jsp";
    }
}
---------------------------------------------
package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import command.CommandHandler;

public class WriteFormAction implements CommandHandler{

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) {
        
        return "/view/writeForm.jsp";
    }
}
---------------------------------------------
package com.dao;

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

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

import com.domain.Article;
import com.domain.Article2;
//import com.util.StringUtil;

public class ArticleDao {

    private static ArticleDao instance =new ArticleDao();
    Article ac = new Article();

    //�̱��� ����
    private ArticleDao(){}
    public static ArticleDao getInstance(){
        return instance;
    }


    //getConnection : JDBC DB���� 
    private Connection getConnection() throws Exception{
        Context initCtx= new InitialContext();
        Context envCtx=(Context)initCtx.lookup("java:comp/env");
        DataSource ds=(DataSource)envCtx.lookup("jdbc/oracle");

        return ds.getConnection();
    }

    //Article 테이블에 넣기
    public void insertArticle1(Article2 article)throws Exception{
    	

        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql=null;
        int cnt = 0;
        try{
            conn= getConnection();
			sql = "insert into ARTICLE (article_no, writer_id, writer_name, title, moddate, regdate, read_cnt, password) " 
                + "values(article_no_seq.nextval,1,?,?,sysdate,sysdate,0,?)";
            
            System.out.println("query:"+sql);
            pstmt = conn.prepareStatement(sql);
            System.out.println(article.getTitle());
            System.out.println(article.getWriter_name());
            System.out.println(article.getPassword());
            pstmt.setString(++cnt, article.getWriter_name());
            pstmt.setString(++cnt, article.getTitle());
            pstmt.setString(++cnt, article.getPassword());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //Article_content 테이블에 넣기
    public void insertArticle2(Article2 article)throws Exception{

        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql2=null;
        int cnt = 0;        

        try{
            conn= getConnection();
            sql2 = "insert into ARTICLE_content (article_no, content) " 
                    + "values(article_no_seq.currval,?)";
            System.out.println("query:"+sql2);
            pstmt = conn.prepareStatement(sql2);
            pstmt.setString(++cnt, article.getContent());             
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    
    //�۰���
    public int getArticleCount(String keyField,String keyWord)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        int count =0;
        String sql =null;
        
        try{
            conn=getConnection();
            if(keyWord == null || "".equals(keyWord.trim())){
                sql="select count(*) from ARTICLE";
                pstmt =conn.prepareStatement(sql);
            }else{
                sql="select count(*) from ARTICLE where "+keyField+" like ?";
                pstmt =conn.prepareStatement(sql);
                pstmt.setString(1, "%"+keyWord+"%");
            }
            rs =pstmt.executeQuery();
            if (rs.next()){
                count =rs.getInt(1);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }            
        return count;
    }
    
    //����Ʈ�̱�
    public List<Article> getArticles(int startRow, int endRow, String keyField,String keyWord)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List<Article> list =null;
        String sql=null;
        
        try{
            conn =getConnection();
            if(keyWord == null || "".equals(keyWord.trim())){
                sql ="select * from (select a.*, rownum rnum from (select * from ARTICLE order by article_no desc)a) where rnum >=? and rnum <=?";
                pstmt =conn.prepareStatement(sql);            
                pstmt.setInt(1, startRow);
                pstmt.setInt(2, endRow);    
            }else{
                sql ="select * from(select a.*, rownum rnum from(select * from ARTICLE where "+keyField+" like ? order by article_no desc)a) where rnum >=? and rnum <=?";
                pstmt =conn.prepareStatement(sql);    
                pstmt.setString(1, "%"+keyWord+"%");
                pstmt.setInt(2, startRow);
                pstmt.setInt(3, endRow);
            }
            rs = pstmt.executeQuery();
            if(rs.next()){
                list= new ArrayList<Article>();                
                do{
                    Article article =new Article();
                    article.setArticle_no(rs.getInt("article_no"));
                    article.setTitle(rs.getString("title"));
                    article.setWriter_name(rs.getString("writer_name"));                                     
                    article.setRead_cnt(rs.getInt("read_cnt"));
                    article.setRegdate(rs.getTimestamp("regdate"));
                  
                    list.add(article);
                }while(rs.next());
            }else{
                list = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return list;
    }
    
    //��������
//    public Article getArticle(int num)throws Exception{
//        Connection conn =null;
//        PreparedStatement  pstmt= null;
//        ResultSet rs = null;
//        Article article =null;
//        String sql=null;
//        
//        try{
//            conn=getConnection();
//            sql ="select * from ARTICLE where article_no = ? ";
//
//            pstmt=conn.prepareStatement(sql);
//            pstmt.setInt(1, num);
//            rs=pstmt.executeQuery();
//            
//            if(rs.next()){
//                article =new Article();
//                article.setArticle_no(rs.getInt("article_no"));
//                article.setWriter_id(rs.getString("writer_id"));
//                article.setWriter_name(rs.getString("writer_name"));
//                article.setTitle(rs.getString("title"));
//                article.setRegdate(rs.getTimestamp("regdate"));
//                article.setModdate(rs.getTimestamp("moddate"));                   
//                article.setRead_cnt(rs.getInt("read_cnt"));
//                article.setContent(StringUtil.clobToString(rs,"content"));
//            }
//        }catch(Exception ex){
//            ex.printStackTrace();
//        }finally{
//            execClose(rs,pstmt,conn);
//        }
//        return article;
//    }

    //execClose : �ڿ�����
    public void execClose(ResultSet rs, PreparedStatement pstmt, Connection conn)throws Exception{
        if(rs !=null) try{rs.close();}catch(SQLException sqle){}
        if(pstmt !=null) try{pstmt.close();}catch(SQLException sqle){}
        if(conn !=null) try{conn.close();}catch(SQLException sqle){}
    }
}
---------------------------------------------
package com.domain;

import java.sql.Timestamp;

public class Article {
    
    private int article_no;
    private String writer_id;
    private String writer_name;
    private String title;
    private Timestamp regdate;
    private Timestamp moddate;
    private int read_cnt;
    private String content;
    
    public int getArticle_no() {
		return article_no;
	}
	public void setArticle_no(int article_no) {
		this.article_no = article_no;
	}
	public String getWriter_id() {
		return writer_id;
	}
	public void setWriter_id(String writer_id) {
		this.writer_id = writer_id;
	}
	public String getWriter_name() {
		return writer_name;
	}
	public void setWriter_name(String writer_name) {
		this.writer_name = writer_name;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Timestamp getRegdate() {
		return regdate;
	}
	public void setRegdate(Timestamp regdate) {
		this.regdate = regdate;
	}
	public Timestamp getModdate() {
		return moddate;
	}
	public void setModdate(Timestamp moddate) {
		this.moddate = moddate;
	}
	public int getRead_cnt() {
		return read_cnt;
	}
	public void setRead_cnt(int read_cnt) {
		this.read_cnt = read_cnt;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
    
    
   
	
 
    
    
 
}
---------------------------------------------
package com.domain;

public class Article2 {

	
	 private String writer_name;
	 private String title;
	 private String content;
	 private String writer_id;
	 
	 private int article_no;
	 
	 private String password; // 게시글비밀번호
	 
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getArticle_no() {
		return article_no;
	}
	public void setArticle_no(int article_no) {
		this.article_no = article_no;
	}
	public String getWriter_id() {
		return writer_id;
	}
	public void setWriter_id(String writer_id) {
		this.writer_id = writer_id;
	}
	public String getWriter_name() {
		return writer_name;
	}
	public void setWriter_name(String writer_name) {
		this.writer_name = writer_name;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}
---------------------------------------------
package com.domain;

public class ArticlePage {
    
    private int count;
    private int pageSize;
    private int currentPage;
    private int number;
    private String keyField;
    private String keyWord;
    
    
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }    
    public String getKeyField() {
        return keyField;
    }
    public void setKeyField(String keyField) {
        this.keyField = keyField;
    }
    public String getKeyWord() {
        return keyWord;
    }
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }        
}



---------------------------------------------
package command;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ArticleVO;
import dao.BoardDAO;
import dao.ViewRequest;
import dao.ViewService;

public class ViewHandler implements CommandHandler {
	
	private static final String FORM_VIEW = "/contentdetail.jsp";
	private ViewService viewService = new ViewService();
	ArticleVO articleVO;
	ViewRequest viewReq;
	
	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) {
		
		System.out.println("viewHandler 실행");
		
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		res.setContentType("text/html; charset=utf-8");
		String action = req.getPathInfo();
		System.out.println("action:" + action);
		
		String article_no = req.getParameter("article_no");
		
		try {
			List<ArticleVO> articlesList = new ArrayList<ArticleVO>();
			
				article_no = req.getParameter("article_no");
				articleVO = viewService.viewArticle(Integer.parseInt(article_no));
				req.setAttribute("article", articleVO);
				req.setAttribute("article_no", article_no);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        return "/contentdetail.jsp?article_no='" + article_no + "'";
		
	}

}
---------------------------------------------
package dao;

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

import javax.naming.NamingException;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;

public class ViewService {
	private BoardDAO boardDAO = new BoardDAO();
	private ArticleVO articleVO = new ArticleVO();

	public ViewService() {
		boardDAO = new BoardDAO();
		articleVO = new ArticleVO();
	}
	
	// 글 상세정보
	public ArticleVO viewArticle(int article_no) {
		ArticleVO article = null;
		article = boardDAO.selectArticle(article_no, 0);
		return article;
	}

}
---------------------------------------------
package dao;

import java.sql.Date;
import java.util.Map;

public class ViewRequest {
	
	private int article_no; // 게시글 번호
	private String writer_id; // 등록자 Id
	private String name; // member테이블의 name
	private String title; // 제목
	private Date regdate; // 등록일시
	private Date moddate; // 수정일시
	private int read_cnt; // 조회수 count
	
	// article_content 테이블
	private String content; // 게시내용
	
	public int getArticle_no() {
		return article_no;
	}

	public void setArticle_no(int article_no) {
		this.article_no = article_no;
	}

	public String getWriter_id() {
		return writer_id;
	}

	public void setWriter_id(String writer_id) {
		this.writer_id = writer_id;
	}

	public String getName() {
		return name;
	}

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

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getRegdate() {
		return regdate;
	}

	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}

	public Date getModdate() {
		return moddate;
	}

	public void setModdate(Date moddate) {
		this.moddate = moddate;
	}

	public int getRead_cnt() {
		return read_cnt;
	}

	public void setRead_cnt(int read_cnt) {
		this.read_cnt = read_cnt;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
---------------------------------------------
package command;

import java.io.UnsupportedEncodingException;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ArticleVO;
import dao.BoardDAO;
import dao.ModRequest;
import dao.ModService;
import dao.ViewRequest;

public class ModHandler implements CommandHandler {
	
	private static final String FORM_VIEW = "/contentalter.jsp";
	private ModService modService = new ModService();
	ArticleVO articleVO;
	ModRequest modReq;

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) {
		
		System.out.println("modHandler 실행");
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ModRequest modReq = new ModRequest();
		modReq.setArticle_no(Integer.parseInt(req.getParameter("article_no")));
		modReq.setTitle(req.getParameter("title"));
		modReq.setContent(req.getParameter("content"));
		
        
        String article_no = req.getParameter("article_no");
        
        try {
    			article_no = req.getParameter("article_no");
				modService.mod(modReq);
				articleVO = modService.viewArticle(Integer.parseInt(article_no));
				req.setAttribute("article", articleVO);
				req.setAttribute("article_no", article_no);
        
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        return "/contentdetail.jsp?article_no=" + article_no;
		
	}

}
---------------------------------------------
package dao;

import java.lang.reflect.Member;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;

import javax.naming.NamingException;

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;

public class ModService {
	private BoardDAO boardDAO = new BoardDAO();
	private ArticleVO articleVO = new ArticleVO();

	public ModService() {
		boardDAO = new BoardDAO();
		articleVO = new ArticleVO();
	}

	public void mod(ModRequest modReq) {
			try {
				boardDAO.update1(modReq);
				boardDAO.update2(modReq);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public ArticleVO viewArticle(int article_no) { // 업데이트된 글 가져오는 메소드
		ArticleVO article = null;
		article = boardDAO.selectArticle(article_no, 0);
		return article;
	}
	
}
---------------------------------------------
package dao;

import java.sql.Date;


public class ModRequest {
	
	private int article_no; // 게시글 번호
	private String title; // 제목
	private Date moddate; // 수정일시
	
	private String content; // 게시내용
	
	 private String password; // 게시글 비밀번호

	 
	 

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getArticle_no() {
		return article_no;
	}

	public void setArticle_no(int article_no) {
		this.article_no = article_no;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getModdate() {
		return moddate;
	}

	public void setModdate(Date moddate) {
		this.moddate = moddate;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
---------------------------------------------
package command;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ArticleVO;
import dao.BoardDAO;
import dao.ModRequest;
import dao.ViewRequest;
import dao.RemoveService;

public class RemoveHandler implements CommandHandler {
	
	private static final String FORM_VIEW = "/delProc.jsp";
	private RemoveService removeService = new RemoveService();
	ArticleVO articleVO;
	ModRequest modReq;

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) {
			return processSubmit(req, res);
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) {
		
		System.out.println("removeHandler 실행");
		
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int article_no = Integer.parseInt(req.getParameter("article_no"));
        
			
        try {
				articleVO = removeService.deleteArticle(article_no);
				req.setAttribute("article", articleVO);
				req.setAttribute("article_no", article_no);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        req.setAttribute("article_no", article_no);
        
        return "/list.do";
			
	}

}
---------------------------------------------

package dao;

import java.util.List;

public class RemoveService {
	
	private BoardDAO boardDAO = new BoardDAO();
	private ArticleVO articleVO = new ArticleVO();

	public RemoveService() {
		boardDAO = new BoardDAO();
		articleVO = new ArticleVO();
	}
	
//	public boolean chk(int article_no, String password) {
//		boolean result = boardDAO.PwdCheck(article_no, password);
//		return result;
//	}
	
	public ArticleVO deleteArticle(int article_no) {
		ArticleVO article = null;
		article = boardDAO.deleteArticle1(article_no);
		article = boardDAO.deleteArticle2(article_no);
		return article;
	}

}

---------------------------------------------
package dao;

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


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

import jdbc.JdbcUtil;
import jdbc.connection.ConnectionProvider;
import member.model.Member;

public class BoardDAO {
	private DataSource dataFactory;
	Connection conn;
	PreparedStatement pstmt;
	
	private static BoardDAO instance = new BoardDAO();

	public static BoardDAO getInstance() {
		if (instance == null)              
		   instance = new BoardDAO();
		return instance;
	}

	public BoardDAO() {
		try {
			Context ctx = new InitialContext();
			Context envContext = (Context) ctx.lookup("java:/comp/env");
			dataFactory = (DataSource) envContext.lookup("jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ArticleVO selectArticle(int article_no, int i){ // 게시글 상세 정보 조회 메소드
		ArticleVO article=new ArticleVO();
		try{
		conn = dataFactory.getConnection();
		
		if(i!=-1) { //조회수 증가 메소드
			String query = "update article set read_cnt = read_cnt+1 where article_no = " + article_no;
			System.out.println(query);
			pstmt = conn.prepareStatement(query);
			pstmt.executeUpdate();
		}
		
		String query ="select a.article_no, a.writer_id, a.writer_name, a.title, ac.content, a.regdate, a.moddate, a.read_cnt"
			                     +" from article a, article_content ac" 
			                     +" where a.article_no = ac.article_no"
								 +" and a.article_no=?";
		System.out.println(query);
		pstmt = conn.prepareStatement(query);
		pstmt.setInt(1, article_no);
		ResultSet rs =pstmt.executeQuery();
		rs.next();
		int _article_no =rs.getInt("article_no");
		String writer_id = rs.getString("writer_id");
		String writer_name = rs.getString("writer_name");
		String title = rs.getString("title");
		Date regdate = rs.getDate("regdate");
		Date moddate = rs.getDate("moddate");
		int read_cnt = rs.getInt("read_cnt");
		String content = rs.getString("content");

		article.setArticle_no(_article_no);
		article.setWriter_id(writer_id);
		article.setWriter_name(writer_name);
		article.setTitle(title);
		article.setRegdate(regdate);
		article.setModdate(moddate);
		article.setRead_cnt(read_cnt);
		article.setContent(content);
		rs.close();
		pstmt.close();
		conn.close();
		}catch(Exception e){
		e.printStackTrace();	
		}
		return article;
		}
	
	public boolean PwdCheck(int article_no, String password) { // 게시글 수정, 삭제시 확인 - passChkProc.jsp 에서 사용
		String pwd="";
		boolean result = false;
		try {
			conn = dataFactory.getConnection();
			String query = "select password from article";
				query += " where article_no='"+article_no+"'";
			pstmt = conn.prepareStatement(query);
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			pwd = rs.getString("password");
			System.out.println(pwd);
			rs.close();
			pstmt.close();
			conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		result = password.equals(pwd);
		System.out.println("password : "+password + "//pwd : "+pwd);
		System.out.println("result결과 : "+result);
		return result;
	}
	
	public void update1(ModRequest modReq) throws SQLException { // 게시글 제목, 수정일시 수정 메소드
		conn = dataFactory.getConnection();
		try {
			conn = dataFactory.getConnection();
			String query2 = "update article set title='" + modReq.getTitle() + "'";
			query2 += ", moddate=?";
			query2 += " where article_no=" + modReq.getArticle_no() ;

			System.out.println(query2);
			pstmt = conn.prepareStatement(query2);
			pstmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
			pstmt.executeUpdate();
			pstmt.close();
			conn.close();
			} catch (Exception e) {
			e.printStackTrace();
		}
				
	}
	
	public void update2(ModRequest modReq) throws SQLException { // 게시글 내용 수정 메소드
		try {
			conn = dataFactory.getConnection();
			String query1 = "update article_content set content='" + modReq.getContent() + "'";
			query1 += " where article_no=" + modReq.getArticle_no() ;
	
			System.out.println(query1);
			pstmt = conn.prepareStatement(query1);
			pstmt.executeUpdate();
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public ArticleVO deleteArticle1(int article_no) { // 게시글 제목삭제 메소드
		ArticleVO article = new ArticleVO();
		try {
			conn = dataFactory.getConnection();
			String query1 = "DELETE FROM article WHERE article_no=" + article_no;
			System.out.println(query1);
			pstmt = conn.prepareStatement(query1);
			pstmt.executeUpdate();
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return article;
	}
	
	public ArticleVO deleteArticle2(int article_no) { // 게시글 내용삭제 메소드
		ArticleVO article = new ArticleVO();
		try {
			conn = dataFactory.getConnection();
			String query2 = "DELETE FROM article_content WHERE article_no=" + article_no;
			System.out.println(query2);
			pstmt = conn.prepareStatement(query2);
			pstmt.executeUpdate();
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return article;
	}
	
}
---------------------------------------------
package dao;

import java.sql.Date;

public class ArticleVO {
	// article 테이블
	private int article_no; // 게시글 번호
	private String writer_id; // 등록자 Id
	private String writer_name; // 등록자 이름
	private String title; // 제목
	private Date regdate; // 등록일시
	private Date moddate; // 수정일시
	private int read_cnt; // 조회수 count
	
	// article_content 테이블
	private String content; // 게시내용
	
	public ArticleVO() {
		
	}

	public ArticleVO(int article_no, String writer_id, String writer_name, String title, Date regdate, Date moddate,
			int read_cnt, String content) {
		this.article_no = article_no;
		this.writer_id = writer_id;
		this.writer_name = writer_name;
		this.title = title;
		this.regdate = regdate;
		this.moddate = moddate;
		this.read_cnt = read_cnt;
		this.content = content;
	}

	public int getArticle_no() {
		return article_no;
	}

	public void setArticle_no(int article_no) {
		this.article_no = article_no;
	}

	public String getWriter_id() {
		return writer_id;
	}

	public void setWriter_id(String writer_id) {
		this.writer_id = writer_id;
	}

	public String getWriter_name() {
		return writer_name;
	}

	public void setWriter_name(String writer_name) {
		this.writer_name = writer_name;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getRegdate() {
		return regdate;
	}

	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}

	public Date getModdate() {
		return moddate;
	}

	public void setModdate(Date moddate) {
		this.moddate = moddate;
	}

	public int getRead_cnt() {
		return read_cnt;
	}

	public void setRead_cnt(int read_cnt) {
		this.read_cnt = read_cnt;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}

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

============================= 3. 방명록 ============================= 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="java.util.*"
    import="guestbook.dao.*"
    pageEncoding="UTF-8"
    %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록</title>
</head>
<body>
<h3 align="left">방명록</h3>
<div style="border:1px solid; padding:5px; width:270px;background-color:ivory; text-align:center">
	<span style="font-weight: bold;">[ 방명록 등록 ]</span>
	<form name="addGuest" method="post" action="/BBS/addGuest.do"  encType="UTF-8">
	이름 : <input type="text" name ="guest_name"><br>
	암호 : <input type="password" name ="password"><br>	
	-------------메시지---------------
	<br><textarea rows="5" cols="30" name="message"></textarea><br>
	<input type="submit" value="등록">
	<input type="reset" value="다시입력">
	<input type="hidden" name="command" value="addGuest">
	<input type="reset" value="새로고침" onclick="location.href='/BBS/view/guestbook.jsp'">
	<c:if test="${isLogon }">
		<input type="button" value="메인으로" onClick="location.href='/BBS/loginafter.jsp'">
	</c:if>
	<c:if test="${!isLogon }">
		<input type="button" value="메인으로" onClick="location.href='/BBS/main.jsp'">
	</c:if>
	</form>
	</div>
	<%
		int pageNumber = 1;
		if(request.getParameter("pageNumber")!=null){
			pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
		}
		request.setCharacterEncoding("utf-8");
		MessageList msgList = new MessageList();
		List guestList = new ArrayList();	
		guestList = msgList.message(pageNumber);
	%>
	<c:set var="guestList" value="<%=guestList %>"/>
	<br><table border=1 width=400 align=left>
	<c:forEach var="guest" items="${guestList }">
		<tr  bgcolor="#F8ECE0">
			<td>메시지 번호 : ${guest.messageId}<br>
			손님 이름 :	${guest.name}<br>
			메시지 :${guest.message}<br>
			<a href='/BBS/view/deletePwd.jsp?messageId=${guest.messageId }'>삭제</a>
			<a href='/BBS/view/modifyPwd.jsp?messageId=${guest.messageId }'>수정</a>
			</td>
		</tr>
	</c:forEach> 
		<tr bgcolor="#F6D8CE"><td align="center">
			<c:forEach var="pageNum" begin="1" end="<%=msgList.pageTotalCount() %>">
				<a href="/BBS/view/guestbook.jsp?pageNumber=${pageNum}">[${pageNum}]</a>
			</c:forEach>
		</td></tr>
	</table>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 등록 성공 페이지</title>
</head>
<body>
<c:if test="${'false'==check }">
	<h3>메시지 등록 실패</h3>
</c:if>
<c:if test="${'false'!=check }">
	<h3>방명록에 메시지를 남겼습니다.</h3>
</c:if>
<a href='/BBS/view/guestbook.jsp'>[목록 보기]</a>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 등록 성공 페이지</title>
</head>
<body>
<c:if test="${'false'==check }">
	<h3>비밀번호가 일치하지 않습니다!</h3>
</c:if>
<c:if test="${'false'!=check }">
	<h3>메시지를 삭제하였습니다.</h3>
</c:if>

<a href='/BBS/view/guestbook.jsp'>[목록 보기]</a>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div style="border:1px solid; padding:5px; width:270px;background-color:ivory; text-align:center">
	<span style="font-weight: bold;">[ 방명록 수정 ]</span>
	<form name="modifyGuest" method="post" action="/BBS/modify.do"  encType="UTF-8">
	<table>
	<tr><td>이름  : </td><td><input type="text" name ="guest_name" value=${guest_name }></td></tr>
	<tr><td>암호변경 : </td><td><input type="password" name ="password"></td></tr>
	</table>
	-------------메시지---------------
	<br><textarea rows="5" cols="30" name="message" >${message }</textarea><br>
	<input type="submit" value="수정">
	<input type="reset" value="다시입력">
	<input type="hidden" name="messageId" value=${param.messageId }>
	<input type="button" value="목록" onClick="location.href='/BBS/view/guestbook.jsp'">
	</form>
	</div>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>수정 확인</title>
</head>
<body>
	<h3>수정: password check</h3>
	<form name="delGuest" method="post" action="/BBS/modifyCheck.do"
		encType="UTF-8">
		<input type="hidden" name="messageId" value="${param.messageId}">
		암호입력 : <input type="password" name="password"> <input
			type="submit" value="확인"> <input type="reset" value="취소"
			onclick="history.back()">
	</form>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 암호확인 결과</title>
</head>
<body>
	<h3>비밀번호가 일치하지 않습니다!</h3>
<a href='/BBS/view/guestbook.jsp'>[목록 보기]</a>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 수정 결과</title>
</head>
<body>
	<h3>방명록 수정이 완료되었습니다!</h3>
<a href='/BBS/view/guestbook.jsp'>[목록 보기]</a>
</body>
</html>
---------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>삭제 확인</title>
</head>
<body>
	<h3>삭제: password check</h3>
	<form name="delGuest" method="post" action="/BBS/pwdCheck.do"
		encType="UTF-8">
		<input type="hidden" name="messageId" value="${param.messageId}">
		암호입력 : <input type="password" name="password"> <input
			type="submit" value="확인"> <input type="reset" value="취소"
			onclick="history.back()">
	</form>
</body>
</html>
---------------------------------------------
package guestbook.command;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import guestbook.service.*;
import guestbook.model.*;

public class AddGuestbookHandler implements CommandHandler {
	private static final String FORM_VIEW = "view/addGuestbook.jsp";
	private AddGuestService addGuest = new AddGuestService();

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		
		req.setCharacterEncoding("utf-8");
		
		GuestbookVO vo = new GuestbookVO();
		String message = req.getParameter("message");
		String name = req.getParameter("guest_name");
		String pwd = req.getParameter("password");
		
		vo.setMessage(message);
		vo.setName(name);
		vo.setPassword(pwd);
		try {
			if((message!=null && message.length()!=0)
					&&(name!=null && name.length()!=0)
					&&(pwd!=null && pwd.length()!=0)) {
				addGuest.add(vo);
				return FORM_VIEW;
			}else {
				throw new Exception();
			}
		} catch (Exception e) {
			req.setAttribute("check", false);
			return FORM_VIEW;
		}
	}

}
---------------------------------------------
package guestbook.service;


import guestbook.dao.GuestbookDAO;
import guestbook.model.GuestbookVO;


public class AddGuestService{
	private GuestbookDAO dao = new GuestbookDAO();

	public void add(GuestbookVO vo) {
		String maxNum =Integer.toString(dao.GuestbookMax());
		vo.setMessageId(maxNum);
		dao.addGuestbook(vo);
	}
}
---------------------------------------------
package guestbook.model;

public class GuestbookVO {
	private String messageId;
	private String name;
	private String password;
	private String message;
	
	public String getMessageId() {
		return messageId;
	}
	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}
---------------------------------------------
package guestbook.dao;

import java.lang.Character.Subset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

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

import guestbook.model.GuestbookVO;

public class GuestbookDAO {

	private Connection con;
	private PreparedStatement pstmt;
	private DataSource dataFactory;
	
	public GuestbookDAO() {
		try {
			Context ctx = new InitialContext();
			Context envContext = (Context)ctx.lookup("java:/comp/env");
			dataFactory = (DataSource) envContext.lookup("jdbc/oracle");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void addGuestbook(GuestbookVO vo) {
		try {
			con = dataFactory.getConnection();
			String messageId = vo.getMessageId();
			String password = vo.getPassword();
			String name = vo.getName();
			String message = vo.getMessage();
			System.out.println("message ID : "+messageId);
			String query = "insert into guestbook_message";
			query += " (message_id, password, guest_name, message)";
			query += " values(?,?,?,?)";
			System.out.println("prepareStatement : " + query);
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, messageId);
			pstmt.setString(2, password);
			pstmt.setString(3, name);
			pstmt.setString(4, message);
			pstmt.executeUpdate();
			pstmt.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public List GuestList(int firstRow, int endRow) {
		List list = new ArrayList();
		try {
			con = dataFactory.getConnection();
			String query = "select * ";
				query += " from (select rownum rnum, a.*";
				query += " from guestbook_message a order by message_id desc) ";
				query += "where rnum >= ? and rnum <= ? ";
			pstmt = con.prepareStatement(query);
			pstmt.setInt(1, firstRow);
			pstmt.setInt(2, endRow);
			
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				String message_id = rs.getString("message_id");
				String password = rs.getString("password");
				String guest_name = rs.getString("guest_name");
				String message = rs.getString("message");
				GuestbookVO vo = new GuestbookVO();
				vo.setMessageId(message_id);
				vo.setPassword(password);
				vo.setName(guest_name);
				vo.setMessage(message);
				list.add(vo);
			}
			rs.close();
			pstmt.close();
			con.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public GuestbookVO SelectById(String id) {
		GuestbookVO vo = new GuestbookVO();
		try {
			con = dataFactory.getConnection();
			String query = "select * ";
				query += " from guestbook_message";
				query += " where message_id=?";
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, id);
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			String message_id = rs.getString("message_id");
			String password = rs.getString("password");
			String guest_name = rs.getString("guest_name");
			String message = rs.getString("message");
			vo.setMessageId(message_id);
			vo.setPassword(password);
			vo.setName(guest_name);
			vo.setMessage(message);
			rs.close();
			pstmt.close();
			con.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return vo;
	}
	
	public void GuestbookDelete(GuestbookVO vo) {
		String message_id = vo.getMessageId();
		try {
			System.out.println("delete 메소드 실행 : " + message_id);
			con = dataFactory.getConnection();
			String query = "delete from guestbook_message";
				query += " where message_id='"+message_id+"'";
			System.out.println("prepareStatement : "+  query);
			pstmt = con.prepareStatement(query);
			pstmt.executeUpdate();
			pstmt.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean PwdCheck(GuestbookVO vo) {	
		String id = vo.getMessageId();
		String delPwd = vo.getPassword();
		String pwd="";
		boolean result = false;
		try {
			con = dataFactory.getConnection();
			String query = "select password from guestbook_message";
				query += " where message_id='"+id+"'";
			pstmt = con.prepareStatement(query);
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			rs.next();
			pwd = rs.getString("password");
			rs.close();
			pstmt.close();
			con.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		result = delPwd.equals(pwd);
		System.out.println("delpwd : "+delPwd + "//pwd : "+pwd);
		System.out.println("result결과 : "+result);
		return result;
	}
	
	public int GuestbookMax() {
		System.out.println("guestbookmax실행");
		String max = "0";
		try {
			con = dataFactory.getConnection();
			String query = "select MAX(message_id) as max from guestbook_message";
			pstmt = con.prepareStatement(query);
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				max = rs.getString("max");
			}
			rs.close();
			pstmt.close();
			con.close();
			return Integer.parseInt(max)+1;
		}catch(Exception e) {
			return 1;
		}
	}
	
	public int GuestbookNum() {
		String num = "0";
		try {
			con = dataFactory.getConnection();
			String query = "select COUNT(message_id) as num "
					+ "from guestbook_message";
			pstmt = con.prepareStatement(query);
			System.out.println("prepareStatement:" + query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				num = rs.getString("num");
			}
			rs.close();
			pstmt.close();
			con.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return Integer.parseInt(num);
	}
	
	public boolean Modified(GuestbookVO vo) {
		String id = vo.getMessageId();
		String message = vo.getMessage();
		String name = vo.getName();
		String password = vo.getPassword();
		try {
			con = dataFactory.getConnection();
			String query = "UPDATE guestbook_message SET";
			if((name!=null)&&(name!="")) {
				query +=" guest_name='"+name+"',";
			}if((message!=null)&&(message!="")) {
				query +=" message='"+message+"',";
			}if((password!=null)&&(password!="")) {
				query +=" password='"+password+"',";
			}
				query = query.substring(0, query.length()-1);
				query += " WHERE message_id='"+id+"'";
			System.out.println("prepareStatement : " + query);
			pstmt = con.prepareStatement(query);
			pstmt.executeUpdate();
			pstmt.close();
		}catch(Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
}
---------------------------------------------
package guestbook.dao;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import guestbook.model.GuestbookVO;

public class MessageList {
	private static final int MESSAGE_COUNT_PER_PAGE = 3;
	GuestbookDAO dao = new GuestbookDAO();
	
	public List message(int pageNumber) {
		List list = new ArrayList();
		int messageTotalCount = dao.GuestbookNum();
		int currentPageNumber = pageNumber;
		try {
			int firstRow = 0;
			int endRow = 0;
			if (messageTotalCount > 0) {
				firstRow = (pageNumber - 1) * MESSAGE_COUNT_PER_PAGE + 1;
				endRow = firstRow + MESSAGE_COUNT_PER_PAGE - 1;
				list = dao.GuestList(firstRow, endRow);
			} else {
				currentPageNumber = 0;
				list = Collections.emptyList();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public int pageTotalCount() {
		int messageTotalCount = dao.GuestbookNum();
		int pageNum = messageTotalCount / 3;
		if(pageNum == 0) {
			return 1;
		}else if((pageNum !=0) && (messageTotalCount%3==0)) {
			return pageNum;
		}else {
			return pageNum+1;
		}
	}
}
---------------------------------------------
package guestbook.command;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import guestbook.service.*;
import guestbook.model.*;


public class ModifyHandler implements CommandHandler{
	private static final String FORM_VIEW = "view/modifyResult.jsp";
	private GuestModifyService checkService = new GuestModifyService();
	
	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		
		req.setCharacterEncoding("utf-8");
		
		GuestbookVO vo = new GuestbookVO();
		vo.setMessageId(req.getParameter("messageId"));
		vo.setMessage(req.getParameter("message"));
		vo.setPassword(req.getParameter("password"));
		vo.setName(req.getParameter("guest_name"));
		System.out.println(vo.getName());
		if(checkService.modify(vo)) {
			return FORM_VIEW;
		}else {
			req.setAttribute("check", false);
			return FORM_VIEW;
		}
	}
}
---------------------------------------------
package guestbook.command;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import guestbook.service.*;
import guestbook.model.*;


public class ModifyCheckHandler implements CommandHandler{
	private static final String FORM_VIEW = "view/guestModify.jsp";
	private GuestModifyService checkService = new GuestModifyService();
	
	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		
		req.setCharacterEncoding("utf-8");
		
		GuestbookVO vo = new GuestbookVO();
		vo.setMessageId(req.getParameter("messageId"));
		vo.setPassword(req.getParameter("password"));
		if(checkService.modifyCheck(vo)) {
			vo = checkService.selectById(vo.getMessageId());
			req.setAttribute("guest_name", vo.getName());
			req.setAttribute("message", vo.getMessage());
			return FORM_VIEW;
		}else {
			return "view/modifyPwdFalse.jsp";
		}
	}
}
---------------------------------------------
package guestbook.service;

import guestbook.dao.GuestbookDAO;
import guestbook.model.GuestbookVO;

public class GuestModifyService {
	private GuestbookDAO dao = new GuestbookDAO();

	public boolean modifyCheck(GuestbookVO vo) {
		boolean result = dao.PwdCheck(vo);
		if(result) {
			return true;
		}
		return false;
	}
	
	public boolean modify(GuestbookVO vo) {
		boolean result = dao.Modified(vo);
		if(result) {
			return true;
		}
		return false;
	}
	public GuestbookVO selectById(String message_id) {
		GuestbookVO vo = dao.SelectById(message_id);
		return vo;
	}
	
}
---------------------------------------------
package guestbook.command;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import command.CommandHandler;
import guestbook.service.*;
import guestbook.model.*;

public class PwdCheckHandler implements CommandHandler {
	private static final String FORM_VIEW = "view/deleteGuestbook.jsp";
	private PwdCheckService checkService = new PwdCheckService();

	@Override
	public String process(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		if (req.getMethod().equalsIgnoreCase("GET")) {
			return processForm(req, res);
		} else if (req.getMethod().equalsIgnoreCase("POST")) {
			return processSubmit(req, res);
		} else {
			res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
			return null;
		}
	}

	private String processForm(HttpServletRequest req, HttpServletResponse res) {
		return FORM_VIEW;
	}

	private String processSubmit(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		req.setCharacterEncoding("utf-8");
		
		GuestbookVO vo = new GuestbookVO();
		vo.setMessageId(req.getParameter("messageId"));
		vo.setPassword(req.getParameter("password"));
		if(checkService.delete(vo)) {
			return FORM_VIEW;
		}else {
			req.setAttribute("check", false);
			return FORM_VIEW;
		}
	}
}
---------------------------------------------
package guestbook.service;

import guestbook.dao.GuestbookDAO;
import guestbook.model.GuestbookVO;

public class PwdCheckService{
	private GuestbookDAO dao = new GuestbookDAO();

	public boolean delete(GuestbookVO vo) {
		boolean result = dao.PwdCheck(vo);
		if(result) {
			dao.GuestbookDelete(vo);
			return true;
		}
		return false;
	
	}
}



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

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

14일차  (0) 2019.08.27
13일차  (0) 2019.08.26
12일차  (0) 2019.08.19
11일차  (0) 2019.08.14
10일차  (0) 2019.08.13
And

12일차

|
@@@@@@@@@@@@@@@@@ 0819 실습

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>first</title>
</head>
<body>
	<input type="button" value="회원가입하기" onClick="location.href='signup.jsp'">
	<input type="button" value="로그인하기" onClick="location.href='login.jsp'">
</body>
</html>

===========

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="day0819.*"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="m" class="day0819.MemberBean" scope="session"/>
<jsp:setProperty property="*" name="m" />
<jsp:setProperty property="name" name="m" value="<%=m.getName()%>" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 창</title>
</head>
<body>
	<form method = "post" action="/pro14/MemberServlet">
		아이디 : <input type = "text" name = "member_id"><br>
		암호 : <input type = "password" name = "password"><br>
		<input type = "submit" value = "로그인">
		<input type="hidden" name="name" value=<jsp:getProperty  name="m" property="name" />>
		<input type="hidden" name="mode" value="login">
	</form>
</body>
</html>

==============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="day0819.*"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
	<script type="text/javascript">
		function fn_validate(){
			var frmLogin = document.frmLogin;
			var member_id = frmLogin.member_id.value;
			var name = frmLogin.name.value;
			var password = frmLogin.password.value;
			var password_chk = frmLogin.password_chk.value;
			
			if(member_id.length == 0 || member_id == ""){
				alert("아이디는 필수입니다.");
			} else if (name.length == 0 || name == ""){
				alert("이름은 필수입니다.");
			} else if (password.length == 0 || password == ""){
				alert("비밀번호는 필수입니다.");
			} else if (password !== password_chk){
				alert("비밀번호가 동일하지 않습니다.");
			} else {
				frmLogin.method = "post";
				frmLogin.action = "/pro14/MemberServlet";
				frmLogin.submit();
			}
		}
	</script>
<title>회원가입 창</title>
</head>
<body>
	<form name="frmLogin" method="post" encType="UTF-8">
		ID<input type="text" name="member_id"><br>
		이름<input type="text" name="name"><br>
		암호<input type="password" name="password"><br>
		확인<input type="password" name="password_chk"><br>
		<input type="submit" value="가입" onClick="fn_validate()">
		<input type="hidden" name="mode" value="signup">
	</form>
</body>
</html>

====================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");
	String member_id = request.getParameter("member_id");
	session.getAttribute("member_id");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>암호변경 창</title>
</head>
<body>
	<form method = "post" action="/pro14/MemberServlet">
		현재 암호 : <input type = "password" name = "password"><br>
		새 암호 : <input type = "password" name = "password_new"><br>
		<input type = "submit" value = "암호변경">
		<input type="hidden" name="member_id" value=<%= member_id %>>
		<input type="hidden" name="mode" value="changeok">
	</form>
</body>
</html>

========================

package day0819;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class MemberServlet
 */
@WebServlet("/MemberServlet")
public class MemberServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String p_mode = request.getParameter("mode");
		
	    MemberDAO dao=new MemberDAO();
	    MemberBean vo = new MemberBean();
	    
    	String member_id = request.getParameter("member_id");
    	String password = request.getParameter("password");
    	String password_new = request.getParameter("password_new");
    	String name = request.getParameter("name");
    	
    	vo.setMember_id(member_id);
    	vo.setName(name);
    	vo.setPassword(password);
	    
	    if(p_mode != null && p_mode.equals("change")) {
			RequestDispatcher dispatch = request.getRequestDispatcher("/pro14/day0819/change.jsp");
			dispatch.forward(request, response);
//	    	request.setAttribute("member_id", member_id);
//	    	response.sendRedirect("/pro14/day0819/change/?member_id=member_id.jsp");
	    }else if(p_mode != null && p_mode.equals("changeok")) {
	    	HttpSession session = request.getSession();
			session.setAttribute("result", true); //조회 결과가 true이면 isLogOn 속성을 true로 세션에 저장.
			session.setAttribute("change.member_id", member_id); // 조회한 결과가 true이면 ID와 pwd를 세션에 저장.
			session.setAttribute("change.password", password);
	    	dao.change(member_id, password, password_new);
	    	response.sendRedirect("/pro14/day0819/first.jsp");
		}else if(p_mode != null && p_mode.equals("signup")) {
	    	dao.signup(vo);
	    	response.sendRedirect("/pro14/day0819/first.jsp");
	    }else if(p_mode != null && p_mode.equals("login")) {
	    	boolean result = dao.isExisted(vo);
			if(result) {
				// 사용자 존재하므로 세션에 사용자 정보 설정
//				member_id="";
//				password="";
//				result=false;
				System.out.println(name + "2");
				HttpSession session = request.getSession();
				// 로그인 성공여부 설정
//				if(session!= null) {
				session.setAttribute("result", true); //조회 결과가 true이면 isLogOn 속성을 true로 세션에 저장.
				session.setAttribute("login.member_id", member_id); // 조회한 결과가 true이면 ID와 pwd를 세션에 저장.
				session.setAttribute("login.name", name); // 조회한 결과가 true이면 ID와 pwd를 세션에 저장.
				session.setAttribute("change.member_id", member_id); // 조회한 결과가 true이면 ID와 pwd를 세션에 저장.
				session.setAttribute("login.password", password);
				out.print("<html><body>");
				out.print("안녕하세요 " + name + "님!!!");
				out.println("<input type=\"button\" value=\"로그아웃하기\" onClick=\"location.href='/pro14/day0819/first.jsp'\">");
				out.println("<input type=\"button\" value=\"암호변경하기\" onClick=\"location.href='/pro14/day0819/change.jsp?member_id=" + member_id + "'\">");
				out.print("</html></body>");
//				} else {
//					response.sendRedirect("/pro14/day0819/first.jsp");
//				}
			} else {
				out.println("<html><body><center>회원 아이디가 틀립니다.");
				out.println("<a href='/pro14/day0819/login.jsp'\">다시 로그인 하기</a>");			
				out.println("</html></body>");	
	    }
//			RequestDispatcher dispatch = request.getRequestDispatcher("/pro14/day0819/first.jsp");
//			dispatch.forward(request, response);
	}

	}
}


====================

package day0819;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemberDAO {
	private Connection con;
	private PreparedStatement pstmt; // 실무에선 PreparedStatement를 더 많이씀.
	private DataSource dataFactory;
	
	public MemberDAO()
	{
		try
		{
			Context ctx = new InitialContext();
			Context envContext = (Context)ctx.lookup("java:/comp/env");
			dataFactory = (DataSource)envContext.lookup("jdbc/oracle");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public boolean isExisted(MemberBean memberBean) {
		boolean result = false;
		String member_id = memberBean.getMember_id();
		String password = memberBean.getPassword();
		try {
			con = dataFactory.getConnection();
			// 오라클의 decode 함수를 이용해 조회하여 ID와 비밀번호가 테이블에 존재하면 true를, 존재하지 않으면 false를 조회함.
			String query = "select decode(count(*),1,'true','false') as result from member";
					query += " where member_id=? and password=?";
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, member_id);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			rs.next(); // 커서를 첫번째 레코드로 위치시킴.
			result = Boolean.parseBoolean(rs.getString("result"));
			System.out.println("result=" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public void signup(MemberBean memberBean)
	{ // 회원 가입
		try
		{
			Connection con = dataFactory.getConnection();
			String member_id = memberBean.getMember_id();
			String password = memberBean.getPassword();
			String name = memberBean.getName();
			String query = "insert into member";
			query += " (member_id,password,name,regdate)";
			query += " values(?,?,?,sysdate)"; // 순서대로 값을 assign 해야함.
			System.out.println("prepareStatement: " + query);
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, member_id);
			pstmt.setString(2, password);
			pstmt.setString(3, name);
//			pstmt.setDate(4, regdate);
			pstmt.executeUpdate();
			pstmt.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void change(String member_id, String password, String password_new)
	{ // 비밀번호 변경
		try
		{
			Connection con = dataFactory.getConnection();
			String query = "UPDATE member";
			query += " SET password = ?";
			query += " WHERE member_id = '" + member_id + "'";
			query += " AND password ='" + password + "'";
			System.out.println("prepareStatement: " + query);
			pstmt = con.prepareStatement(query);
			pstmt.setString(1, password_new);
			pstmt.executeUpdate();
			pstmt.close();
			System.out.println("비밀번호 변경 로그확인");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}


========================

package day0819;

import java.sql.Date;

public class MemberBean {
	private String member_id;
	private String password;
	private String name;
	private Date regdate;
	
	public MemberBean()
	{
		System.out.println("MemberBean 생성자 호출");
	}

	public String getMember_id() {
		return member_id;
	}

	public void setMember_id(String member_id) {
		this.member_id = member_id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

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

	public Date getRegdate() {
		return regdate;
	}

	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}
	
	
	
}

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

13일차  (0) 2019.08.26
게시판  (0) 2019.08.26
11일차  (0) 2019.08.14
10일차  (0) 2019.08.13
9일차  (0) 2019.08.12
And

11일차

|

주요내용 : Core Tag Library(C:if c:choose c:forEach c:url), 다국어 Tag Library

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
	<c:set var="id" value="hong" scope="page"/>
	<c:set var="pwd" value="1234" scope="page"/>
	<c:set var="name" value="${'홍길동'}" scope="page"/>
	<c:set var="age" value="${22}" scope="page"/>
	<c:set var="height" value="${177}" scope="page"/>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>조건문 실습</title>
</head>
<body>
	<c:if test="${true}">
		<h1>항상 참입니다</h1>
	</c:if>
	
	<c:if test="${11==11}">
		<h1>두 값은 같습니다.</h1>
	</c:if>
	
	<c:if test="${11!=31}">
		<h1>두 값은 같지 않습니다.</h1>
	</c:if>
	
	<c:if test="${(id=='hong') && (name=='홍길동')}">
		<!--String이므로 ' ' 으로 비교 -->
		<!--id와 name이 선언되어있으므로 EL태그에서 사용가능함. -->
		<h1>아이디는 ${id}이고, 이름은 ${name}입니다.</h1>
	</c:if>
	
	<c:if test="${age==22}"> <!-- int이르모 바로 비교 -->
		<h1>${name}의 나이는 ${age}살입니다.</h1>
	</c:if>
	
	<c:if test="${height>160}">
		<h1>${name}의 키는 160보다 큽니다.</h1>
	</c:if>
</body>
</html>

================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
	<c:set var="id" value="hong" scope="page"/>
	<c:set var="pwd" value="1234" scope="page"/>
	<c:set var="name" value="${'홍길동'}" scope="page"/> <!-- 주석처리시 이름을 입력하세요 라는 오류 메세지 출력 -->
	<c:set var="age" value="${22}" scope="page"/>
	<c:set var="height" value="${177}" scope="page"/>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>조건문 실습</title>
</head>
<body>
	<table border="1" align="center">
			<tr align=center bgcolor="lightgreen">
			<td width="7%"><b>아이디</b></td>
			<td width="7%"><b>비밀번호</b></td>
			<td width="7%"><b>이름</b></td>
			<td width="7%"><b>나이</b></td>
			<td width="7%"><b>키</b></td>
		</tr>
	<c:choose>
		<%-- <c:when test="${name==null}"> --%> <!-- JSP의 주석처리 기호 -->
		<c:when test="${empty name}">
			<tr align="center">
				<td colspan=5> 이름을 입력하세요!!</td> <!-- td가 아래 5개있으므로 5개로 열 병합 -->
			</tr>
		</c:when>
		<c:otherwise> // name이 정상적이면 회원정보를 출력.
			<tr align=center>
			<td>${id}</td>
			<td>${pwd}</td>
			<td>${name}</td>
			<td>${age}</td>
			<td>${height}</td>
		</tr>
		</c:otherwise>
	</c:choose>
	</table>
</body>
</html>

=======================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	List dataList = new ArrayList();
	dataList.add("hello");
	dataList.add("world");
	dataList.add("안녕하세요!!");
%>
<c:set  var="list"  value="<%=dataList  %>" />
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>반복문 실습</title>
</head>
<body>
// <c:forEach var="변수이름" items="반복할객체이름" begin="시작값" end="마지막값"
//	step="증가값" varStatus="반복상태변수이름">

	<c:forEach var="i" begin="1" end="10" step="1" varStatus="loop">
		i=${i} &nbsp;&nbsp;&nbsp; 반복횟수: ${loop.count} <br>
	</c:forEach>
	<br>
	
	<c:forEach var="i" begin="1" end="10" step="2">
		5 * ${i} = ${5*i}<br>
	</c:forEach>
	<br>
	
	<!-- c:set에서 정의한 data를 가져옴. list에 해당하는 것이 객체이면 점을 이용해 가져옴. -->
	<c:forEach  var="data" items="${list}" >
       ${data } <br> 
   	</c:forEach>
	<br>
	
	<c:set var="fruits" value="사과, 파인애플, 바나나, 망고, 귤" />
	<c:forTokens var="token" items="${fruits}" delims=",">
		${token}<br>
	</c:forTokens>
</body>
</html>

========================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	List membersList = new ArrayList();
	MemberBean m1 = new MemberBean("son", "1234", "손흥민", "son@test.com");
	MemberBean m2 = new MemberBean("ki", "4321", "기성용", "ki@test.com");
	MemberBean m3 = new MemberBean("park", "1212", "박지성", "park@test.com");
	membersList.add(m1);
	membersList.add(m2);
	membersList.add(m3);
%>
<c:set  var="membersList"  value="<%=membersList  %>" />
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>회원 정보 출력창</title>
</head>
<body>
	<table border="1" align="center">
		<tr align=center bgcolor="lightgreen">
			<td width="7%"><b>아이디</b></td>
			<td width="7%"><b>비밀번호</b></td>
			<td width="5%"><b>이름</b></td>
			<td width="5%"><b>이메일</b></td>
		</tr>
		<c:forEach var="i" begin="0" end="2" step="1">
			<tr align="center">
			<td>${membersList[i].id}</td>
			<td>${membersList[i].pwd}</td>
			<td>${membersList[i].name}</td>
			<td>${membersList[i].email}</td>
		</tr>
		</c:forEach>
	</table>
</body>
</html>

============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
	List membersList = new ArrayList();
	MemberBean m1 = new MemberBean("son", "1234", "손흥민", "son@test.com");
	MemberBean m2 = new MemberBean("ki", "4321", "기성용", "ki@test.com");
	MemberBean m3 = new MemberBean("park", "1212", "박지성", "park@test.com");
	membersList.add(m1);
	membersList.add(m2);
	membersList.add(m3);
%>
<c:set  var="membersList"  value="<%=membersList  %>" />
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>회원 정보 출력창</title>
</head>
<body>
	<table border="1" align="center">
		<tr align=center bgcolor="lightgreen">
			<td width="7%"><b>아이디</b></td>
			<td width="7%"><b>비밀번호</b></td>
			<td width="5%"><b>이름</b></td>
			<td width="5%"><b>이메일</b></td>
		</tr>
		<!-- item 속성에 membersList를 할당한 후 실행하여 자동으로 var의 member에 membersList의 MemberBean 객체가 차례대로 할당
		member7 보단 member8 방법이 좋음.-->
		<c:forEach var="member" items="${membersList}">
			<tr align="center">
			<td>${member.id}</td>
			<td>${member.pwd}</td>
			<td>${member.name}</td>
			<td>${member.email}</td>
		</tr>
		</c:forEach>
	</table>
</body>
</html>

============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import = "java.util.*, sec01.ex02.MemberBean"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<c:url var="url1" value="/test01/member1.jsp">
	<c:param name="id" value="hong"/>
	<c:param name="pwd" value="1234"/>
	<c:param name="name" value="홍길동"/>
	<c:param name="email" value="hong@test.com"/>
</c:url>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>c:url 태그 실습</title>
</head>
<body>
	<%-- <a href='${contextPath}/text01/member1.jsp'>회원정보출력</a> --%>
	<a href='${url1}'>회원정보출력</a>
</body>
</html>

=============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>catch 태그</title>
</head>
<body>

<c:catch var="ex">
name 파라미터의 값 = <%=request.getParameter("name") %><br>
<%if(request.getParameter("name").equals("test")){ %>
${param.name }은 test입니다.
<%} %>
</c:catch>
<p>
<c:if test="${ex!=null}">
익센셥이 발생하였습니다.<br>
${ex}
</c:if>
</body>
</html>

=================================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>입력창</title>
</head>
<body>
	<form action="result2.jsp" method="post">
	아이디 : <input type="text" name="userID"><br>
	비밀번호 : <input type="password" name="userPw"><br>
	<input type="submit" value="로그인">
	<input type="reset" value="다시입력">
	</form>
</body>
</html>

=============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>결과창</title>
</head>
<body>
// -- 이중조건문 구현 --
	<c:if test="${empty param.userID}">
		아이디를 입력하세요.<br>
		<a href="login.jsp">로그인 창</a>
	</c:if>
	<c:if test="${not empty param.userID}">
		<c:if test="${param.userID=='admin'}">
		<h1>관리자로 로그인 했습니다.</h1>
		<form>
			<input type=button value="회원정보 삭제하기"/>
			<input type=button value="회원정보 수정하기"/>
		</form>
	</c:if>
	<c:if test="${param.userID!='admin'}">
		<h1>환영합니다.
			<c:out value="${param.userID}"/>님!!!</h1>
	</c:if>
	</c:if>
</body>
</html>

==============================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>구구단 입력창</title>
</head>
<body>
	<h1>출력할 구구단의 수를 지정해 주세요.</h1>
	<form method=get action='guguResult2.jsp'>
	출력할 구구단 : <input type=text name='dan' /><br>
	<input type="submit" value="구구단 출력">
	</form>	
</body>
</html>

===========================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>구구단 결과창</title>
</head>
<body>
	<c:set var="dan" value="${param.dan}"/>
	<table border="1" width="800" align="center">
		<tr align="center" bgcolor="lightgreen">
			<td colspan="2">
				<c:out value="${dan}"/> 단 출력</td>
		</tr>
	<c:forEach var="i" begin="1" end="9" step="1">
		<c:if test="${i%2==0}"><!-- 짝수 -->
			<tr align="center" bgcolor="#CCFF66">
		</c:if>
		<c:if test="${i%2==1}"><!-- 홀수 -->
			<tr align="center" bgcolor="#CCCCFF">
		</c:if>
		<td width="400">
			<c:out value="${dan}"/> * <c:out value="${i}"/>
		</td>
		<td width="400">
			<c:out value="${i*dan}"/>
		</tr>
	</c:forEach>
	</table>
</body>
</html>

===================================

mem.name = 홍길동
mem.address = 서울시 강남구
mem.job = 회계사

mem.name = \ud64d\uae38\ub3d9
mem.address = \uc11c\uc6b8\uc2dc \uac15\ub0a8\uad6c
mem.job = \ud68c\uacc4\uc0ac

mem.name = hong kil-dong
mem.address = kang-nam gu, seoul
mem.job = account

========================

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.*"
    pageEncoding="UTF-8"
    isELIgnored="false"
%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> // fmt태그를 이용하기 전에 반드시 설정해야함.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL 다국어 기능</title>
</head>
<body>
	<fmt:setLocale value="en_US"/>
<%--<fmt:setLocale value="ko_KR"/>--%>
	<h1>
		회원정보<br><br>
		<fmt:bundle basename="resource.member"> // resource 패키지 아래 member 프로퍼티 파일을 읽어옴.
		이름:<fmt:message key="mem.name"/><br> // <fmt:message>태그의 key 속성에 프로퍼티 파일의 key를 지정하여 값을 출력.
		주소:<fmt:message key="mem.address"/><br>
		직업:<fmt:message key="mem.job"/><br>
		</fmt:bundle>
	</h1>
</body>
</html>

'Bitcamp > BITCAMP - Servlet & JSP' 카테고리의 다른 글

게시판  (0) 2019.08.26
12일차  (0) 2019.08.19
10일차  (0) 2019.08.13
9일차  (0) 2019.08.12
8일차  (0) 2019.08.09
And