Employee.java
package web.jdbc.test;

public class Employee {

	private int empno;
	private String ename;
	private int deptno;
	private String hiredate;
	private int sal;
	private int mgr;
	
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public int getSal() {
		return sal;
	}
	public void setSal(int sal) {
		this.sal = sal;
	}
	public int getMgr() {
		return mgr;
	}
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}
	
	
}

EmpDAO.java
package web.jdbc.test;

import java.sql.*;
import java.util.*;

public class EmpDAO {
	// 데이터베이스 연결관련정보를 문자열로 선언
	private String jdbc_driver = "oracle.jdbc.OracleDriver";
	private String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

	private Connection getConn() throws Exception{
		// JDBC 드라이버 로드하여 DriverManager에 등록함
		Class.forName(jdbc_driver);

		// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
		Connection conn = DriverManager.getConnection(db_url,"user05","user05");
		return conn;
	}

	private void closeAll(ResultSet rs, Statement stmt, Connection conn){
		try {
			if(rs!=null)rs.close();
			if(stmt!=null)stmt.close();
			if(conn!=null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Employee> getAllEmps(){
		String sql ="select * from employee";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			Employee emp = null;
			ArrayList<Employee> list = new ArrayList<Employee>();
			while(rs.next()){
				emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				list.add(emp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			closeAll(rs, stmt, conn);
		}
		return null;
	}

	// 사번을 전달받고 데이터베이스를 검색하여 해당 사원의 상세정보를 리턴한다
	// @param empno 검색할 사원의 사번
	// @return Employee 사원의 상세정보를 저장하고 있는 DTO
	public Employee getEmp(int empno){
		String sql = "select * from employee where empno="+empno;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if (rs.next()){
				Employee emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				emp.setHiredate(rs.getString("HIREDATE"));
				emp.setSal(rs.getInt("SAL"));
				emp.setMgr(rs.getInt("MGR"));
				return emp;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			closeAll(rs, stmt, conn);
		}
		return null;
	}
}

empDesc.jsp
<%@page import="web.jdbc.test.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<% 
	int empno = Integer.valueOf(request.getParameter("empno")); 
	Employee emp = dao.getEmp(empno);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
	table {border: 1px solid black;}
	td {text-align: center;}
	th {border: 1px solid black; background-color: green; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>사원의 상세정보 보기</title>
</head>
<body>
<table>
<tr>
	<td colspan="4"><h1>사번이 <%=empno %>인 사원의 상세정보</h1></td>
</tr>
<tr>
	<td>사번</td><td><%=empno %></td>
	<td>이름</td><td><%=emp.getEname() %></td>
</tr>
<tr>
	<td>부서</td><td><%=emp.getDeptno()%></td>
	<td>입사일</td><td><%=emp.getHiredate()%></td>
</tr>
<tr>
	<td>급여</td><td><%=emp.getSal()%></td>
	<td>매니져</td><td><%=emp.getMgr()%></td>
</tr>
</table>
</body>
</html>
empList.jsp
<%@page import="web.jdbc.test.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<%
	ArrayList<Employee> list = dao.getAllEmps();
%>

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
	table {border: 1px solid black;}
	td {text-align: center;}
	th {border: 1px solid black; background-color: green; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>오라클 접속 테스트</title>
</head>
<body>
<table rules="rows">
<tr>
	<th>Empno</th>
	<th>Ename</th>
	<th>Deptno</th>
</tr>
<%
	for(int i=0;i<list.size();i++){
		Employee emp = list.get(i);
		int empno = emp.getEmpno();
		%>
		<tr>
		<td><%=empno %></td> 
		<td><a href="empDesc.jsp?empno=<%=empno%>"><%=emp.getEname() %></a></td> 
		<td><%=emp.getDeptno() %></td>
		</tr>
	<%}
%>
</table>
</body>
</html>






http://dl.dropbox.com/u/92046264/303jsp/


JDBC Test in Oracle


Java 프로그램과 연결할 때 사용할 JDBC Driver는 설치된 Oracle 디렉토리에서 검색해보면 해당 오라클 버전의 JDBC Driver를 찾을 수가 있다. 만약 찾지 못하면 아래에서 다운로드할 수 있다.

ojdbc14.jar


package web.jdbc.test;
import java.sql.*;

public class OracleTest {
	public static void main(String[] args)  {
		// 데이터베이스 연결관련 변수 선언
		Connection conn = null;
		Statement stmt = null;

		// 데이터베이스 연결관련정보를 문자열로 선언
		String jdbc_driver = "oracle.jdbc.OracleDriver";
		String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

		try{
			// JDBC 드라이버 로드하여 DriverManager에 등록함
			Class.forName(jdbc_driver);

			// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
			conn = DriverManager.getConnection(db_url,"user09","user09");

			// Connection 객체로 부터 SQL문 작성을 위한 Statement 준비
			stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery("select * from emp");
			while(rs.next()) {
				System.out.println(rs.getString(1)+" " +rs.getString(2)+" " +rs.getString(3)+" " +rs.getString(4)+" " +rs.getString(5));
			}
			rs.close();
			stmt.close();
			conn.close();
		}
		catch(Exception e) {
			System.out.println(e);
		}
		System.out.println("테스트 끝");
	}
}



오라클 디비랑 잘 연결 되어서 요렇게 출력된다~~







DAO - data access object

DTO - data transfer object

ORM - (Object-relational mapping)








oracleTest.jsp
<%@page import="web.jdbc.test.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="dao" class="web.jdbc.test.EmpDAO"/>
<%
	ArrayList<Employee> list = dao.getAllEmps();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>오라클 접속 테스트</title>
</head>
<body>
<ol>
<%
	for(int i=0;i<list.size();i++){
		Employee emp = list.get(i);%>
		<li><%=emp.getEmpno() %> / <%=emp.getEname() %> / <%=emp.getDeptno() %>
	<%}
%>
</ol>
</body>
</html>
Employee.java
package web.jdbc.test;

public class Employee {
	
	private int empno; //사원번호
	private String ename;//사원이름
	private int deptno;//부서번호
	private String hiredate;//고용날짜
	private int sal;//봉급
	private int mgr;//매니져
	
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String eanme) {
		this.ename = eanme;
	}
	public int getDeptno() {
		return deptno;
	}
	public void setDeptno(int deptno) {
		this.deptno = deptno;
	}
	public String getHiredate() {
		return hiredate;
	}
	public void setHiredate(String hiredate) {
		this.hiredate = hiredate;
	}
	public int getSal() {
		return sal;
	}
	public void setSal(int sal) {
		this.sal = sal;
	}
	public int getMgr() {
		return mgr;
	}
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}	
}

EmpDAO.java
package web.jdbc.test;

import java.sql.*;
import java.util.ArrayList;

public class EmpDAO {
	// 데이터베이스 연결관련 변수 선언
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;

	// 데이터베이스 연결관련정보를 문자열로 선언
	String jdbc_driver = "oracle.jdbc.OracleDriver";//ojdbc14.jar에 있다.
	String db_url = "jdbc:oracle:thin:@211.183.3.5:1521:ORCL";

	private Connection getConn() throws Exception{

		// JDBC 드라이버 로드하여 DriverManager에 등록함
		Class.forName(jdbc_driver);

		// 로드된 드라이버를 이용하여 DB와 연결하고 Connection 인스턴스 구함
		Connection conn = DriverManager.getConnection(db_url,"user09","user09");
		return conn;
	}

	private void closeAll(ResultSet rs,Statement stmt,Connection conn){
		try{
			if(rs!=null)rs.close();
			if(stmt!=null)stmt.close();
			if(conn!=null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public ArrayList<Employee> getAllEmps(){
		String sql="select * from emp";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs =null;
		try {
			conn = getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			Employee emp = null;
			ArrayList<Employee> list = new ArrayList<Employee>();
			while(rs.next()){
				emp = new Employee();
				emp.setEmpno(rs.getInt("EMPNO"));
				emp.setEname(rs.getString("ENAME"));
				emp.setDeptno(rs.getInt("DEPTNO"));
				list.add(emp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{//오류와 관련없이 항상 실행
			closeAll(rs,stmt,conn);
		}
		return null;
	}
}



'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습10  (0) 2012.07.17
복습8  (0) 2012.07.13
복습7 회원 정보 저장 폼  (0) 2012.07.12
복습6 Cookie,Session을 이용한 login 처리,자바빈(JavaBeans)  (0) 2012.07.11
복습5 페이지 모듈화,error page,Cookie  (0) 2012.07.10

표현 언어


Expression Language

JSP에서 사용가능한 새로운 스크립트 언어

EL의 주요 기능

JSP의 네 가지 기본 객체가 제공하는 영역의 속성 사용

Collection 객체, 배열에 대한 접근 방법 제공

수치 연산, 관계 연산, 논리 연산자 제공

자바 클래스 메서드 호출 기능 제공

표현언어만의 기본 객체 제공

간단한 구문 때문에 표현식 대신 사용

기본 문법

${expr}, #{expr}

사용예

<jsp:include page="/module/${skin.id}/header.jsp" />

<b>${sessionScope.member.id}</b>님 환영합니다.

${expr}은 표현식이 실행되는 시점에 바로 값 계산

#{expr}은 값이 실제로 필요한 시점에 값 계산

JSP 템플릿 텍스트에서는 사용 불가

스크립트 요소(스크립트릿, 표현식, 선언부)를 제외한 나머지 부분에서 사용




${expr}#{expr}의 동작 방식 예

<% 
    Member m = new Member();
    m.setName("이름1");
%>
<c:set var="m" value="<%= m %>" /><%--선언시의 값을 가짐--%> 

<%-- 이 시점에는 값 생성하지 않음 --%>
<c:set var="name" value="#{m.name}" /><%--현재 값을 가지지 않음--%>

<% m.setName("이름2"); %>

${name} <%-- 사용될 때 값 계산, "이름2" 출력 --%>

<% m.setName("이름3"); %>

${name} <%-- 사용될 때 값 계산, "이름3" 출력 --%>




EL에서 기본 객체





예제
EL은 영역 개체에 있어야 인식한다.
package test.bean;

public class Member {
	
	private String name;
	private String id;
	private String pwd;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	
}

<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Member m = new Member();
	m.setId("myID");
	m.setPwd("myPWD");
	m.setName("김연아");
	pageContext.setAttribute("m", m);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
회원 이름:[${m.name }]
</body>
</html>
<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member">
	<jsp:setProperty name="m" property="name" value="김연아"/>
	<jsp:setProperty name="m" property="id" value="myID"/>
	<jsp:setProperty name="m" property="pwd" value="myPWD"/>
</jsp:useBean>    
<%-- <%
	Member m = new Member();
	m.setId("myID");
	m.setPwd("myPWD");
	m.setName("김연아");
	pageContext.setAttribute("m", m);
%> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
회원 이름:[${m.name }]
<%=m.getName() %>
</body>
</html>




<%@ page import="test.bean.Member" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String[] name={"강호동","이수근","김종민"};
	pageContext.setAttribute("arr", name);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<%=name[0] %><p/>
${arr[0]}
</body>
</html>


<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("1", "강호동");
	map.put("2", "이수근");
	map.put("three", "김종민");
	pageContext.setAttribute("map", map);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<%=map.get("1") %><p/>
${ map["1"]}<p/>
${ map.three }<!-- map에 영문이 아니면 오류가 난다. -->
</body>
</html>
<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	pageContext.setAttribute("map", map);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<%=map.get("김종민") %><p/>
${ map["김종민"]}<p/>
</body>
</html>



session 영역에서 값을 가져와서 nextPage에 출력

<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	session.setAttribute("map", map);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
&lt연락처&gt <p/>
강호동:${ map["강호동"]}<p/>
이수근:${ map["이수근"]}<p/>
김종민:${ map["김종민"]}<p/>
</body>
</html>


01


<%@ page import="test.bean.Member" %>
<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	//String[] name={"강호동","이수근","김종민"};
	ArrayList<String> name= new ArrayList<String>();
	name.add("강호동");
	name.add("이수근");
	name.add("김종민");
	HashMap<String,String> map = new HashMap<String,String>();
	map.put("강호동", "123-12321");
	map.put("이수근", "123-1232-2323");
	map.put("김종민", "234-2343-3242");
	request.setAttribute("map", map);
%>
<jsp:forward page="nextPage.jsp"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>




<%@ page import="test.bean.*, java.util.*" %>
<%@ page contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member" scope="request">
	<jsp:setProperty name="m" property="name" value="김종민"/>
	<jsp:setProperty name="m" property="id" value="myID"/>
	<jsp:setProperty name="m" property="pwd" value="myPWD"/>
</jsp:useBean>
<jsp:forward page="nextPage.jsp"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title></title>
</head>
<body>
<a href="nextPage.jsp">다음페이지로 이동</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="m" class="test.bean.Member"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
${m.name}<p/>
${m.id}<p/>
${m.pwd}<p/>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>브라우저에서 전달된 파라미터</title>
</head>
<body>
아이디 : ${param.id }<br/>
암호 : ${param.pwd }<br/>
</body>
</html>



<jsp:setProperty> 액션 태그

자바빈 객체의 프로퍼티 값 설정

구문

<jsp:setProperty name="id" property="이름" value=""  />

name - 자바빈 객체의 이름

property - 값을 설정할 프로퍼티

value - 프로퍼티의

<jsp:setProperty name="id" property="이름"
   
param="파라미터이름"  />

param - 프로퍼티의 값으로 사용할 파라미터 이름.

<jsp:setProperty name="id" property="*" />

프로퍼티와 동일한 이름의 파라미터를 이용해서 값을 설정

폼에 입력한 값을 자바 객체에 저장할 때 유용하게 사용




예제)



회원 정보 저장 폼



























Cookie 를 이용한 login 처리

cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){
		request.setAttribute("login", "pass");
	%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		Cookie cookie = new Cookie("login","pass");
		response.addCookie(cookie);
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
service.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ include file="loginCheck.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>회원 이용가능 페이지</title>
</head>
<body><p/><p/><p/>
<h1>회원이므로 이 기능을 이용할 수 있습니다.</h1>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
Cookie[] cookies = request.getCookies();
	boolean pass = false;
	if(cookies!=null){
		for(int i=0;i<cookies.length;i++){
			if(cookies[i].getName().equals("login")){
				pass = true;
				break;
			}
		}
	}
	if(!pass){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>






세션(session)이란

웹 컨테이너에서 클라이언트의 정보를 보관할 때 사용

오직 서버에서만 생성

클라이언트마다 세션이 생성





세션과 session 기본 객체

page 디렉티브의 session 속성 값을 true로 지정

-세션이 존재하지 않을 경우 세션이 생성되고, 세션이 존재할 경우 이미 생성된 세션을 사용

session 기본 객체를 이용해서 세션에 접근

-session의 기본 값은 true이므로 false로 하지 않는 이상 항상 세션 사용

<%@ page contentType = ... %>

<%@ page session = "true" %>

<%

    ...

    session.setAttribute("userInfo", userInfo);

    ...

%>

속성 이용해서 클라이언트 관련 정보 저장



Session을 이용한 login 처리

※위 cookie를 이용한 login 처리 예제와 소스 같고 아래만 소스바꿈

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		/*상태 정보가 session으로 감  */
		session.setAttribute("login","pass");
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	if(login==null){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>


모든 페이지에서 로그인체크 해서 세션정보(아이디 비번)값이 없으면 경고 창 띄우고 loginForm으로 이동

loginCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	boolean pass = false;
	if(login!=null){
		pass = true;
	}
	
%>	
<script type="text/javascript">
	var pass = <%=pass%>;
	if(!pass){
		alert("회원으로 로그인한 경우에만 사용할 수 있습니다.");
		location.href="loginForm.jsp";
	}
</script>




자바빈

Bean

-1.기본 생성자

-2.변수

-3.set,get

-4.public



자바빈(JavaBeans)


-자바빈 - 웹 프로그래밍에서 데이터의 표현을 목적으로 사용

-일반적인 구성

값을 저장하기 위한 필드

값을 수정하기 위한 setter

값을 읽기 위한 getter


public class BeanClassName {
    /* 값을 저장하는 필드 */
    private String value;
    
    /* BeanClassName의 기본 생성자 */
    public BeanClassName() {
    }
    
    /* 필드의 값을 읽어오는 값 */
    public String getValue() {
        return value;
    }

    /* 필드의 값을 변경하는 값 */
    public void setValue(String value) {
        this.value = value;
    }
}

<jsp:useBean> 태그

JSP에서 자바빈 객체를 생성할 때 사용

구문

-<jsp:useBean id="[빈이름]" class="[자바빈클래스이름]"    scope="[범위]" />

id - JSP 페이지에서 자바빈 객체에 접근할 때 사용할 이름

class - 패키지 이름을 포함한 자바빈 클래스의 완전한 이름

scope - 자바빈 객체가 저장될 영역을 지정한다. page, request, session, application 중 

하나를 값으로 갖는다. 기본값은 page.

-예

<jsp:useBean id="info" class="chap11.member.MemberInfo" scope="request" />
<%= info.getName() %>







페이지 모듈화



※JSP 주석(TomCat에 의해서 컨버젼 할때 문장 무시) : <%--  문장  --%>


<jsp:include> 액션 태그

-다른 JSP 페이지의 '실행' 결과를 현재 위치에 삽입

-동작 방식


<jsp:include> 액션 태그

구문
<jsp:include page="포함할페이지" flush="true" />
-page 속성 : 포함할 JSP 페이지
-flush 속성 : 지정한 JSP 페이지를 실행하기 전에 출력 버퍼를 플러시 할 지의 여부를 지정한다.
 true이면 출력 버퍼를 플러시하고, false이면 하지 않는다.

중복 영역을 모듈화 하는 데 유용



<jsp:param> 액션 태그
신규 파라미터를 추가하는 데 사용
<jsp:param name="파라미터이름" value="값" />

<jsp:include page="/module/top.jsp" flush="false">
    <jsp:param name="param1" value="value1" />
    <jsp:param name="param2" value="value2" />
</jsp:include>



<jsp:param> 액션 태그의 동작 방식

기존 파라미터는 유지하고 파라미터를 새로 추가
  <jsp:include>로 포함되는 페이지에서만 유효


main.jsp(위와 동일한 결과값 출력)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>메인 페이지</title>
</head>
<body>
<jsp:include page="top.jsp"/>
</body>
</html>

top.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<div style="border:1px solid red; background-color:#999999; height:100px;">
여기는 Top.jsp
</div>

보고있나






include 디렉티브

코드 차원에서 포함
구문 : <%@ include file="포함할파일" %>
활용
-모든 JSP 페이지에서 사용되는 변수 지정
-저작권 표시와 같은 간단하면서도 모든 페이지에서 중복되는 문장

main.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>메인 페이지</title>
</head>
<body>
<%-- <jsp:include page="top.jsp"/> --%>
<%@include file="top.jsp" %>
</body>
</html>


※설정파일은 점차 사라지고 있다~~



<jsp:include> 액션 태그와 include 디렉티브




<jsp:forward> 액션 태그
하나의 JSP 페이지에서 다른 JSP 페이지로 요청 처리를 전달할 때 사용
동작 방식





<jsp:forward> 액션 태그의 전형적 사용법
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    String forwardPage = null;
    
    // 조건에 따라 이동할 페이지를 지정
    if (조건판단1) {
        forwardPage = "페이지URI1";
    } else if (조건판단2) {
        forwardPage = "페이지URI2";
    } else if (조건판단3) {
        forwardPage = "페이지URI3";
    }
%>
<jsp:forward page="<%= forwardPage %>" />


기본 객체의 속성을 이용한 값 전달
속성을 이용해서 JSP 페이지 간 값 전달
 - <jsp:include>나 <jsp:forward>에서 사용



include와 forword의 차이
gugu.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String sDan = request.getParameter("dan");
	int dan = 0;
	if(sDan==null || sDan.equals("")){
		dan =2;
	}else{
	dan = Integer.valueOf(sDan);
	}
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>
guguView.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String str = (String)request.getAttribute("data");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>구구단 보기(guguView.jsp)</title>
</head>
<body style="text-align:center;">
<%=str %>
</body>
</html>




01




에러 페이지 지정 & 에러 페이지 작성

에러 페이지 지정

- <%@ page errorPage = "예외발생시보여질JSP지정" %>


에러 페이지 작성

- <%@ page isErrorPage = "true" %>

isErrorPage 속성이 true인 경우 에러 페이지로 지정

- exception 기본 객체 : 발생한 예외 객체

exception.getMessage() : 예외 메시지

exception.printStackTrace() : 예외 추적 메시지 출력

- IE에서 예외가 올바르게 보여지려면 에러 페이지가 출력한 응답 데이터 크기가 513 바이트보다 커야 함

- <% response.setStatus(HttpServletResponse.SC_OK);%>


※요즘은 web.xml이용하지 않는게 추세




gugu.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="error.jsp" %>    
<%
	String sDan = request.getParameter("dan");
	int dan =  Integer.valueOf(sDan);	
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>

error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>오류발생!!</title>
</head>
<body style="text-align:center;">
<h1>요청을 처리하는 중에 요류가 발생했습니다.</h1>
발생한 예외의 내용<p/><%=exception %>
</body>
</html>






Cookie

이용자의 상태정보를 클라이언트에 저장 할려고 하는 수단, 화면 출력용이 아님


JSP에서 쿠키 생성 / 읽기




쿠키 값의 인코딩/디코딩 처리

쿠키는 값으로 한글과 같은 문자를 가질 수 없음

-쿠키의 값을 인코딩해서 지정할 필요 있음


쿠키 값의 처리

 -값 설정시 : URLEncoder.encode("값", "euc-kr")

예, new Cookie("name", URLEncoder.encode("값", "euc-kr"));



     -값 조회시 : URLDecoder.decode("값", "euc-kr")

Cookie cookie = …; String value = URLDecoder.decode(cookie.getValue(), "euc-kr");



쿠키 값 변경
기존에 존재하는 지 확인 후, 쿠키 값 새로 설정
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
    for (int i = 0 ; i < cookies.length ; i++) {
        if (cookies[i].getName().equals(name)) {
        	Cookie cookie = new Cookie(name, value);
        	response.addCookie(cookie);
        }
    }
}


cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>




주요 기본 객체




※println()쓰는 이유
HTML소스코드 줄바꿈 되서 브라우져 소스보기에 출력되기 때문에



영역객체(Scope Object


PAGE 영역 - 하나의 JSP 페이지를 처리할 때 사용되는 영역

REQUEST 영역 - 하나의 HTTP 요청을 처리할 때 사용되는 영역

SESSION 영역 - 하나의 웹 브라우저와 관련된 영역(한 사람의 아이디 비번 ,구매한 물건의 갯수,가격 공유안됨)

APPLICATION 영역 - 하나의 웹 어플리케이션과 관련된 영역




속성(Attribute)





속성의 활용











<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	pageContext.setAttribute("myData", "페이지영역에 저장된 데이타");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Page Scope Test</title>
</head>
<body>
<%=pageContext.getAttribute("myData") %>
</body>
</html>






loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/>
</body>
</html>
loginFail.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>로그인 실패</title>
</head>
<body>
<h1>로그인에 실패하셨습니다.</h1>
</body>
</html>



012



camera.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")== null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Camera,Canon DSLR 450,1000000");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>카메라 구입 페이지</title>
</head>
<body>
<h1>카메라를 장바구니에 담았습니다.</h1>
<a href="notebook.jsp">노트북 매장 가기</a>
</body>
</html>
notebook.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Notebook,Apple MacBook Pro,1200000");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>노트북 구입 페이지</title>
</head>
<body>
<h1>노트북을 장바구니에 담았습니다.</h1>
<a href="car.jsp">자동차 매장 가기</a>
</body>
</html>
car.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("자동차,현대 소나타,8200000");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>자동차 구입 페이지</title>
</head>
<body>
<h1>자동차를 장바구니에 담았습니다.</h1>
<a href="showCart.jsp">장바구니 내용보기</a>
</body>
</html>
showCart.jsp
<%@ page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>장바구니 보기</title>
</head>
<body>
<h1>장바구니 내용</h1>
<ol>
<%
	for(int i=0;i<cart.size();i++){
		String item = cart.get(i);%>
		<li><%=item %>
 <%}
%>

</ol>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(application.getAttribute("count")==null){
		application.setAttribute("count",0);
	}
	int cnt =(Integer)application.getAttribute("count");
	cnt++;
	application.setAttribute("count",cnt);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>방문자 수</title>
</head>
<body>
<h1>현재까지의 클릭한 수</h1>
<%=application.getAttribute("count") %>
</body>
</html>


reflash 할때 마다 클릭수가 바뀐다~

선언부(Declaration)


스크립트릿이나 표현식에서 사용할 수 있는 함수를 작성할 때 사용

선언부 형식


<%!
    public 리턴타입 메서드이름(파라미터목록) {
        자바코드1;                                              메소드, 변수, 클래스 선언 가능
        자바코드2;
        ...
        자바코드n;
        return 값;
    }
%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private String createGugu(int dan){
		String str ="";
		for(int i=1;i<=9;i++){
			str +=dan + " * " + i + " = " + dan*i + "<br/>"; 
		}
		return str;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>





<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>



↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓



<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Declaration Test</title>
</head>
<body>
<%
	ArrayList<String> list = createGugu(dan);
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>





jsp 모델1 방식(JSP, JAVA) 


Gugudan.java

package web.business;

import java.util.ArrayList;

public class Gugudan {
	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}
	public ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}
}

gugudan.jsp
<%@page import="web.business.Gugudan"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<% 
	int dan= Integer.valueOf(request.getParameter("dan")); 
	Gugudan gugu = new Gugudan();
	ArrayList<String> list = gugu.createGugu(dan);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Declaration Test</title>
</head>
<body>
<%
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>






request 기본 객체


form 처리예

form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Servlet POST 방식으로 요청하기</title>
</head>
<body>
<form  action="formProc.jsp" method="post">
	취미를 선택해주세요(다수개 가능)<p/>
	여행<input type="checkbox" name="hobby" value="여행"/>
	등산<input type="checkbox" name="hobby" value="등산"/>
	게임<input type="checkbox" name="hobby" value="게임"/>
	영화<input type="checkbox" name="hobby" value="영화"/>
	놀기<input type="checkbox" name="hobby" value="놀기"/>
	<input type="submit" value="저장"/>
</form>

</body>
</html>


formProc.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("euc-kr");
	String[] hobby = request.getParameterValues("hobby");
%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>이용자가 선택한 취미</title>
</head>
<body>
<h2>이용자가 선택한 취미</h2>
<ol>
<%
	for(int i=0;i<hobby.length;i++){%>
		<li><%=hobby[i] %><br/>
<%}
%>
</ol>
</body>
</html>







리다이렉트(Redirect)
특정 페이지로 이동하라고 웹 브라우저에 응답

response.sendRedirect(String location)로 구현















Model 2 ---->MVC


C   servlet  ----HTML (x)

                       veiw (x)

                       controller(o)


V    JSP -------view(0)

                       HTML


M    JAVA







스크립트 요소

표현식(Expression) - 값을 출력                      <%=  %>     안(메소드를 선언 할 수 없다.)

스크립트릿(Scriptlet) - 자바 코드를 실행           <%   %>      


선언부(Declaration) - 자바 메서드(함수)를 정의 <%!  %>     → service 메소드 으로 나간다.


Directive                                                       <%@ %>   




<%@ page contentType = "text/html; charset=euc-kr" %>        → Directive
   include                                                                                 → 개발자가 TomCat한테 

   taglib  - JSTL                                                                                                

         Struts                                                                                              JSP → Servlet으로 바꿀때  

         Spring                                                                                                   └(Conversion Time)

<html>

<head>

  <title>HTML 문서의 제목</title>

</head>

<body>

<%                                                                                    →Scriptlet(service메소드 안쪽으로 들어가는 소스; 지역변수)

    String bookTitle = "JSP 프로그래밍";         

    String author = "최범균";

%>

<b><%= bookTitle %></b>(<%= author %>)입니다.                →Expression("bookTilte"은 service메소드 안쪽으로 간다)

</body>

</html>



<%out.print("bookTiltle");%> == <%= bookTitle %> 위 표현식을 scriptlet에 이렇게 표현 할 수 있지만 소스를 줄이기 위해 표현식으로 쓴다.

java 설치 확인

 

cmd창 열고

 

java -version     그러면 자바 설치 가 되어 있다면 설치 버젼이 나옴

 

java

 

javac

 

echo %classpath%

이렇게 나오면 오류나니

 

환경 변수에 새로 만들기

CLASSPATH

.;

 

이렇게 해줌~~

 

 

<IDE :통합 개발 환경 [integrated development environment, 統合開發環境] >

1.에디터

2.JSK 툴

3.webbrowser(client)

4.web server를 편리하게

 


JSP(잘할려면)---->servlet



Servlet - 서버(Serv)에 들어가는 작은(let) 프로그램이다..



HTTP Server   -----servlet(요청과 응답을 다룰수 있는 기능이 있음)


       ↑           

(request ) (response)

                      ↓

Webbrowser   ------http client










package test.web.servlet;

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

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

import org.apache.jasper.tagplugins.jstl.core.Out;


public class TestServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=euc-kr");//http header부분
		
		int num = Integer.valueOf(request.getParameter("num"));//request로 부터 num이라는 파라미터를 받겠다.(숫자여도 문자열로 받기 때문에 Integer)
		
		PrintWriter out = response.getWriter();
		for(int i=1;i<=9;i++){
			out.println(num + " * " + i + " = " +num*i+"</br>");
		}
		
		//server client 연결...stream
		out.println("Hello World");
		out.flush();//buffer안에 있는 데이터를 브라우져로 전송
		
	}

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

}


http://localhost:8080/WebApp/TestServlet  이러면 오류가 남


http://localhost:8080/WebApp/TestServlet?num=7

이렇게 뒤에다  num 값을 주면 7단 구구단이 출력된다.



'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습3 선언부(Declaration),request 기본 객체,리다이렉트(Redirect)  (0) 2012.07.06
복습2 스크립트 요소  (0) 2012.07.05
예비  (0) 2012.05.30
예비  (0) 2012.05.30
예비  (0) 2012.05.30
package com.util;

import java.io.IOException;
import java.io.Reader;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringUtil {
public static String clobToString(ResultSet rs, String msg)
throws SQLException, IOException {
StringBuffer sb = new StringBuffer();
Reader rd = rs.getCharacterStream(msg);
char[] buffer = new char[1024];
int byteRead;
while ((byteRead = rd.read(buffer, 0, 1024)) != -1) {
sb.append(buffer, 0, byteRead);
}
rd.close();
return sb.toString();
}
}


String을 리턴함.






http://www.okjsp.pe.kr/seq/104320




요즘 대세라 할 수 있는 날짜 표기 입니다



자바파일 에서 properties 파일 경로 설정


그리고 Date 타입 설정후 리턴되는 값을 사용


'JSP > 기본(Oracle)' 카테고리의 다른 글

MVC 모델2 : (Album게시판)  (2) 2012.06.20
방명록  (0) 2012.06.20
회원관리  (1) 2012.06.20
모델2 : MVC : Model View Controller - DB연동  (0) 2012.06.20
모델2 : MVC : Model View Controlle r- DB연동없이  (0) 2012.06.20


프로젝트설정.txt

테이블 명세

테이블명 : album

컬럼명 

글번호 num    number       primary key

작성자 writer              not null

제목   subject             not null

이메일 email             

내용   content    clob     not null

비밀번호 passwd              not null

작성일   reg_date timestamp  not null

조회수   readcount number(4) default 0

ip       ip                  not null

저장이미지 image (파일명 저장)


시퀀스명 : album_seq


테이블 만들기

create table album(
num number primary key,
writer varchar2(20) NOT NULL,
subject varchar2(100) NOT NULL,
email varchar2(40),
content clob NOT NULL,
passwd varchar2(10) NOT NULL,
reg_date TIMESTAMP NOT NULL,
readcount number(4) DEFAULT 0,
ip varchar2(20) NOT NULL,
image varchar2(40));

create sequence album_seq;



수업메모


1 Album 테이블의 컬럼

2 Album 기본구성 

  1. 싱글턴 패턴

  2. getConnection

  3. execClose()

3 액션 WriteFormAction -> /view2/writeForm.jsp  (num,readcount,reg-date,ip 는빼고  폼에서 넘김)

4 맵핑 : commandMap.properties


AlbumDao

 insertArticle(Album album){


sql = insert into album (컬럼명) value(???)


num album_seq.nextval

writer

subject

email

conten

password

reg_date sysdate

readcount

ip

image

}


파일


낙엽||jsp 분리


바뀐이름.jsp



주소 : D:/javaWork/work_jsp2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/album/upload

\=>/ 셀렉트라인즈





1. 글쓰기 : WriteFormAction ,WriteProAction

2. 목록 : ListAction (검색)

3. 상세보기 : ContentAction

4. 수정 : UpdateFormAction, UpdateProAction

5. 삭제 : DeleteFormAction, DeleteProAction


1. 글쓰기 : writeForm ,writePro

2. 목록 : List (검색)

3. 상세보기 : content

4. 수정 : updateForm, updatePro

5. 삭제 : deleteForm, deletePro




clob 읽어오기


목록 ->상세 -> 수정 -> 삭제



                    StringBuffer output = new StringBuffer(); 

                    Reader input = rs.getCharacterStream("content"); 

                    char[] buffer = new char[1024]; 

                    int byteRead = 0; 

                    while((byteRead=input.read(buffer,0,1024))!=-1){ 

                     output.append(buffer,0,byteRead); 

                    } 

                    // contents -> CLOB 데이터가 저장될 String

                    String content = output.toString();



                    album.setContent(content);

                    


album.war     

album (1).war




프로젝트명 : album 

팩키지


Java Resources

            src

                 com.action

                            ContentAction

package com.action;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;

public class ContentAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
            
        int num =Integer.parseInt(request.getParameter("num"));
        
        AlbumDao manager = AlbumDao.getInstance();
        Album album = manager.getArticle(num);
        if(album !=null){
            album.setReadcount(manager.updateReadCount(num));
        }        
        
        request.setAttribute("album", album);
        
        return "/view2/content.jsp;";
    }
}



                            DeleteFormAction

package com.action;

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

import com.controller.Action;

public class DeleteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
            
        return "/view2/deleteForm.jsp";
    }
}



                            DeleteProAction

package com.action;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
//import com.oreilly.servlet.MultipartRequest;
import com.util.FileUtil;

public class DeleteProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        request.setCharacterEncoding("utf-8");

        int num = Integer.parseInt(request.getParameter("num"));
        String passwd = request.getParameter("passwd");

        AlbumDao manager = AlbumDao.getInstance();
        int check = manager.userCheck(num, passwd);

        if(check== 1){     
            
            Album album = manager.getArticle(num);
            manager.deleteArticle(num);
            
            if(album.getImage() != null){
                FileUtil.removeFile(album.getImage());                
            }
        }                   

        request.setAttribute("check", new Integer(check));

        return "/view2/deletePro.jsp";
    }
}



                            ListAction

package com.action;

import java.util.List;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.AlbumPage;
import com.domain.Album;


public class ListAction implements Action{
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
    request.setCharacterEncoding("utf-8");

    String keyField =request.getParameter("keyField");
    String keyWord =request.getParameter("keyWord");
    if(keyField==null){
        keyField="";
    }
    if(keyWord==null){
        keyWord="";
    }    
    
    String pageNum =request.getParameter("pageNum");
    
    if(pageNum ==null){
        pageNum = "1";
    }    
    
    int pageSize = 20;
    int currentPage = Integer.parseInt(pageNum);
    int startRow =(currentPage-1)*pageSize +1;
    int endRow =currentPage * pageSize;
    int count = 0;
    int number = 0;
    
    List<Album> albumList =null;
    AlbumDao manager = AlbumDao.getInstance();
    count =manager.getArticleCount(keyField,keyWord);
    
    if(count>0){
        albumList = manager.getArticles(startRow, endRow, keyField, keyWord);
    }
    //가짜 글번호
    number=count-(currentPage-1)*pageSize;

    AlbumPage page= new AlbumPage();
    page.setCount(count);
    page.setCurrentPage(currentPage);
    page.setNumber(number);
    page.setPageSize(pageSize);    
    page.setKeyField(keyField);    
    page.setKeyWord(keyWord);    
    
    request.setAttribute("page", page);
    request.setAttribute("albumList", albumList);

    return "/view2/list.jsp";
    }
}



                            UpdateFormAction

package com.action;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;

public class UpdateFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        int num = Integer.parseInt(request.getParameter("num"));
        
        AlbumDao manager = AlbumDao.getInstance();
        Album album = manager.getArticle(num);        

        request.setAttribute("album", album);
        
        return "/view2/updateForm.jsp";
    }
}



                            UpdateProAction

package com.action;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
import com.oreilly.servlet.MultipartRequest;
import com.util.FileUtil;

public class UpdateProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        request.setCharacterEncoding("utf-8");

        MultipartRequest multi = FileUtil.createFile(request);
        //전송된이미지정보
        String image= multi.getFilesystemName("image");
        
        AlbumDao manager = AlbumDao.getInstance();      
        //인증
        int check = manager.userCheck(Integer.parseInt(multi.getParameter("num")),multi.getParameter("passwd"));

                
        if(check==1){        
            
            String originImage = multi.getParameter("originImage");            

            Album album =new Album();        

            album.setNum(Integer.parseInt(multi.getParameter("num")));
            album.setWriter(multi.getParameter("writer"));
            album.setEmail(multi.getParameter("email"));   
            album.setSubject(multi.getParameter("subject"));
            album.setPasswd(multi.getParameter("passwd"));
            album.setContent(multi.getParameter("content"));
            album.setIp(request.getRemoteAddr());

            if(image !=null){      
                //이미지가 변경되었을 경우
                album.setImage(FileUtil.rename(image));
            }else{
                //이미지가 변경되지 않았을경우
                album.setImage(originImage);
            }
            manager.update(album);
            if(image !=null){
                FileUtil.removeFile(originImage);
            }
        }else{
            //비번이 틀려 인증 실패시 올리려고 전송된 이미지 삭제
            if(image !=null)FileUtil.removeFile(image);
        }
        
        request.setAttribute("check", new Integer(check));

        return "/view2/updatePro.jsp;";
    }
}



                            WriteFormAction

package com.action;

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

import com.controller.Action;

public class WriteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        return "/view2/writeForm.jsp";
    }
}



                            WriteProAction

package com.action;

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

import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
import com.util.FileUtil;
import com.oreilly.servlet.MultipartRequest;

public class WriteProAction  implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        MultipartRequest multi =FileUtil.createFile(request);
        
        Album album = new Album();

        album.setWriter(multi.getParameter("writer"));
        album.setSubject(multi.getParameter("subject"));
        album.setEmail(multi.getParameter("email"));
        album.setContent(multi.getParameter("content"));
        album.setPasswd(multi.getParameter("passwd"));
        album.setIp(request.getRemoteAddr());
        //image 파라미터네임
        album.setImage(FileUtil.rename(multi.getFilesystemName("image")));

        AlbumDao manager = AlbumDao.getInstance();
        manager.insertArticle(album);
        
        return "/view2/writePro.jsp";
    }
}




                 com.controller

                            Action

package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
    public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable;
}

   


                            Controller

package com.controller;

import java.io.FileInputStream;
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.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
           
public class Controller extends HttpServlet {
      
    private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장

    //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
    //명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            String configFilePath = config.getServletContext().getRealPath(
                      configFile);
            fis = new FileInputStream(configFilePath);
            prop.load(fis);
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ex) {
                }
        }
        Iterator keyIter = prop.keySet().iterator();
        while (keyIter.hasNext()) {
            String command = (String) keyIter.next();
            String handlerClassName = prop.getProperty(command);
            try {
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandMap.put(command, handlerInstance);
            } catch (ClassNotFoundException e) {
                throw new ServletException(e);
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
        }
    }

    public void doGet(//get방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    protected void doPost(//post방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    //시용자의 요청을 분석해서 해당 작업을 처리
    private void requestPro(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        String view = null;
        Action com=null;
        
        try {
            String command = request.getRequestURI();
            if (command.indexOf(request.getContextPath()) == 0) {
               command = command.substring(request.getContextPath().length());
            }
            com = (Action)commandMap.get(command); 
            view = com.execute(request, response);
        } catch(Throwable e) {
            throw new ServletException(e);
        }   
        RequestDispatcher dispatcher =request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}



                 com.dao

                            AlbumDao

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
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.Album;
import com.util.StringUtil;

public class AlbumDao {

    private static AlbumDao instance =new AlbumDao();

    //싱글턴 패턴
    private AlbumDao(){}
    public static AlbumDao 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/orcl");

        return ds.getConnection();
    }

    //글쓰기 등록
    public void insertArticle(Album album)throws Exception{

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

        try{
            conn= getConnection();
            //빠지는게 있을때는 컬럼명을 다 넣어줘야함
            sql = "insert into ALBUM (num,writer,subject,email,content,passwd,reg_date,ip,image) " +
                    "values(album_seq.nextval,?,?,?,?,?,sysdate,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, album.getWriter());
            pstmt.setString(++cnt, album.getSubject());
            pstmt.setString(++cnt, album.getEmail());
            pstmt.setString(++cnt, album.getContent());
            pstmt.setString(++cnt, album.getPasswd());
            pstmt.setString(++cnt, album.getIp());
            pstmt.setString(++cnt, album.getImage());
            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 ALBUM";
                pstmt =conn.prepareStatement(sql);
            }else{
                sql="select count(*) from album 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<Album> getArticles(int startRow, int endRow, String keyField,String keyWord)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List<Album> list =null;
        String sql=null;
        
        try{
            conn =getConnection();
            if(keyWord == null || "".equals(keyWord.trim())){
                sql ="select * from (select a.*, rownum rnum from (select * from ALBUM order by num 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 ALBUM where "+keyField+" like ? order by num 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<Album>();                
                do{
                    Album album =new Album();
                    album.setNum(rs.getInt("num"));
                    album.setWriter(rs.getString("writer"));
                    album.setSubject(rs.getString("subject"));
                    album.setEmail(rs.getString("email"));
                    album.setPasswd(rs.getString("passwd"));
                    album.setReg_date(rs.getTimestamp("reg_date"));
                    album.setIp(rs.getString("ip"));
                    album.setImage(rs.getString("image"));                            
                    album.setReadcount(rs.getInt("readcount"));
                    album.setContent(StringUtil.clobToString(rs,"content"));
                    list.add(album);
                }while(rs.next());
            }else{
                list = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return list;
    }
    
    //상세페이지
    public Album getArticle(int num)throws Exception{
        Connection conn =null;
        PreparedStatement  pstmt= null;
        ResultSet rs = null;
        Album album =null;
        String sql=null;
        
        try{
            conn=getConnection();
            sql ="select * from ALBUM where num = ? ";

            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                album =new Album();
                album.setNum(rs.getInt("num"));
                album.setWriter(rs.getString("writer"));
                album.setSubject(rs.getString("subject"));
                album.setEmail(rs.getString("email"));
                album.setPasswd(rs.getString("passwd"));
                album.setReg_date(rs.getTimestamp("reg_date"));
                album.setIp(rs.getString("ip"));
                album.setImage(rs.getString("image"));            
                album.setReadcount(rs.getInt("readcount"));
                album.setContent(StringUtil.clobToString(rs,"content"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return album;
    }
    
    //조회수증가
    public int updateReadCount(int num)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs= null;
        int count =0;
        String sql =null;
        
        try{
            conn=getConnection();
            
            //조회수 증가
            sql="update album set readcount=readcount+1 where num = ?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();
            
            //증가된 조회수 조회
            sql="select readcount from album where num = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                count =rs.getInt(1);
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }            
        return count;
    }
    
    //수정
    public void update(Album album)throws Exception{
            Connection conn=null;
            PreparedStatement pstmt =null;
            int cnt =0;
            String sql = null;
            
            try{
                conn =getConnection();
                sql = "update ALBUM set writer=?,email=?, subject=?,image=?,content=? where num=?";
                pstmt =conn.prepareStatement(sql);                
                pstmt.setString(++cnt, album.getWriter());
                pstmt.setString(++cnt, album.getEmail());
                pstmt.setString(++cnt, album.getSubject());    
                pstmt.setString(++cnt, album.getImage());    
                pstmt.setString(++cnt, album.getContent());    
                pstmt.setInt(++cnt, album.getNum());
                
                pstmt.executeUpdate();
                
            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                execClose(null,pstmt,conn);
            }
    }
    
    //삭제
    public void  deleteArticle(int num)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        String sql=null;        
        
        try{            
            conn= getConnection();
            
            sql="delete from ALBUM where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();

        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
        return ;
    }
        
    //인증
    public int userCheck(int num, String passwd)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        String dbpasswd="";
        String sql="";
        int x=-1;
        try{

            conn= getConnection();
            sql="select passwd from ALBUM where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();

            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd)){
                    x=1;//인증성공
                }else
                    x=0;//비밀전호 틀림
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return x;
    }

    //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){}
    }
}



                 com.domain

                            Alubm

package com.domain;

import java.sql.Timestamp;

public class Album {
    
    private int num;
    private String writer;
    private String subject;
    private String email;
    private String content;
    private String passwd;
    private Timestamp reg_date;
    private int readcount;
    private String ip; 
    private String image;
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getWriter() {
        return writer;
    }
    public void setWriter(String writer) {
        this.writer = writer;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public Timestamp getReg_date() {
        return reg_date;
    }
    public void setReg_date(Timestamp reg_date) {
        this.reg_date = reg_date;
    }
    public int getReadcount() {
        return readcount;
    }
    public void setReadcount(int readcount) {
        this.readcount = readcount;
    }
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
}



                            AlbumPage

package com.domain;

public class AlbumPage {
    
    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;
    }        
}



                 com.util

                            FileUtil

package com.util;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class FileUtil {

    public static final String UPLOAD_PATH = "D:/javaWork/work_jsp2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/album/upload";
    public static final String  ENCODING_TYPE = "utf-8";
    public static final int MAX_SIZE = 10*1024*1024;//10M
    
    public static  MultipartRequest createFile(HttpServletRequest request) throws IOException{
        return new MultipartRequest(request,UPLOAD_PATH,MAX_SIZE,ENCODING_TYPE,new DefaultFileRenamePolicy());
    }
    
    //알아서 파일명을 만들어줌
    public static String rename(String filename) throws Exception{
        if(filename ==null) return null;
        String newName = Long.toString(System.currentTimeMillis())+(int)(Math.random()*50);
        return rename(filename, newName);
    }
    
    //지정한 파일명을 사용한다.
    public static String rename(String filename, String newName) throws Exception{
        if(filename == null) return null;
        File file = new File(UPLOAD_PATH,filename);
        //파일명을 원하는 형식으로 변경하기
        int idx = filename.lastIndexOf(".");
        String extention = "";
        String newFileName = "";

        if(idx != -1) {
            extention = filename.substring(idx);
        }
        // newName 전달시 확장자를 제외해야 하지만 확장자를 포함할 경우 제거함
        int newIdx = newName.lastIndexOf(".");
        if(newIdx !=-1){
            newName = newName.substring(0,newIdx);
        }

        newFileName = newName + extention.toLowerCase();
        File fs = new File(UPLOAD_PATH,newFileName);
        file.renameTo(fs);

        return newFileName;
    }
    
    //파일삭제
    public static void removeFile(String filename){
        if(filename != null){
            File file = new File(UPLOAD_PATH,filename);
            if(file.exists()) file.delete();
        }
    }
}



                            StringUtil

package com.util;

import java.io.IOException;
import java.io.Reader;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringUtil {
    public static String clobToString(ResultSet rs, String msg) throws SQLException, IOException{
        StringBuffer sb = new StringBuffer();
        //getCharacterStream : String 으로 읽어드려 char 배열에넣고 StringqBuffer에 넣음
        Reader rd = rs.getCharacterStream(msg);
        char[] buffer = new char[1024];
        int byteRead;
        while((byteRead=rd.read(buffer,0,1024))!=-1){
            sb.append(buffer,0,byteRead);
        }
        rd.close();
        return sb.toString(); 
    }
}




WebContent

            docs

                 album.sql

create table album(
num number primary key,
writer varchar2(20) NOT NULL,
subject varchar2(100) NOT NULL,
email varchar2(40),
content clob NOT NULL,
passwd varchar2(10) NOT NULL,
reg_date date NOT NULL,
readcount number(4) DEFAULT 0,
ip varchar2(20) NOT NULL);

create sequence album_seq;




            META-INF

                 context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!--
maxActive="20" //최대 커넥션 수
maxIdle="10"   //미리 만들어둘 기본커낵션 수
-->
    <Resource name="jdbc/orcl"
              auth="container"
              type="javax.sql.DataSource"
              username="hr"
              password="hr"
              driverClassName="oracle.jdbc.driver.OracleDriver"
              factory="org.apache.commons.dbcp.BasicDataSourceFactory"
              url="jdbc:oracle:thin:@localhost:1521:orcl"
              maxActive="20"
              maxIdle="10" />
</Context>

            


view2 

    content.jsp

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width ="70%" border ="1" cellpadding="0" cellspacing="0" align="center">
<tr><td  colspan="2" align="center"><h1>상세보기</h1></tr>
<tr>
<td>글번호</td>
<td>${album.num}</td>
</tr>

<tr>
<td>작성자</td>
<td>${album.writer}</td>
</tr>

<tr>
<td>IP</td>
<td>${album.ip}</td>
</tr>
<tr>
<td>조회수</td>
<td>${album.readcount}</td>
</tr>

<tr>
<td>작성일</td>
<td><fmt:formatDate value="${album.reg_date}" pattern="yyyy년MM월dd일"/></td>
</tr>
<tr>
    <td>이메일</td>
    
<c:if test="${! empty album.email}">
    <td>${album.email}</td>
</c:if>
<c:if test="${empty album.email}">    
    <td>&nbsp;</td>
</c:if>    
</tr>
<tr><td>이미지</td><td>
<img src="upload/${album.image}">
</td></tr>
<tr><td>글제목</td><td>
${album.subject}
</td></tr>
<tr><td>내용</td><td>
${album.content}
</td></tr>
<tr><td colspan="2" align="center">
 <input type="button" value="수정하기" onClick="location.href='updateForm.do?num=${album.num}'">  
  <input type="button" value="삭제하기" onClick="location.href='deleteForm.do?num=${album.num}'">
  <input type="button" value="목록보기" onClick="location.href='list.do'">    
</td></tr>
</table>

</body>
</html>



                 deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String num = request.getParameter("num");
String image = request.getParameter("image");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>글삭제</title>
<link href="style.css" rel="stylesheet" type="text/css">

   <script type="text/javascript">
     <!--
       function begin(){
         document.myform.passwd.focus();
       }

       function checkIt(){
          if(!document.myform.passwd.value){
           alert("비밀번호를 입력하지 않으셨습니다.");
           document.myform.passwd.focus();
           return false;
         }
       return true;
       }   
     //-->
   </script>
</head>

<BODY onload="begin()">
<form name="myform" action="deletePro.do?num=<%=num %>" method="post" onSubmit="return checkIt()">
<table cellspacing=1 cellpadding=1 width="260" border=1 align="center" >
  <tr height="30">
    <td colspan="2" align="center">
      <font size="+1" ><b>글삭제</b></font></td></tr>
  
  <tr height="30">
    <td width="110" align=center>비밀번호</td>
    <td width="150" align=center>
      <input type=password name="passwd"  size="15" maxlength="12"></td></tr>
  <tr height="30">
    <td colspan="2" align="center">
      <input type=submit value="글삭제하기"> 
      <input type="button" value="취  소" onclick="location.href='list.do'"></TD></TR>
</TABLE>
</form>
</BODY>
</HTML>



                 deletePro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib    prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 삭제 되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">    
    <script type="text/javascript">
        alert("비밀번호가 맞지 않습니다.");
        history.go(-1);
    </script>
</c:if>



                 list.jsp

<%@ 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" %>
<!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 searchMessage(){
   if(document.search.keyWord.value==""){
     alert("검색어를 입력하세요");
     document.search.keyWord.focus();
     return false;
   }
   return true;
  }
</script>
</head>
<body>
<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>

<c:if test="${page.count > 0}">
<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>글제목</td>
    <td width="120">작성자</td>
    
    <td width="70">조회수</td>
    <td width="120">작성일 </td>
</tr>
<c:set var="number" value="${page.number}"/>
<c:forEach var="album" items="${albumList}">
<tr> 
    <td>${number}<c:set var="number" value="${number - 1}"/></td>
    <td>${album.num}</td>    
    <td><a href="content.do?num=${album.num}">${album.subject}</a></td>
    <td>${album.writer}</td>
     <td>${album.readcount}</td>
    <td><fmt:formatDate value="${album.reg_date}" pattern="yyyy년MM월dd일"/></td>
</tr>
</c:forEach>
</table>
</c:if>
 <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="subject">제목</option>      
          <option value="writer">이름</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>

   <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>



                 updateForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.dao.AlbumDao" %>   
<%@ page import ="com.domain.Album" %>   
<%
    int num = Integer.parseInt(request.getParameter("num"));
    AlbumDao manager = AlbumDao.getInstance();
    Album album = manager.getArticle(num);
    if(album.getEmail()==null){
        album.setEmail("");
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글수정</title>
<script type="text/javascript">
<!--
    function checkIt(){
        var user =document.userinput;
        
        if(!user.writer.value){
            alert("사용자 이름을 입력하세요");
            user.name.focus();
            return false;
        }
        if(!user.passwd.value){
            alert("비밀번호를 입력하세요");
            user.passwd.focus();
            return false;
        }
        if(!user.content.value){
            alert("내용을 입력하세요");
            user.content.focus();
            return false;
        }    
    }
//-->
</script>
</head>
<body>
<form action="updatePro.do" method="post" encType="multipart/form-data" name="userinput"  onSubmit="return checkIt()">  
<input type="hidden" name="num" value="<%=num%>">
<table width ="70%" border ="1" cellpadding="0" cellspacing="0" align="center">
<tr>
<td colspan="2" align="center"><h1>수정하기</h1></td>
</tr>
<tr>
<td>글번호</td>
<td><%=album.getNum() %></td>
</tr>
<tr>
    <td>이름</td>
    <td><input type="text" name="writer" value="<%=album.getWriter() %>" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" value="<%=album.getEmail() %>" size="30"></td>
</tr>
<tr>
    <td>제목</td>
    <td><input type="text" name="subject" value="<%=album.getSubject()%>" size="50"></td>
</tr>
<tr>
    <td>이미지교체</td>
    <input type="hidden" name="originImage" value="<%=album.getImage()%>">
    <td><img src="upload/<%=album.getImage()%>" width="50" height="50">
     <input type="file" size="8" name="image"></td>
</tr>
<tr>
    <td>내용</td>
    <td><textarea name="content" rows="5" cols="50"><%=album.getContent() %></textarea></td>
</tr>
    <tr>
    <td>암호</td>
    <td><input type="password" name ="passwd" size="10">
     암호와 동일해야 글이 수정됩니다.</td>
</tr>
<tr>
    <td colspan="2"  align="center">
  <input type="submit" value="수정하기" >  
  <input type="reset" value="다시작성">
  <input type="button" value="목록보기" onClick="location.href='list.do'">    
    </td>
</tr>
</table>    
</form>  
</body>
</html>



                 updatePro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib    prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 수정 되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">    
    <script type="text/javascript">
        alert("비밀번호가 맞지 않습니다.");
        history.go(-1);
    </script>
</c:if>



                 writeForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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(document.writeform.writer.value==""){
      alert("작성자를 입력하십시요.");
      document.writeform.writer.focus();
      return false;
    }
    if(document.writeform.subject.value==""){
      alert("제목을 입력하십시요.");
      document.writeform.subject.focus();
      return false;
    }
    
    if(document.writeform.content.value==""){
      alert("내용을 입력하십시요.");
      document.writeform.content.focus();
      return false;
    }
        
    if(document.writeform.passwd.value==""){
      alert(" 비밀번호를 입력하십시요.");
      document.writeform.passwd.focus();
      return false;
    }
    return true;
 }    
</script>
</head>
<body>
<center><b>글쓰기</b></center>
<br>
<form method="post" name="writeform" action="writePro.do" encType="multipart/form-data" onsubmit="return writeSave()">
<table width="400" border="1" cellspacing="0" cellpadding="0" align="center">
   <tr>
    <td  width="70" align="center">이 름</td>
    <td  width="330">
       <input type="text" size="10" maxlength="10" name="writer"></td>
  </tr>
  <tr>
    <td  width="70" align="center" >제 목</td>
    <td  width="330">
       <input type="text" size="40" maxlength="50" name="subject">
     </td>
  </tr>
  <tr>
    <td  width="70" align="center">Email</td>
    <td  width="330">
       <input type="text" size="40" maxlength="30" name="email" ></td>
  </tr>
  <tr>
    <td  width="70" align="center" >내 용</td>
    <td  width="330" >
     <textarea name="content" rows="13" cols="40"></textarea> </td>
  </tr>
  <tr>
    <td  width="70" align="center" >비밀번호</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" name="passwd"> 
     </td>
  </tr>
  <tr>
    <td  width="70" align="center" >이미지</td>
    <td  width="330" >
     <input type="file" size="8" name="image"> 
     </td>
  </tr>
<tr>      
 <td colspan=2 align="center"> 
  <input type="submit" value="글쓰기" >  
  <input type="reset" value="다시작성">
  <input type="button" value="목록보기" onClick="location.href='list.do'">
</td></tr></table>
</form>            
</body>
</html>



                 writePro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script type="text/javascript">
<!--
alert("앨범게시판에 글을 등록하였습니다.")
location.href="list.do";
//-->
</script>




            WEB-INF

                 lib (jar 5개  3개는 커넥션풀 3개 jstl 1개 업로드cos 1개)

                            commons-collections-3.1.jar

                            commons-dbcp-1.2.1.jar

                            commons-pool-1.2.jar

                            cos.jar

                            jstl-1.2.jar


                 commandMap.properties

/writeForm.do=com.action.WriteFormAction
/writePro.do=com.action.WriteProAction
/updateForm.do=com.action.UpdateFormAction
/updatePro.do=com.action.UpdateProAction
/deleteForm.do=com.action.DeleteFormAction
/deletePro.do=com.action.DeleteProAction
/list.do=com.action.ListAction
/content.do=com.action.ContentAction



                 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <display-name>member</display-name>
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>com.controller.Controller</servlet-class>
     <init-param>
         <param-name>configFile</param-name>
         <param-value>/WEB-INF/commandMap.properties</param-value>
     </init-param>
 </servlet>   
 
 <servlet-mapping>
     <servlet-name>Controller</servlet-name>
     <url-pattern>*.do</url-pattern>
 </servlet-mapping> 
 <!-- Controller end -->
   
  <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>











create table guestbook(
num number primary key,
register date NOT NULL,
name varchar2(20) NOT NULL,
email varchar2(40),
passwd varchar2(10) NOT NULL,
content varchar2(4000) NOT NULL);

create sequence guestbook_seq;




글번호 num


insert into GUESTBOOK (num,register,name,email,passwd,content) values(guestbook_seq.nextval,?,?,?,?,?)


오라클 sequence guestbook_seq.curval 현재번호

          sequence guestbook_seq.nextval 다음번호


테이블작성






select * from(
       //시스템에서 제공하는 행번호 rownum의 별칭 rnum : 명시적 행번호 호출
       //a.* =  num,register,name,email,.... a아래있는 모든 컬럼이다. (a: 테이블에 대한 별칭)
select a.*, rownum rnum 
from(
//서브쿼리
select * 
from GUESTBOOK
order by num desc
)a//테이블 별칭
) where rnum >=1 and rnum <=10  //행번호 1~10 까지






M: Model : 자바클래스, 데이터 처리

V: View : JSP, 화면 디스클레이

C: Controller : servlet, 요청을 받아서 모델과 뷰를 호출하는 역활







Java Resources

        src

            com.guestbook.action

                 DeleteAction

package com.guestbook.action;

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

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;

public class DeleteAction  implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1.전송된 num,비밀번호 추출
        int num = Integer.parseInt(request.getParameter("num"));
        String passwd = request.getParameter("passwd");
        
        //2. GuestbookDao의 uesrCheck에 num, 비밀번호 전달
        GuestbookDao manager = GuestbookDao.getInstance();
        int check = manager.userCheck(num, passwd);
        
        //3. check가 1인 경우 delete 메서드 호출
        if(check == 1){
            manager.delete(num);
        }
        //4. check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/delete.jsp";
    }
}



                 DeleteFormAction

package com.guestbook.action;

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

import com.guestbook.controller.Action;

public class DeleteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        return "/view2/deleteForm.jsp";
    }
}



                 ListAction

package com.guestbook.action;

import java.util.List;

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

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;
import com.guestbook.domain.GuestbookPage;

public class ListAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //한페이지 글의수
        int pageSize = 10;
        
        String pageNum =request.getParameter("pageNum");
        if(pageNum ==null){
            pageNum = "1";
        }
        
        int currentPage = Integer.parseInt(pageNum);
        int startRow =(currentPage-1)*pageSize +1;
        int endRow =currentPage * pageSize;
        int count = 0;
        
        List<Guestbook> bookList =null;
        GuestbookDao manager = GuestbookDao.getInstance();
        count =manager.getCount();
        
        if(count>0){
            bookList = manager.getList(startRow, endRow);
        }

        //GuestbookPage : 자바빈 하나더 만들기
        //Guestbook 자바빈에 다 넣을수도있다, 그러나 분류를위해 나눠쓴것
        //작업자가 효율적으로 분류해서 쓰도록한다.
        GuestbookPage page= new GuestbookPage();
        page.setCount(count);
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        
        
        request.setAttribute("page", page);
        request.setAttribute("bookList", bookList);

        return "/view2/list.jsp";
    }
}



                 UpdateAction

package com.guestbook.action;

import java.sql.Timestamp;

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

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class UpdateAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1.인코딩처리
        request.setCharacterEncoding("utf-8");            

        //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장
        Guestbook book =new Guestbook();
        book.setNum(Integer.parseInt(request.getParameter("num")));
        book.setName(request.getParameter("name"));
        book.setEmail(request.getParameter("email"));   
        book.setPasswd(request.getParameter("passwd"));
        book.setContent(request.getParameter("content"));
        
        //3.GuestbookDao의 userCheck 메소드에 num과 비밀번호 전달인증
        GuestbookDao manager = GuestbookDao.getInstance();
        int check = manager.userCheck(book.getNum(),book.getPasswd());
        
        //4.check가 1인 경우 GuestbookDao의 update 메소드에 자바빈 전달                
        if(check==1){
        manager.update(book);        
        }
        //5.check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/update.jsp;";
    }
}



                 UpdateFormAction

package com.guestbook.action;

import java.sql.Timestamp;

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

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class UpdateFormAction  implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1. 전송된 글번호(num)를 request에서 추출
        int num = Integer.parseInt(request.getParameter("num"));
        
        
        //2. GuestbookDao의 getGuestbook 메소드에 num를 전달
        GuestbookDao manager = GuestbookDao.getInstance();
        Guestbook book = manager.getGuestBook(num);        
        
        //3. 자바빈을 reqeust에 저장
        request.setAttribute("book", book);
        
        return "/view2/updateForm.jsp";
    }
}



                 WriteAction

package com.guestbook.action;

import java.sql.Timestamp;

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

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class WriteAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        //1.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장
        Guestbook guestbook =new Guestbook();
        guestbook.setRegister(new Timestamp(System.currentTimeMillis()));
        guestbook.setName(request.getParameter("name"));
        guestbook.setEmail(request.getParameter("email"));   
        guestbook.setPasswd(request.getParameter("passwd"));
        guestbook.setContent(request.getParameter("content"));
        
        //3.GuestbookDao의 insert 메소드에 자바빈 전달                
        GuestbookDao manager = GuestbookDao.getInstance();
        manager.insert(guestbook);        
        
        return "/view2/write.jsp";
    }
}



                 WriteFormAction

package com.guestbook.action;

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

import com.guestbook.controller.Action;

public class WriteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        return "view2/writeForm.jsp";
    }
}



        com.guestbook.controller

                 Action

package com.guestbook.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
    public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable;
}

   


                 Controller

package com.guestbook.controller;

import java.io.FileInputStream;
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.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
           
public class Controller extends HttpServlet {
      
    private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장

    //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
    //명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            String configFilePath = config.getServletContext().getRealPath(
                      configFile);
            fis = new FileInputStream(configFilePath);
            prop.load(fis);
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ex) {
                }
        }
        Iterator keyIter = prop.keySet().iterator();
        while (keyIter.hasNext()) {
            String command = (String) keyIter.next();
            String handlerClassName = prop.getProperty(command);
            try {
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandMap.put(command, handlerInstance);
            } catch (ClassNotFoundException e) {
                throw new ServletException(e);
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
        }
    }

    public void doGet(//get방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    protected void doPost(//post방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    //시용자의 요청을 분석해서 해당 작업을 처리
    private void requestPro(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        String view = null;
        Action com=null;
        
        try {
            String command = request.getRequestURI();
            if (command.indexOf(request.getContextPath()) == 0) {
               command = command.substring(request.getContextPath().length());
            }
            com = (Action)commandMap.get(command); 
            view = com.execute(request, response);
        } catch(Throwable e) {
            throw new ServletException(e);
        }   
        RequestDispatcher dispatcher =request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}



        com.guestbook.dao

                 GuestbookDao

package com.guestbook.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
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.guestbook.domain.Guestbook;

public class GuestbookDao {
    private static GuestbookDao instance =new GuestbookDao();
    
    public static GuestbookDao getInstance(){
        return instance;
    }
    private GuestbookDao(){}
    
    private Connection getConnection() throws Exception{
        Context initCtx= new InitialContext();
        Context envCtx=(Context)initCtx.lookup("java:comp/env");
        DataSource ds=(DataSource)envCtx.lookup("jdbc/orcl");
        
        return ds.getConnection();
    }
    
    //글저장
    public void insert(Guestbook book) throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        //바인드문자 ?의 순서
        int cnt = 0;        
        
        try{
            conn= getConnection();
            sql = "insert into GUESTBOOK (num,register,name,email,passwd,content) " +
                    "values(guestbook_seq.nextval,?,?,?,?,?)";
            //sql ="insert into GUESTBOOK values(guestbook_seq.nextval,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(++cnt, book.getRegister());
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getPasswd());
            pstmt.setString(++cnt, book.getContent());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //글의 총갯수
    public int getCount() throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        int count =0;
        String sql =null;
        
        try{
            conn=getConnection();
            // 갯수를 구하는 sql 함수 count(*) :레코드의 총수는
            sql="select count(*) from GUESTBOOK";
            pstmt =conn.prepareStatement(sql);
            rs =pstmt.executeQuery();
            if (rs.next()){
                //1: 컬럼의 순서 (가상의 컬럼 count(*))
                //getInt(count(*))도 가능
                count =rs.getInt(1);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }            
        return count;
    }
    
    //글 목록 
    public List<Guestbook> getList(int startRow, int endRow)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List<Guestbook>list =null;
        String sql="";
        
        try{
            conn =getConnection();
            //새글이 위로 올라오게 내림차순
            //sql ="select * from GUESTBOOK order by num desc";
            // select(select 서브쿼리)
            sql ="select * from(select a.*, rownum rnum from(select * from GUESTBOOK order by num desc)a) where rnum >=? and rnum <=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            
            //sql문 반영
            rs=pstmt.executeQuery();
            
            //데이터가 있는가없는가 확인
            if(rs.next()){
                //있으면
                list= new ArrayList<Guestbook>();
                //if문에서 이미 커서가 첫번째 행을 가리키기 때문에 첫번째 행 부터 뽑기위해 do while 문
                do{
                    Guestbook book =new Guestbook();
                    book.setNum(rs.getInt("num"));
                    book.setRegister(rs.getTimestamp("register"));
                    book.setName(rs.getString("name"));
                    book.setEmail(rs.getString("email"));
                    book.setPasswd(rs.getString("passwd"));
                    book.setContent(rs.getString("content"));
                    list.add(book);
                }while(rs.next());
            }else{
                //없으면
                //데이터가 없는 경우 비어있는 List 생성
                list = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return list;
    }
    
    //수정 폼에 보여질 한건의 레코드 정보
    public Guestbook getGuestBook(int num)throws Exception{
        Connection conn =null;
        PreparedStatement  pstmt= null;
        ResultSet rs = null;
        Guestbook book=null;
        String sql=null;
        
        try{
            conn=getConnection();
            sql ="select * from GUESTBOOK where num = ? ";
            
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                book=new Guestbook();
                book.setNum(rs.getInt("num"));
                book.setRegister(rs.getTimestamp("register"));
                book.setName(rs.getString("name"));
                book.setEmail(rs.getString("email"));
                book.setPasswd(rs.getString("passwd"));
                book.setContent(rs.getString("content"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return book;
    }
    
    //인증
    public int userCheck(int num, String passwd)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        String dbpasswd="";
        String sql="";
        int x=-1;
        try{
            
            conn= getConnection();
            sql="select passwd from GUESTBOOK where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd)){
                    x=1;//인증성공
                }else
                    x=0;//비밀전호 틀림
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return x;
    }
    
    //글수정
    public void update(Guestbook book)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        int cnt =0;
        String sql = null;
        
        try{
            conn =getConnection();
            sql = "update GUESTBOOK set name=?,email=?, content=? where num=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getContent());    
            pstmt.setInt(++cnt, book.getNum());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
    }
    
    //글삭제
    public void delete(int num)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        String sql=null;        
        
        try{            
            conn= getConnection();
            
            sql="delete from GUESTBOOK where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();

        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
        return ;
    }    
    
    //자원정리
    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){}
    }    
}



        com.guestbook.domain

                 Guestbook

package com.guestbook.domain;

import java.sql.Timestamp;

public class Guestbook {
    
    private int num;
    private Timestamp register;
    private String name;
    private String email;
    private String passwd;
    private String content;
    
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public Timestamp getRegister() {
        return register;
    }
    public void setRegister(Timestamp register) {
        this.register = register;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}



                 GuestbookPage

package com.guestbook.domain;

public class GuestbookPage {

    private int count;
    private int pageSize;
    private int currentPage;
    
    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;
    }    
}



META-INF

        context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!--
maxActive="20" //최대 커넥션 수
maxIdle="10"   //미리 만들어둘 기본커낵션 수
-->
    <Resource name="jdbc/orcl"
              auth="container"
              type="javax.sql.DataSource"
              username="hr"
              password="hr"
              driverClassName="oracle.jdbc.driver.OracleDriver"
              factory="org.apache.commons.dbcp.BasicDataSourceFactory"
              url="jdbc:oracle:thin:@localhost:1521:orcl"
              maxActive="20"
              maxIdle="10" />
</Context>



WebContent

        view2

            delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib    prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 삭제 되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">    
    <script type="text/javascript">
        alert("비밀번호가 맞지 않습니다.");
        history.go(-1);
    </script>
</c:if>



            deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>글삭제</title></head>
<body>
<form action="delete.do" method="post">
<input type="hidden" name="num" value="${param.num }">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"><br>
    글을 쓸때 입력한 암호와 동일해야 글이 삭제됩니다.</td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글삭제하기"></td>
</tr>
</table>
</form>
</body>
</html>



            list.jsp

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>글목록</title></head>
<body>
<table width="100%" align="center">
<tr>
    <td>
    <a href="writeForm.do">글쓰기</a>
    </td>
</table>
<c:if test="${page.count == 0}">
<table width="100%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr>
    <td bgcolor="#e9e9e9">
    방명록에 저장된 글이 없습니다.
    </td>
</table>
</c:if>
<c:if test="${page.count > 0}">
<table width="100%" border="1" cellpadding="0" cellspacing="0" align="center">
<!--
bookList를 받아 반복문 
EL 함수(잘안씀 교제 P523)외에는 프로퍼티형식
\$ 는 주석에서도 \로 무력화 시켜야한다.
\${book.email} O  \${book,getEmial()} X옳지않다.
\${book.name} O  \${book,getName()} X옳지않다.
표기법은 변수명이지만 사실상 getter메소드를 통해 출력받는다.
-->
<c:forEach var="book" items="${bookList}">
<tr>
    <td bgcolor="#e9e9e9">
    <b>${book.name}(${(book.email == null) ? "" : book.email})</b>
    - <font size="2">
    <fmt:formatDate value="${book.register}" pattern="yyyy년MM월dd일"/>
    <a href="updateForm.do?num=${book.num}">[수정]</a>
    <a href="deleteForm.do?num=${book.num}">[삭제]</a>
    </font>
    </td>
</tr>
<tr>
    <td>${book.content }</td>
</tr>
</c:forEach>
</table>
</c:if>
<div align="center">
<c:if test="${page.count > 0}">
    <!--
    1.페이지블록지정  EL로 감싸 넘김 ${10} Integer로 인정
    re: 
    value="${(page.currentPage - 1) / pageBlock}" integerOnly="true" :실수가 나와도 정수로만표현 
    -->
   <c:set var="pageBlock" value="${10}"/>
   <c:set var="pageCount" value="${(page.count - 1) / page.pageSize + 1}"/>
   <fmt:parseNumber var="rs" value="${(page.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 }">[이전]</a>
   </c:if>

   <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}">[${i}]</a>
       </c:if>
   </c:forEach>

   <c:if test="${endPage < pageCount}">
        <a href="list.do?pageNum=${startPage + pageBlock}">[다음]</a>
   </c:if>
</c:if>
</div>
</body>
</html>



            update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib    prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 수정되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">    
    <script type="text/javascript">
        alert("비밀번호가 맞지 않습니다.");
        history.go(-1);
    </script>
</c:if>


 

            updateForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 checkIt() {
        var user = document.userinput;
               
        if(!user.name.value) {
            alert("사용자 이름을 입력하세요");
            user.name.focus();
            return false;
        }
        if(!user.passwd.value ) {
            alert("비밀번호를 입력하세요");
            user.passwd.focus();
            return false;
        }
        if(!user.content.value ) {
            alert("내용을 입력하세요");
            user.content.focus();
            return false;
        }
    }
//-->
</script>
</head>
<body>
<form action="update.do" method="post">
<!-- 
get방식으로 넘어온 num을 EL을 통해서 뽑아낸다. value="${param.num}"
-->
<input type="hidden" name="num" value="${param.num}">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"><br>
    글을 쓸때 입력한 암호와 동일해야 글이 수정됩니다.</td>
</tr>
<tr>
    <td>이름</td>
    <td><input type="text" name="name" 
               value="${book.name}" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" 
               value="${book.email}" size="30"></td>
</tr>
<tr>
    <td>내용</td>
    <td>
    <textarea name="content" rows="5" 
       cols="50">${book.content}</textarea>
    </td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글수정하기"></td>
</tr>

</table>
</form>
</body>
</html>



            write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<script type="text/javaScript">
alert("방명록에 글을 등록하였습니다.");
location.href="list.do";
</script>


  

            writeForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 checkIt() {
        var user = document.userinput;
               
        if(!user.name.value) {
            alert("사용자 이름을 입력하세요");
            user.name.focus();
            return false;
        }
        if(!user.passwd.value ) {
            alert("비밀번호를 입력하세요");
            user.passwd.focus();
            return false;
        }
        if(!user.content.value ) {
            alert("내용을 입력하세요");
            user.content.focus();
            return false;
        }
       
    }
//-->
</script>
</head>
<body>
<form name="userinput" action="write.do" method="post" onsubmit="return checkIt()">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>이름</td>
    <td><input type="text" name="name" size="10"></td>
</tr>
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" size="30"></td>
</tr>
<tr>
    <td>내용</td>
    <td><textarea name="content" rows="5" cols="50"></textarea></td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글남기기"></td>
</tr>
</table>
</form>
</body>
</html>



        WEB-INF

            lib

                 commons-collections-3.1.jar

                 commons-dbcp-1.2.1.jar

                 commons-pool-1.2.jar

                 jstl-1.2.jar


            commandMap.properties

/writeForm.do=com.guestbook.action.WriteFormAction
/write.do=com.guestbook.action.WriteAction
/list.do=com.guestbook.action.ListAction
/updateForm.do=com.guestbook.action.UpdateFormAction
/update.do=com.guestbook.action.UpdateAction
/deleteForm.do=com.guestbook.action.DeleteFormAction
/delete.do=com.guestbook.action.DeleteAction



            web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <display-name>guestbook</display-name>
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>com.guestbook.controller.Controller</servlet-class>
     <init-param>
         <param-name>configFile</param-name>
         <param-value>/WEB-INF/commandMap.properties</param-value>
     </init-param>
 </servlet>   
 
 <servlet-mapping>
     <servlet-name>Controller</servlet-name>
     <url-pattern>*.do</url-pattern>
 </servlet-mapping> 
 <!-- Controller end -->
   
  <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>






글등록 테스트  WriteFormAction -> writeForm.jsp -> WriteAction -> write.jsp









글목록 테스트  ListAction -> list.jsp




수정테스트 UpdateFormAction -> updateForm.jsp -> UpdateAction -> update.jsp -> list.do











삭제테스트 :  DeleteFormAction  -> deleteForm.jsp -> DeleteAction -> delete.jsp -> list.do







//Struts2 : MVC모델제공 => FrameWork


모델1, 모델2  DAO 나 자바빈은 변하지않아 재활용가능


예제. MEMBER (회원관리)

회원가입,아이디중복확인,로그인,정보수정,회원탈퇴(회원삭제)


member.war



Java Resources

        src

            com.action

                 ConfirmIdAction

package com.action;

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

import com.controller.Action;
import com.dao.MemberDao;

public class ConfirmIdAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        String id =request.getParameter("id");
        MemberDao manager = MemberDao.getInstance();
        int check=manager.confirmId(id);
        
        request.setAttribute("check", new Integer(check));
        request.setAttribute("id", id);
        
        return "/view2/confirmId.jsp";
    }
}



                 DeleteFormAction

package com.action;

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

import com.controller.Action;

public class DeleteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        HttpSession session = request.getSession();
        if(session.getAttribute("memId") == null)
            return "/view2/loginForm.jsp";
            
        return "/view2/deleteForm.jsp";
    }
}



                 DeleteProAction

package com.action;

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

import com.controller.Action;
import com.dao.MemberDao;

public class DeleteProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
        
        //1. 로그인 여부 체크
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view2/loginForm.jsp";
        
        //2. session에서 id를 추출해고 전송받은 비밀번호를
        
        String id =(String)session.getAttribute("memId");
        String passwd = request.getParameter("passwd");
                
        //     memberDao의 userCheck 에 전달
        MemberDao manager = MemberDao.getInstance();
        int check = manager.userCheck(id, passwd);
        
        //3. check 1인 경우 deleteMember 메소드에 id 전달
        if(check== 1){
            manager.deleteMember(id);
            session.invalidate();
        }           
        
        //4. check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/deletePro.jsp";
    }
}


                InputFormAction

package com.action;

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

import com.controller.Action;

public class InputFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        return "/view2/inputForm.jsp";
    }  
}



                 InputProAction

package com.action;

import java.sql.Timestamp;

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

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class InputProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //2.request에서 전송된 데이터를 추출        
        //3.자바빈에 데이터 셋팅        
        Member member =new Member();
        member.setId(request.getParameter("id"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setJumin1(request.getParameter("jumin1"));
        member.setJumin2(request.getParameter("jumin2"));
        member.setEmail(request.getParameter("email"));
        member.setBlog(request.getParameter("blog"));       
        member.setReg_date(new Timestamp(System.currentTimeMillis()));
        
        //4.MemberDao의 insertMember 메소드 호출
        MemberDao manager = MemberDao.getInstance();
        manager.insertMember(member);
        
        return "/view2/inputPro.jsp";
    }
}


                 LoginAction

package com.action;

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

import com.controller.Action;

public class LoginAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return "/view2/loginForm.jsp";

        return "/view2/login.jsp";
    }    
}


                 LoginFormAction

package com.action;

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

import com.controller.Action;

public class LoginFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        return "/view2/loginForm.jsp";
    }  
}



                 LoginProAction

package com.action;

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

import com.controller.Action;
import com.dao.MemberDao;

public class LoginProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        String id =request.getParameter("id");
        String passwd =request.getParameter("passwd");
        
        MemberDao manager = MemberDao.getInstance();
        int check= manager.userCheck(id, passwd);        
        
        if(check==1){
            HttpSession session=request.getSession();
            session.setAttribute("memId", id);
        }
        
        request.setAttribute("check", new Integer(check));
        
        return "/view2/loginPro.jsp";
    }
}



                 LogoutAction

package com.action;

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

import com.controller.Action;

public class LogoutAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        HttpSession session =request.getSession();
        session.invalidate();
        
        return "view2/logout.jsp";
    }
}



                 ModifyFormAction

package com.action;

import java.sql.Timestamp;

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

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class ModifyFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1. 로그인 여부 조사
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view/loginForm.jsp";

        //2.session에 저장된 id 호출        
        String id = (String)session.getAttribute("memId");  
            
        //3.MemberDao의 getMember 메서드에 id 전달
        MemberDao manager = MemberDao.getInstance();
        Member member = manager.getMember(id);        
        
        //4.반환받은  Member를 request에 저장
        request.setAttribute("member", member);
        
        return "/view2/modifyForm.jsp";
    }
}



                 ModifyProAction

package com.action;

import java.sql.Timestamp;

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

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class ModifyProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1.로그인 여부 조사
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view/loginForm.jsp";
        
        //2.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //3.자바빈을 생성하고 자바빈에 전송된 데이터를 저장
        Member member =new Member();
        member.setId((String)session.getAttribute("memId"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setJumin1(request.getParameter("jumin1"));
        member.setJumin2(request.getParameter("jumin2"));
        member.setEmail(request.getParameter("email"));
        member.setBlog(request.getParameter("blog"));  
        member.setReg_date(new Timestamp(System.currentTimeMillis()));
        
        //4.MemberDao의 updateMember 메소드에 자바빈 전달
        MemberDao manager = MemberDao.getInstance();
        manager.updateMember(member);
        
        return "/view2/modifyPro.jsp";
    }
}



        com.controller

                 Action

package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
    public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable;
}



                 Controller

package com.controller;

import java.io.FileInputStream;
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.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
           
public class Controller extends HttpServlet {
      
    private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장

    //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
    //명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            String configFilePath = config.getServletContext().getRealPath(
                      configFile);
            fis = new FileInputStream(configFilePath);
            prop.load(fis);
        } catch (IOException e) {
            throw new ServletException(e);ㅠ
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ex) {
                }
        }
        Iterator keyIter = prop.keySet().iterator();
        while (keyIter.hasNext()) {
            String command = (String) keyIter.next();
            String handlerClassName = prop.getProperty(command);
            try {
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandMap.put(command, handlerInstance);
            } catch (ClassNotFoundException e) {
                throw new ServletException(e);
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
        }
    }

    public void doGet(//get방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    protected void doPost(//post방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    //시용자의 요청을 분석해서 해당 작업을 처리
    private void requestPro(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        String view = null;
        Action com=null;
        
        try {
            String command = request.getRequestURI();
            if (command.indexOf(request.getContextPath()) == 0) {
               command = command.substring(request.getContextPath().length());
            }
            com = (Action)commandMap.get(command); 
            view = com.execute(request, response);
        } catch(Throwable e) {
            throw new ServletException(e);
        }   
        RequestDispatcher dispatcher =request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}



        com.dao

                 MemberDao

package com.dao;

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

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

import com.domain.Member;

public class MemberDao {
    
        
/*    @싱글턴 패턴
    생성자의 접근지정자는 private으로 지정
    static한 getInstance()를  메소드를 사용
    객체의 주소를 보관하는 static 참조변수 사용 
      //참조변수 instance에 객체 주소할당
      //객체를 한번생성해서 계속가지고있슴 (변경에관한게 아무것도없슴)
    객체를 하나만 생성해서 공유하고자 싱글턴 패턴 구현
    @멤버변수가 있는 경우에는 절대로 싱글턴 패턴을 구현하면 안된다.
      //멤버변수를 공유시켜버리면 여러사용자가 멤버변수를 같이 변경하게됨    */
    private static MemberDao instance =new MemberDao();
    
    public static MemberDao getInstance(){
        return instance;
    }

    //생성자 인데 private 외부에서는 생성못하게 막아둔거
    //메소드를 static 하게만들어  메서드를  이용해서 
    //Member.getInstance();
    private MemberDao(){
    }
    
    //커네션풀로 부터 커넥션을 할당 받는 메소드
    private Connection getConnection() throws Exception{
        Context initCtx= new InitialContext();
        Context envCtx=(Context)initCtx.lookup("java:comp/env");
        DataSource ds=(DataSource)envCtx.lookup("jdbc/orcl");
        
        return ds.getConnection();
    }
    
    //회원가입
    public void insertMember(Member member)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        int cnt = 0;
        
        try{
            //커넥션 풀로 부터 커넥션 할당
            conn= getConnection();
            sql ="insert into MEMBER values(?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getId());
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getJumin1());
            pstmt.setString(++cnt, member.getJumin2());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setTimestamp(++cnt, member.getReg_date());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 아이디 , 비밀번호 체크
    public int userCheck(String id, String passwd)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        String sql="";
        String dbpasswd="";
        int x = -1;
        
        try{
            conn =getConnection();
            sql ="select passwd from MEMBER where id = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd))
                    x=1; //인증성공
                else
                    x=0; //비밀번호 틀림
            }else
                x=-1; //해당 아이디 없음
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return x;
    }
    
    //회원 상세정보 
    public Member getMember(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Member member=null;
        String sql="";
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                member=new Member();
                member.setId(rs.getString("id"));
                member.setPasswd(rs.getString("passwd"));
                member.setName(rs.getString("name"));
                member.setJumin1(rs.getString("jumin1"));
                member.setJumin2(rs.getString("jumin2"));
                member.setEmail(rs.getString("email"));
                member.setBlog(rs.getString("blog"));
                member.setReg_date(rs.getTimestamp("reg_date"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return member;
    }
    
    //회원정보 수정
    public void updateMember(Member member)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        int cnt =0;
        try{
            conn =getConnection();
            sql = "update MEMBER set passwd=?,name=?,email=?, blog=? where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setString(++cnt, member.getId());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }   
    
    //회원탈퇴 , 회원정보 삭제
    public void deleteMember(String id)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        try{
            conn =getConnection();
            sql = "delete from MEMBER where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //ID 중복 체크
    public int confirmId(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql="";
        int x=-1;
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();    
            
            if(rs.next())
                x=1; //해당아이디 있음
            else
                x=-1;//해당아이디 없음
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        
        return x;
    }
    
    //자원 정리를 위한 메소드
    //계란노른자
    //Connection 를통해서 PreparedStatement 를생성하고 
    //PreparedStatement 를 통해서 ResultSet 를 생성하기때문에
    //종료할때는 ResultSet=>PreparedStatement=>Connection 와같이 생성순서의 역순으로 close 해줘야한다
    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){}
    }
}


        com.doamin

                 Member

package com.domain;
import java.sql.Timestamp;

//자바빈
public class Member {
    //프로퍼티
    private String id;
    private String passwd;
    private String name;
    private String jumin1;
    private String jumin2;
    private String email;
    private String blog;
    private Timestamp reg_date;
    
    //getter
    public String getId() {
        return id;
    }
    //setter
    public void setId(String id) {
        this.id = id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJumin1() {
        return jumin1;
    }
    public void setJumin1(String jumin1) {
        this.jumin1 = jumin1;
    }
    public String getJumin2() {
        return jumin2;
    }
    public void setJumin2(String jumin2) {
        this.jumin2 = jumin2;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getBlog() {
        return blog;
    }
    public void setBlog(String blog) {
        this.blog = blog;
    }
    public Timestamp getReg_date() {
        return reg_date;
    }
    public void setReg_date(Timestamp reg_date) {
        this.reg_date = reg_date;
    }
    
    @Override
    public String toString() {
        return "Member [id=" + id + ", passwd=" + passwd + ", name=" + name
                + ", jumin1=" + jumin1 + ", jumin2=" + jumin2 + ", email="
                + email + ", blog=" + blog + ", reg_date=" + reg_date + "]";
    }    
}




WebContent

        view2

            confirmId.jsp

<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>ID 중복확인</title>
<script type="text/javascript">
<!--
  function setid()
    {        
        opener.document.userinput.id.value="${id}";
        self.close();
    }
        //-->
</script>
</head>
<body>
<c:if test="${check == 1}">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <td height="39" >${id }이미 사용중인 아이디입니다.</td>
  </tr>
</table>
<form name="checkForm" method="post" action="confirmId.do">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <td align="center"> 
       다른 아이디를 선택하세요.<p>
       <input type="text" size="10" maxlength="12" name="id"> 
       <input type="submit" value="ID중복확인">
    </td>
  </tr>
</table>
</form>
</c:if>
<c:if test="${check != 1}">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr> 
    <td align="center"> 
      <p>입력하신 ${id} 는 사용하실 수 있는 ID입니다. </p>
      <input type="button" value="닫기" onclick="setid()">
    </td>
  </tr>
</table>
</c:if>
</body>
</html>



            deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>회원탈퇴</title>
<link href="style.css" rel="stylesheet" type="text/css">

   <script type="text/javascript">
     <!--
       function begin(){
         document.myform.passwd.focus();
       }

       function checkIt(){
          if(!document.myform.passwd.value){
           alert("비밀번호를 입력하지 않으셨습니다.");
           document.myform.passwd.focus();
           return false;
         }
       return true;
       }   
     //-->
   </script>
</head>

<BODY onload="begin()">
<form name="myform" action="deletePro.do" method="post" onSubmit="return checkIt()">
<table cellspacing=1 cellpadding=1 width="260" border=1 align="center" >
  
  <tr height="30">
    <td colspan="2" align="center">
      <font size="+1" ><b>회원 탈퇴</b></font></td></tr>
  
  <tr height="30">
    <td width="110" align=center>비밀번호</td>
    <td width="150" align=center>
      <input type=password name="passwd"  size="15" maxlength="12"></td></tr>
  <tr height="30">
    <td colspan="2" align="center">
      <input type=submit value="회원탈퇴"> 
      <input type="button" value="취  소" onclick="location.href='login.do'"></TD></TR>
</TABLE>
</form>
</BODY>
</HTML>



            deletePro.jsp

<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>회원탈퇴</title>
</head>
<body>
<c:if test="${check == 1}">
회원정보가 삭제되었습니다.
<input type="button" value="확인" onclick="location.href='loginForm.do'">
</c:if>
<c:if test="${check != 1}">
    <script>
        alert("비밀번호가 맞지 않습니다.");
        history(-1);
    </script>
</c:if>
</body>
</html>



            inputForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 checkIt() {
        var userinput = document.userinput;
        if(!userinput.id.value) {
            alert("ID를 입력하세요");
            userinput.id.focus();
            return false;
        }
        if(!userinput.passwd.value ) {
            alert("비밀번호를 입력하세요");
            userinput.passwd.focus();
            return false;
        }
        if(userinput.passwd.value != userinput.passwd2.value){
            alert("비밀번호를 동일하게 입력하세요");
            userinput.passwd2.focus();
            return false;
        }
        if(!userinput.name.value) {
            alert("사용자 이름을 입력하세요");
            userinput.name.focus();
            return false;
        }
        if(!userinput.jumin1.value)
        {
            alert("주민등록번호를 입력하세요");
            userinput.jumin1.focus();
            return false;
        }
        if(!userinput.jumin2.value)
        {
            alert("주민등록번호를 입력하세요");
            userinput.jumin2.focus();
            return false;
        }
    }

    // 아이디 중복 여부를 판단
    function openConfirmid(userinput) {
        // 아이디를 입력했는지 검사
        if (userinput.id.value == "") {
            alert("아이디를 입력하세요");
            return;
        }
        // url과 사용자 입력 id를 조합합니다.
        url = "confirmId.do?id=" + userinput.id.value ;
        
        // 새로운 윈도우를 엽니다.
        open(url, "confirm", 
        "toolbar=no, location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=300, height=200");
    }
    //주민번호 6자리 입력 후 자동으로 다음 칸으로 이동
    function nextField(userinput,checklength){
            if( userinput.jumin1.value.length  >= checklength ) {
            userinput.jumin2.focus();
        }
        return true;
    }
</script>
</head>
<body>
<form method="post" action="inputPro.do" name="userinput" onSubmit="return checkIt()">
  <table width="600" border="1" cellspacing="0" cellpadding="3" align="center" >
    <tr> 
    <td colspan="2" height="39" align="center">
       <font size="+1" ><b>회원가입</b></font></td>
    </tr>
    <tr> 
      <td width="200"><b>아이디 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td width="200"> 사용자 ID</td>
      <td width="400"> 
        <input type="text" name="id" size="10" maxlength="12">
        <input type="button" name="confirm_id" value="ID중복확인" OnClick="openConfirmid(this.form)">
      </td>
    </tr>
    <tr> 
      <td width="200"> 비밀번호</td>
      <td width="400" > 
        <input type="password" name="passwd" size="15" maxlength="12">
      </td>
    </tr>  
    <tr>  
      <td width="200">비밀번호 확인</td>
      <td width="400"> 
        <input type="password" name="passwd2" size="15" maxlength="12">
      </td>
    </tr>
    <tr> 
      <td width="200"><b>개인정보 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td width="200">사용자 이름</td>
      <td width="400"> 
        <input type="text" name="name" size="15" maxlength="10">
      </td>
    </tr>
    <tr> 
      <td width="200">주민등록번호</td>
      <td width="400"> 
        <input type="text" name="jumin1" onKeyUp="nextField(this.form,6);"  size="7" maxlength="6">
        -<input type="text" name="jumin2" size="7" maxlength="7">
      </td>
    </tr>
    <tr> 
      <td width="200">E-Mail</td>
      <td width="400"> 
        <input type="text" name="email" size="40" maxlength="30">
      </td>
    </tr>
    <tr> 
      <td width="200"> Blog</td>
      <td width="400"> 
        <input type="text" name="blog" size="60" maxlength="50">
      </td>
    </tr>
    <tr> 
      <td colspan="2" align="center"> 
          <input type="submit" name="confirm" value="등   록" >
          <input type="reset" name="reset" value="다시입력">
          <input type="button" value="가입안함" onclick="javascript:window.location='login.do'">
      </td>
    </tr>
  </table>
</form>
</body>
</html>


 

           inputPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
alert("축하! 축하!");
location.href="login.do"
</script>



            login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> 
<head><title>메인입니다..</title>
</head>
<body>
   <table width=500 cellpadding="0" cellspacing="0"  align="center" border="1" >
         <tr>
           <td width="300" height="20">하하하</td>

           <td rowspan="3" align="center">
             ${sessionScope.memId}님이 <br>
             방문하셨습니다
             <form  method="post" action="logout.do">  
             <input type="submit"  value="로그아웃">
              <input type="button" value="회원정보변경" onclick="javascript:window.location='modifyForm.do'">
             <input type="button" value="회원탈퇴" onclick="javascript:window.location='deleteForm.do'">
             </form>
         </td>
        </tr> 
       <tr> 
         <td rowspan="2" width="300" >메인입니다.</td>
      </tr>
     </table>
     <br>
</body>
</html>



            loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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 begin(){
         document.myform.id.focus();
       }
       function checkIt(){
         if(!document.myform.id.value){
           alert("이름을 입력하지 않으셨습니다.");
           document.myform.id.focus();
           return false;
         }  
         if(!document.myform.passwd.value){
           alert("비밀번호를 입력하지 않으셨습니다.");
           document.myform.passwd.focus();
           return false;
         }
         return true;
       }
     //-->
   </script>
</head>
<BODY onload="begin()">
<form name="myform" action="loginPro.do" method="post" onSubmit="return checkIt()">
<table cellspacing=1 cellpadding=1 width="260" border=1 align="center" >
  
  <tr height="30">
    <td colspan="2" align="center"><strong>회원로그인</strong></td></tr>
  
  <tr height="30">
    <td width="110" align=center>아이디</td>
    <td width="150" align=center>
       <input type="text" name="id" size="15" maxlength="12"></td></tr>
  <tr height="30">
    <td width="110" align=center>비밀번호</td>
    <td width="150" align=center>
      <input type=password name="passwd"  size="15" maxlength="12"></td></tr>
  <tr height="30">
    <td colspan="2" align="center">
      <input type=submit value="로그인"> 
      <input type="button" value="회원가입" onclick="location.href='inputForm.do'"></td></tr>
</table>
</form>

</body>
</html>



            loginPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${check == 1}">
<script>
    location.href="login.do";
</script>
</c:if>
<c:if test="${check == 0}">
<script>
    alert("비밀번호가 맞지 않습니다.");
    history.go(-1);
</script>
</c:if>
<c:if test="${check == -1}">
<script>
    alert("아이디가 맞지 않습니다.");
    history.go(-1);
</script>
</c:if>



            logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    response.sendRedirect("loginForm.do");
%> 



            modifyForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>회원정보수정</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javaScript">
   <!-- 
    function checkIt() {
        var userinput = document.userinput;
               
        if(!userinput.passwd.value ) {
            alert("비밀번호를 입력하세요");
            return false;
        }
       
        if(!userinput.name.value) {
            alert("사용자 이름을 입력하세요");
            return false;
        }
        return true;
    }
//-->
</script>
</head>
<body>
<form method="post" action="modifyPro.do" name="userinput" onsubmit="return checkIt()">

  <table width="600" border="1" cellspacing="0" cellpadding="3"  align="center">
    <tr> 
      <td colspan="2" height="39" align="center">
         <font size="+1" ><b>회원 정보수정</b></font></td>
    </tr>
    <tr>
      <td colspan="2" align="center">회원의 정보를 수정합니다.</td>
    </tr>
     <tr> 
      <td width="200"><b>아이디 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td  width="200"> 사용자 ID</td>
      <td  width="400">${member.id}</td>
    </tr>
    
     <tr> 
      <td width="200"> 비밀번호</td>
      <td width="400"> 
        <input type="password" name="passwd" size="10" maxlength="10" value="${member.passwd}">
      </td>
    </tr>  
    <tr> 
      <td  width="200"><b>개인정보 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td   width="200">사용자 이름</td>
      <td  width="400"> 
        <input type="text" name="name" size="15" maxlength="10" value="${member.name}">
      </td>
    </tr>
    <tr> 
      <td width="200">주민등록번호</td>
      <td width="400"> 
        ${member.jumin1}-${member.jumin2}
      </td>
    </tr>
   <tr> 
      <td width="200">E-Mail</td>
      <td width="400">
          <input type="text" name="email" size="40" maxlength="30" value="${member.email}">
      </td>
    </tr>
    <tr> 
      <td width="200">Blog</td>
      <td width="400"> 
        <input type="text" name="blog" size="60" maxlength="50" value="${member.blog}">
      </td>
    </tr>      
    <tr> 
      <td colspan="2" align="center"> 
       <input type="submit" name="modify" value="수   정" >
       <input type="button" value="취  소" onclick="javascript:window.location='login.do'">      
      </td>
    </tr>
  </table>
</form>
</body>
</html>


            modifyPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>회원정보 수정</title>
</head>
<body>
회원정보가 수정되었습니다.
<input type="button" value="메인으로" onclick="location='login.do'">
</body>
</html>



        WEB-INF

            lib

                 commons-collections-3.1.jar

                 commons-dbcp-1.2.1.jar

                 commons-pool-1.2.jar

                 jstl-1.2.jar


            commandMap.properties

/inputForm.do=com.action.InputFormAction
/inputPro.do=com.action.InputProAction
/loginForm.do=com.action.LoginFormAction
/loginPro.do=com.action.LoginProAction
/login.do=com.action.LoginAction
/logout.do=com.action.LogoutAction
/modifyForm.do=com.action.ModifyFormAction
/modifyPro.do=com.action.ModifyProAction
/deleteForm.do=com.action.DeleteFormAction
/deletePro.do=com.action.DeleteProAction
/confirmId.do=com.action.ConfirmIdAction



            web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <display-name>member</display-name>
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>com.controller.Controller</servlet-class>
     <init-param>
         <param-name>configFile</param-name>
         <param-value>/WEB-INF/commandMap.properties</param-value>
     </init-param>
 </servlet>   
 
 <servlet-mapping>
     <servlet-name>Controller</servlet-name>
     <url-pattern>*.do</url-pattern>
 </servlet-mapping> 
 <!-- Controller end -->
   
  <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>



회원가입 테스트 : InputFormAction -> inputForm -> InputAction -> input -> LoginFormAction -> loginForm





로그인 테스트 : LoginAction(섹션내용으로 로그인체크) ->로그아웃상태 -> LoginFormAction ->  LoginProAction->






로그아웃 테스트  LogoutAction -> logout ->login.do




수정 테스트 : ModifyFormAction -> modifyForm.jsp -> ModifyProAction -> modifyPro.jsp -> login.do










회원탈퇴 테스트 : DeleteFormAction -> deleteForm.jsp -> DeleteProAction -> deletePro.jsp -> loginForm.do






중복아이디 체크  ConfirmIdAction-> confirmId




예제3: Model 2  DB연동 : ORACLE DB. MEMBER1 테이블 사용


mvcMain2.war


Java Resources 
     dr.mini.action 

         DeleteAction

package dr.mini.action;

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

import dr.mini.controller.Action;
      
import dr.mini.dao.MemberDao;

public class DeleteAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
                
        MemberDao manager = MemberDao.getInstance();
        int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd"));
        
        if(check == 1){
            manager.deleteMember(request.getParameter("id"));
        }
        
        request.setAttribute("check", check);

        return "/view/delete.jsp";
    }
}


DeleteFormAction
package dr.mini.action;

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

import dr.mini.controller.Action;

public class DeleteFormAction implements Action{
      
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        
        request.setAttribute("id", id);
        
        return "/view/deleteForm.jsp";
    }
}


InsertAction
package dr.mini.action;

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

import dr.mini.controller.Action;

import java.sql.Timestamp;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class InsertAction implements Action{
     
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
            
        request.setCharacterEncoding("utf-8");
        
        Member member =new Member();
        member.setId(request.getParameter("id"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setRegister(new Timestamp(System.currentTimeMillis()));
        
        MemberDao manager = MemberDao.getInstance();
        manager.insertMember(member);
                
        return "/view/insert.jsp";
    }
}
InsertFormAction
package dr.mini.action;

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

import dr.mini.controller.Action;

public class InsertFormAction implements Action{
   
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        return "/view/insertForm.jsp";
    }
}

SelectDetailAction
package dr.mini.action;

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

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class SelectDetailAction implements Action {

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
           
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        MemberDao mdb=MemberDao.getInstance();
        Member member =mdb.getMember(id);
        
        request.setAttribute("member", member);
        
        return "/view/selectDetail.jsp";
    }
}


SelectListAction
package dr.mini.action;

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

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;
import java.util.List;

public class SelectListAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");

        List<member> List =null;        
        MemberDao mdb = MemberDao.getInstance();
        List = mdb.getMemberList();
        
        request.setAttribute("memberList", List);
   
        return "/view/selectList.jsp";
    }
}


UpdateAction
package dr.mini.action;

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

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class UpdateAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
            
        MemberDao manager = MemberDao.getInstance();        
        int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd"));
        
        if(check==1){
            Member member =new Member();
            member.setId(request.getParameter("id"));
            member.setName(request.getParameter("name"));
            manager.updateMember(member);
        }
        //오토박싱
        request.setAttribute("check", check);
        
        return "/view/update.jsp";
    }
}

   

 UpdateFormAction

package dr.mini.action;

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

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class UpdateFormAction implements Action{
      
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        
        MemberDao manager= MemberDao.getInstance();
        Member member = manager.getMember(id);
        
        request.setAttribute("member", member);
        
        return "/view/updateForm.jsp";
    }
}

dr.mini.controller 

 Action

package dr.mini.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
    public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable;
}   

        Controller

package dr.mini.controller;

import java.io.FileInputStream;
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.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
           
public class Controller extends HttpServlet {
      
    private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장

    //명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
    //명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            String configFilePath = config.getServletContext().getRealPath(
                      configFile);
            fis = new FileInputStream(configFilePath);
            prop.load(fis);
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ex) {
                }
        }
        Iterator keyIter = prop.keySet().iterator();
        while (keyIter.hasNext()) {
            String command = (String) keyIter.next();
            String handlerClassName = prop.getProperty(command);
            try {
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandMap.put(command, handlerInstance);
            } catch (ClassNotFoundException e) {
                throw new ServletException(e);
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            }
        }
    }

    public void doGet(//get방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    protected void doPost(//post방식의 서비스 메소드
        HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        requestPro(request, response);
    }

    //시용자의 요청을 분석해서 해당 작업을 처리
    private void requestPro(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        String view = null;
        Action com=null;
        
        try {
            String command = request.getRequestURI();
            if (command.indexOf(request.getContextPath()) == 0) {
               command = command.substring(request.getContextPath().length());
            }
            com = (Action)commandMap.get(command); 
            view = com.execute(request, response);
        } catch(Throwable e) {
            throw new ServletException(e);
        }   
        RequestDispatcher dispatcher =request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}


dr.mini.dao 

 MemberDao

package dr.mini.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 dr.mini.domain.Member;

public class MemberDao {
    
    private static MemberDao instance = new MemberDao();

    public static MemberDao getInstance() {
        return instance;
    }

    private MemberDao(){}
   
    private Connection getConnection()throws Exception {
        Context initCtx = new InitialContext();
        Context envCtx = 
            (Context)initCtx.lookup("java:comp/env");
        DataSource ds = 
            (DataSource)envCtx.lookup("jdbc/orcl");
        return ds.getConnection();
    }
    
    //회원가입
    public void insertMember(Member member)throws Exception {
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        int cnt = 0;
        
        try{
            conn= getConnection();
            sql ="insert into MEMBER1 values(?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getId());
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setTimestamp(++cnt, member.getRegister());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 목록 보기
    public List getMemberList()throws Exception {
        
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List memeberList =null;
        Member member=null;
        String sql="";
        
        try{
            conn =getConnection();
            sql ="select * from MEMBER1 order by register desc";
            pstmt =conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                memeberList= new ArrayList();
                do{
                    member =new Member();
                    member.setId(rs.getString("id"));
                    member.setPasswd(rs.getString("passwd"));
                    member.setName(rs.getString("name"));
                    member.setRegister(rs.getTimestamp("register"));
                    memeberList.add(member);
                }while(rs.next());
            }else{
                //없으면
                //데이터가 없는 경우 비어있는 List 생성
                memeberList = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return memeberList;
    }
    
    //회원 상세 정보 보기
    public Member getMember(String id)throws Exception {
        
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Member member=null;
        String sql="";
        try{
            conn=getConnection();
            sql="select * from MEMBER1 where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                member=new Member();
                member.setId(rs.getString("id"));
                member.setPasswd(rs.getString("passwd"));
                member.setName(rs.getString("name"));
                member.setRegister(rs.getTimestamp("register"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return member;
    }
    
    //회원 인증
    public int userCheck(String id, String passwd)throws Exception {
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        String sql="";
        String dbpasswd="";
        int x = -1;
        
        try{
            conn =getConnection();
            sql ="select passwd from MEMBER1 where id = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd))
                    x=1; //인증성공
                else
                    x=0; //비밀번호 틀림
            }else
                x=-1; //해당 아이디 없음
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return x;
    }
    
    //회원 정보 수정
    public void updateMember(Member member)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        int cnt =0;
        try{
            conn =getConnection();
            sql = "update MEMBER1 set name=? where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getId());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 탈퇴 //회원정보 삭제
    public void deleteMember(String id)throws Exception {
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        try{
            conn =getConnection();
            sql = "delete from MEMBER1 where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //자원정리
        private void execClose(ResultSet rs,PreparedStatement pstmt, Connection conn){
            if (rs != null) try { rs.close(); } catch(SQLException ex) {}
            if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
            if (conn != null) try { conn.close(); } catch(SQLException ex) {}
        }
}

dr.mini.domain 

 Member

package dr.mini.domain;

import java.sql.Timestamp;

//자바빈
public class Member {
    //프로퍼티
    private String id;
    private String passwd;
    private String name;
    private Timestamp register;    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Timestamp getRegister() {
        return register;
    }
    public void setRegister(Timestamp register) {
        this.register = register;
    }
}

WebContent 
     META-INF

         context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>   
<!--
maxActive="20" //최대 커넥션 수
maxIdle="10"   //미리 만들어둘 기본커낵션 수
-->
    <Resource name="jdbc/orcl"
              auth="container"
              type="javax.sql.DataSource"
              username="hr"
              password="hr"
              driverClassName="oracle.jdbc.driver.OracleDriver"
              factory="org.apache.commons.dbcp.BasicDataSourceFactory"
              url="jdbc:oracle:thin:@localhost:1521:orcl"
              maxActive="20"
            maxIdle="10" />
</Context>

view 

 delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<%    //오토언박싱
    int check =(Integer)request.getAttribute("check");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삭제 예제</title>
</head>
<body>
<%if (check == 1){ %>
<script type="text/javascript">
alert("글을 삭제하였습니다");
location.href="selectList.do";
</script>
<% 
    }else{
%>
<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%
    }
%>
</body>
</html>



deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<% 
  String id = (String)request.getAttribute("id");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삭제 예제</title></head>
<body>
  <h2>member1 테이블에 삭제 예제</h2>
  <form method="post" action="delete.do">
  <input type="hidden" name="id" value="<%=id %>">
    아이디 : <%=id %><p>
    패스워드 : <input type="password" name="passwd"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>

insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삽입(추가)예제</title>
</head>
<body>
  member1 테이블에 새로운 레코드를 삽입(추가)했습니다.
  <input type="button" value="목록보기" onclick="location.href='selectList.do'">
</body>
</html>    

insertForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삽입(추가)예제</title></head>
<body>
  <h2>member1 테이블에 레코드삽입(추가)예제</h2>
  <form method="post" action="insert.do">
    아이디 : <input type="text" name="id"><p>
    패스워드 : <input type="password" name="passwd"><p>
    이름:<input type="text" name="name"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>  

selectDetail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dr.mini.domain.Member" %>
<%
    Member member = (Member)request.getAttribute("member");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>레코드 삽입 (추가)예제</title>
</head>
<body>
<h2>회원관리 상세 페이지</h2>
아이디:<%=member.getId() %><br/>
패스워드:<%=member.getPasswd() %><br/>
이름:<%=member.getName() %><br/>
<input type="button" value="수정" onclick="location.href='updateForm.do?id=<%=member.getId()%>'">
<input type="button" value="삭제" onclick="location.href='deleteForm.do?id=<%=member.getId()%>'">
</body>
</html>   

selectList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="dr.mini.domain.Member"%>
<%@ page import="java.text.SimpleDateFormat"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>테이블의 레코드를 화면에 표시하는 예제</title>
</head>
<body>
    <h2>member1 테이블의 레코드를 화면에 표시하는 예제</h2>
    <a href="insertForm.do">등록</a>
    <br />
    
    <% //목록같은경우는 어쩔수없이 jsp에서 루프를 돌려야함.
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy년 MM월 dd일  HH:mm:ss");
        //제네릭표현에 의해 타입이 정해져있음
        List<Member> memberList = (List<Member>)request.getAttribute("memberList");
        
        Member mb=null;
        if(!memberList.isEmpty()){
            for(int i=0;i<memberList.size();i++){
                //제네릭 표현때문에 (Member)memberList를 memberList로 생략가능
                mb=memberList.get(i);
    %>
    <a href="selectDetail.do?id=<%=mb.getId()%>"><%=mb.getId()%></a>-<%=mb.getPasswd()%>-<%=mb.getName()%>-<%=dateFormat.format(mb.getRegister())%><br />
    <%}}%>
</body>
</html>

update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<%   //오토언박싱 
    int check =(Integer)request.getAttribute("check");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 수정 예제</title>
</head>
<body>
<%if (check == 1){ %>
<script type="text/javascript">
alert("글을 수정하였습니다");
location.href="selectList.do";
</script>
<% 
    }else{
%>
<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%
    }
%>
</body>
</html>

updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="dr.mini.domain.Member" %>
<%
    Member member=(Member)request.getAttribute("member");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>   
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>레코드 수정 예제</title>
</head>
<body>
<h2>member1 테이블에 레코드 수정 예제</h2>
<form method="post" action="update.do">
<input type="hidden" name="id" value="<%=member.getId()%>">
아이디:<%=member.getId() %><p>
패스워드:<input type="password" name="passwd"><p>
이름:<input type="text" name="name" value="<%=member.getName()%>"><p>
<input type="submit" value="보내기">
</form>
</body>
</html>
WEB-INF 
 lib 
 commons-collections-3.1.jar 
 commons-dbcp-1.2.1.jar 
 commons-pool-1.2.jar 

 commandMap.properties
/insertForm.do=dr.mini.action.InsertFormAction
/insert.do=dr.mini.action.InsertAction
/selectList.do=dr.mini.action.SelectListAction
/selectDetail.do=dr.mini.action.SelectDetailAction
/updateForm.do=dr.mini.action.UpdateFormAction
/update.do=dr.mini.action.UpdateAction
/deleteForm.do=dr.mini.action.DeleteFormAction
/delete.do=dr.mini.action.DeleteAction

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>dr.mini.controller.Controller</servlet-class>
     <init-param>
         <param-name>configFile</param-name>
         <param-value>/WEB-INF/commandMap.properties</param-value>
     </init-param>
 </servlet>   
 
 <servlet-mapping>
     <servlet-name>Controller</servlet-name>
     <url-pattern>*.do</url-pattern>
 </servlet-mapping> 
 <!-- Controller end -->
   
  <display-name>mvcMain2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>



컨트롤러 맵핑확인 :Controller


insertForm.do 로연결확인



회원가입 테스트 [Controller 실행 ->요청-> InsertFormAction.java->insertForm.jsp  -> insertAction.java-> insert.jsp]


DB입력확인


리스트확인 : selectList.do


상세페이지 테스트 : SelectDetailAction -> selectDetail.jsp


수정페이지 테스트 : UpdateFormAction ->updateForm.jsp ->UpdateActioc ->update.jsp




삭제테스트 : DeleteFormAction ->deleteForm.jsp ->DeleteActioc ->delete.jsp

'JSP > 기본(Oracle)' 카테고리의 다른 글

방명록  (0) 2012.06.20
회원관리  (1) 2012.06.20
모델2 : MVC : Model View Controlle r- DB연동없이  (0) 2012.06.20
MVC: Model View Controller 모델2 ( 완전중요)  (0) 2012.06.20
EL(표현언어), JSTL, 국제화 태그 - 예제  (0) 2012.06.20

+ Recent posts