OpenFrameWork

오픈프레임워크_Day44

px 2015. 5. 15. 08:49
### : 목차 구분 기호
--- : 목차 내에 항목 구분 기호
@@@ : 태그 용도 
,,, : 같은 항목 내에 구분 기호

목차
1. 이론 및 정보
2. 설정 및 그 밖에
3. 소스코드 또는 실습
4. 과제

###################################
1. 이론 및 정보
-----------------------------------
* JSP도 Servlet도 lifeCycle을 그대로 가지고 있으나 메서드 이름은 다름
----------------------------------- 
* JSP와 DataBase 연결
-----------------------------------
###################################
2. 설정 및 그 밖에
-----------------------------------
* Eclipse 프로젝트 새로 만듬
Dynamic Web Project - DBApp
Tomcat 8.0 선택 ,web.xml 체크

아래 파일들 넣기
/DBApp/WebContent/WEB-INF/lib/servlet-api.jar
/DBApp/WebContent/WEB-INF/lib/ojdbc6.jar

폴더 생성
/DBApp/WebContent/v1

DBApp는 버전이 점점 올라가면서 실무에서 쓰는 방식으로 바뀌어 나갈 것임
-----------------------------------
###################################
3. 소스코드 또는 실습 
-----------------------------------
3-1
Project : BeanApp
Workspace : ~\JSP\EclipseWork
/BeanApp/WebContent/fileCounter.jsp

<%@page import="java.io.FileReader"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.BufferedReader"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%!
     int count;
     BufferedReader br;
     PrintWriter pw;
     String path;
     
     public void jspInit(){
          try{
               // 파일에 있는 카운터 읽어들이기
               path = getServletContext().getRealPath("/");
               //System.out.println(path);
               //F:\study\JSP\EclipseWork\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\BeanApp\
               br = new BufferedReader(new FileReader(path + "\\counter.txt"));
               String strCount = br.readLine();
               count = Integer.parseInt(strCount);
          }
          catch(Exception err){
               err.printStackTrace();
          }
          finally{
               if(br != null){
                    try{br.close();} catch(Exception err){}
               }
          }
     }
     
     public void jspDestroy(){
          // 메모리에 있는 카운터변수(count)를 파일에 저장시키기
          saveFile();
     }
     
     public void saveFile(){
          try{
               pw = new PrintWriter(path + "\\counter.txt");
               pw.println(count);
          }
          catch(Exception err){
               err.printStackTrace();
          }
          finally{
               if(pw != null){
                    try{pw.close();} catch(Exception err){}
               }
          }
     }
%>
<%
     if(session.isNew()){
          count++;
          saveFile();
     }
%>
<h2>총 방문자 수 : <%=count%></h2>
</body>
</html>
-----------------------------------  
3-2
Project : BeanApp
Workspace : ~\JSP\EclipseWork
/BeanApp/WebContent/counter.txt

0
-----------------------------------  
3-3
Project :BeanApp
Workspace : ~\JSP\EclipseWork
/BeanApp/src/bean/filecount/FileCount.java

package bean.filecount;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;

public class FileCount {
     int count = 0;
     BufferedReader br;
     PrintWriter pw;
     String path;
     
     public FileCount() {}     
     
     public void setPath(String path){
          this.path = path;
     }
     
     public void setStart(boolean b) {
          try{
               br = new BufferedReader(new FileReader(path + "\\counter.txt"));
               String strCount = br.readLine();
               count = Integer.parseInt(strCount);
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               if (br != null) {
                    try{br.close();}catch(Exception e){}
               }
          }
     }
          
     public void saveFile(){
          try{
               pw = new PrintWriter(path+"\\counter.txt");
               pw.println(count);
          }catch(Exception e){
               e.printStackTrace();
          }finally{
               if (pw != null) {
                    try{pw.close();}catch(Exception e){}
               }
          }
     }
     
     public void setNewCount(String s){
          count++;     
          if((count%10 == 0)&&(count >= 10))
               saveFile();
     }
     
     public int getCount(){
          
          return count;
     }
}
----------------------------------- 
3-4
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/addSawon.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>사원 추가</h1>
<form action="addSawon_proc.jsp" method="post">
     <table border="1">
          <tr>
               <td align="center">아이디</td>
               <td><input type="text" name="s_id" /></td>
          </tr>
          <tr>
               <td align="center">이름</td>
               <td><input type="text" name="s_name" /></td>
          </tr>
          <tr>
               <td align="center">나이</td>
               <td><input type="text" name="s_age" /></td>
          </tr>
          <tr>
               <td align="center">패스워드</td>
               <td><input type="password" name="s_pass" /></td>
          </tr>
          <tr>
               <td align="center">근무지</td>
               <td>
                    <select name="s_addr">
                         <option value="서울">서울</option>
                         <option value="광주">광주</option>
                         <option value="부산">부산</option>
                         <option value="제주">제주</option>
                    </select>
               </td>
          </tr>
          <tr>
               <td align="center">부서명</td>
               <td>
                    <select name="s_dept">
                         <option value="영업">영업</option>
                         <option value="기술">기술</option>
                         <option value="기획">기획</option>
                    </select>
               </td>
          </tr>
          <tr>
               <td colspan="2" align="center">
                    <input type="submit" value="추가" />&nbsp;&nbsp;&nbsp;
                    <input type="reset" value="다시 작성" />
               </td>               
          </tr>
     </table>
</form>
</body>
</html>
----------------------------------- 
3-5
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/index.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
<script>
     function delCheck(s_no) {
          var result = confirm("정말 삭제하시겠습니까?");
          if(result == true){
               location.href="deleteSawon.jsp?s_no="+s_no;
          }
     }
</script>
</head>
<body>
<h1>직원 정보 리스트</h1>
<a href="addSawon.html">사원추가</a>
<br/>
<form method="post" action="index.jsp">
     <select name="search">
          <option value="s_id">id</option>
          <option value="s_addr">근무지</option>
          <option value="s_dept">부서명</option>
     </select>
     <input type="text" name="searchText"/>
     <input type="submit" name="검색"/>
</form>
<table border="1">
     <tr>
          <th>사번</th>
          <th>아이디</th>
          <th>이름</th>
          <th>패스워드</th>
          <th>나이</th>
          <th>근무지</th>
          <th>부서명</th>
          <th>수정</th>
          <th>삭제</th>          
     </tr>
     <%
          Connection con = null;
          Statement stmt = null;
          ResultSet rs = null;
          String url = "jdbc:oracle:thin:@localhost:1521:orcl";
          
          try{
               Class.forName("oracle.jdbc.driver.OracleDriver");
               con = DriverManager.getConnection(url, "scott","1111");
               stmt = con.createStatement();
               rs = stmt.executeQuery(sql);
               while(rs.next()){
                    int s_no = rs.getInt("s_no");
                    String s_id = rs.getString("s_id");
                    String s_name = rs.getString("s_name");
                    String s_pw = rs.getString("s_pass");
                    int s_age = rs.getInt("s_age");
                    String s_addr = rs.getString("s_addr");
                    String s_dept = rs.getString("s_dept");                    
     %>
                    <tr>
                         <th><%=s_no%></th>
                         <th><%=s_id%></th>
                         <th><%=s_name%></th>
                         <th><%=s_pw%></th>
                         <th><%=s_age%></th>
                         <th><%=s_addr%></th>
                         <th><%=s_dept%></th>
                         <th><a href="editSawon.jsp?s_no=<%=s_no%>">수정</a></th>
                         <th><a href="javascript:delCheck('<%=s_no%>')">삭제</th>
                    </tr>
     <%
               }
          }catch(Exception e){
               System.out.println("index.jsp : "+e);
          }finally{
               if(rs!=null)try{rs.close();}catch(Exception e){}
               if(stmt!=null)try{stmt.close();}catch(Exception e){}
               if(con!=null)try{con.close();}catch(Exception e){}
          }
     %>
</table>
</body>
</html>
----------------------------------- 
3-6
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/oracle.sql

CREATE table tblSawon(
     s_no          number,
     s_id          varchar2(20),
     s_name          varchar2(20),
     s_pass          varchar2(20),
     s_age          number(2),
     s_addr          varchar2(20),
     s_dept          varchar2(20),
     CONSTRAINT pk_no PRIMARY KEY(s_no)
);
CREATE SEQUENCE seq_no;

insert into tblSawon values(seq_no.nextVal, 'hong', '홍길동', '1111', 20, '서울', '영업');
insert into tblSawon values(seq_no.nextVal, 'lim', '임꺽정', '2222', 29, '광주', '영업');
insert into tblSawon values(seq_no.nextVal, 'lee', '이순신', '3333', 39, '부산', '영업');
insert into tblSawon values(seq_no.nextVal, 'shin', '신돌석', '4444', 36, '서울', '기술');
insert into tblSawon values(seq_no.nextVal, 'jang', '장보고', '5555', 35, '서울', '기술');
insert into tblSawon values(seq_no.nextVal, 'ahn', '안창호', '6666', 34, '제주', '기획');
insert into tblSawon values(seq_no.nextVal, 'yun', '윤봉길', '7777', 25, '제주', '기획');
----------------------------------- 
3-7 
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/oracleTestConnection.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1>오라클 연결 테스트</h1>
<%
     try{
          //my sql로 할때
          //Class.forName("com.mysql.jdbc.Driver");
          //String url = "jdbc:mysql://localhost:3306/test";
          //Connection con = DriverManager.getConnection(url, "root","1111");
          Class.forName("oracle.jdbc.driver.OracleDriver");
          String url = "jdbc:oracle:thin:@localhost:1521:orcl";
          Connection con = DriverManager.getConnection(url, "scott","1111");
          if(con!=null)
               out.println("연결 성공");
     }catch(Exception e){
          System.out.println("연결실패 : "+e);
     }
%>
</body>
</html>
-----------------------------------  
3-8 
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/addSawon_proc.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
     request.setCharacterEncoding("euc-kr");
     String s_id = request.getParameter("s_id");
     String s_name = request.getParameter("s_name");
     String s_pass = request.getParameter("s_pass");
     String s_age = request.getParameter("s_age");
     String s_addr = request.getParameter("s_addr");
     String s_dept = request.getParameter("s_dept");
     //out.println(s_id+","+s_name+","+s_pass+","+s_age+","+s_addr+","+s_dept);
     
     String sql = "insert into " 
               + "tblsawon(s_no,s_id,s_name,s_pass,s_age,s_addr,s_dept)"
               + " values(seq_no.nextVal,'"+s_id+"','"+s_name+"','"+s_pass+"',"+
               s_age+",'"+s_addr+"','"+s_dept+"')";
     //out.println(sql);
     
     Connection con = null;
     Statement stmt = null;
     ResultSet rs = null;
     String url = "jdbc:oracle:thin:@localhost:1521:orcl";
     
     try{
          Class.forName("oracle.jdbc.driver.OracleDriver");
          con = DriverManager.getConnection(url, "scott","1111");
          stmt = con.createStatement();
          stmt.executeUpdate(sql);
     %>
          <script>
               alert("사원이 잘 추가 되었습니다.");
               location.href="index.jsp";
          </script>     
     <%
     }catch(Exception e){
          System.out.println("addSawon_proc.jsp : "+e);
     }finally{
          if(rs!=null)try{rs.close();}catch(Exception e){}
          if(stmt!=null)try{stmt.close();}catch(Exception e){}
          if(con!=null)try{con.close();}catch(Exception e){}
     }
%>
</body>
</html>
-----------------------------------  
3-9 
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/editSawon.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
     String s_no = request.getParameter("s_no");
     Connection con = null;
     Statement stmt = null;
     ResultSet rs = null;
     String url = "jdbc:oracle:thin:@localhost:1521:orcl";
     String sql = "select * from tblsawon where s_no = " + s_no;
     
     String s_id=null,s_name=null,s_pass=null,
               s_addr=null,s_dept=null,s_age=null;
     try{
          Class.forName("oracle.jdbc.driver.OracleDriver");
          con = DriverManager.getConnection(url, "scott","1111");
          stmt = con.createStatement();
          rs = stmt.executeQuery(sql);
          if(rs.next()){
               s_no = rs.getString("s_no");
               s_id = rs.getString("s_id");
               s_name = rs.getString("s_name");
               s_pass = rs.getString("s_pass");
               s_age = rs.getString("s_age");
               s_addr = rs.getString("s_addr");
               s_dept = rs.getString("s_dept");
          }
     }catch(Exception e){
          System.out.println("editSawon.jsp : "+e);
     }finally{
          if(rs!=null)try{rs.close();}catch(Exception e){}
          if(stmt!=null)try{stmt.close();}catch(Exception e){}
          if(con!=null)try{con.close();}catch(Exception e){}
     }
%>
<form action="editSawon_proc.jsp" method="post">
<input type="hidden" name="s_no" value="<%=s_no%>"/>
     <table border="1">
          <tr>
               <td align="center">아이디</td>
               <td><input type="text" name="s_id" value="<%=s_id%>"/></td>
          </tr>
          <tr>
               <td align="center">이름</td>
               <td><input type="text" name="s_name" value="<%=s_name%>"/></td>
          </tr>
          <tr>
               <td align="center">나이</td>
               <td><input type="text" name="s_age" value="<%=s_age%>"/></td>
          </tr>
          <tr>
               <td align="center">패스워드</td>
               <td><input type="password" name="s_pass" value="<%=s_pass%>"/></td>
          </tr>
          <tr>
               <td align="center">근무지</td>
               <td>
                    <select name="s_addr">
                         <option value="서울"<%if(s_addr.equals("서울")){%>selected="selected"<%}%>>서울</option>
                         <option value="광주"<%if(s_addr.equals("광주")){%>selected="selected"<%}%>>광주</option>
                         <option value="부산"<%if(s_addr.equals("부산")){%>selected="selected"<%}%>>부산</option>
                         <option value="제주"<%if(s_addr.equals("제주")){%>selected="selected"<%}%>>제주</option>
                    </select>
               </td>
          </tr>
          <tr>
               <td align="center">부서명</td>
               <td>
                    <select name="s_dept">
                         <option value="영업"<%if(s_dept.equals("영업")){%>selected="selected"<%}%>>영업</option>
                         <option value="기술"<%if(s_dept.equals("기술")){%>selected="selected"<%}%>>기술</option>
                         <option value="기획"<%if(s_dept.equals("기획")){%>selected="selected"<%}%>>기획</option>
                    </select>
               </td>
          </tr>
          <tr>
               <td colspan="2" align="center">
                    <input type="submit" value="수정" />&nbsp;&nbsp;&nbsp;
                    <input type="reset" value="다시 작성" />
               </td>               
          </tr>
     </table>
</form>
</body>
</html>
-----------------------------------  
3-10 
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/editSawon_proc.jsp

<%@ page contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
     request.setCharacterEncoding("euc-kr");
     String s_no = request.getParameter("s_no");
     String s_id = request.getParameter("s_id");
     String s_name = request.getParameter("s_name");
     String s_pass = request.getParameter("s_pass");
     String s_age = request.getParameter("s_age");
     String s_addr = request.getParameter("s_addr");
     String s_dept = request.getParameter("s_dept");
     //out.println(s_id+","+s_name+","+s_pass+","+s_age+","+s_addr+","+s_dept);
     
     String sql = "update tblsawon set " 
               + "s_id='"+s_id+"', s_name='"+ s_name+"', s_pass='"+s_pass+"', s_age="+
               s_age+", s_addr='"+s_addr+"', s_dept='"+s_dept+"' where s_no = "+s_no;
     //out.println(sql);
     
     Connection con = null;
     Statement stmt = null;
     ResultSet rs = null;
     String url = "jdbc:oracle:thin:@localhost:1521:orcl";
     
     try{
          Class.forName("oracle.jdbc.driver.OracleDriver");
          con = DriverManager.getConnection(url, "scott","1111");
          stmt = con.createStatement();
          stmt.executeUpdate(sql);
     %>
          <script>
               alert("사원이 잘 수정 되었습니다.");
               location.href="index.jsp";
          </script>     
     <%
     }catch(Exception e){
          System.out.println("editSawon_proc.jsp : "+e);
     }finally{
          if(rs!=null)try{rs.close();}catch(Exception e){}
          if(stmt!=null)try{stmt.close();}catch(Exception e){}
          if(con!=null)try{con.close();}catch(Exception e){}
     }
%>
</body>
</html>
-----------------------------------  
3-11 
Project : DBApp
Workspace : ~\JSP\EclipseWork
/DBApp/WebContent/v1/deleteSawon.jsp

<%@ page contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
     request.setCharacterEncoding("euc-kr");
     String s_no = request.getParameter("s_no");
     String sql = "delete from tblsawon where s_no = " + s_no;
     
     Connection con = null;
     Statement stmt = null;
     ResultSet rs = null;
     String url = "jdbc:oracle:thin:@localhost:1521:orcl";
     
     try{
          Class.forName("oracle.jdbc.driver.OracleDriver");
          con = DriverManager.getConnection(url, "scott","1111");
          stmt = con.createStatement();
          stmt.executeUpdate(sql);
     %>
          <script>
               alert("사원이 잘 삭제 되었습니다.");
               location.href="index.jsp";
          </script>     
     <%
     }catch(Exception e){
          System.out.println("deleteSawon_proc.jsp : "+e);
     }finally{
          if(rs!=null)try{rs.close();}catch(Exception e){}
          if(stmt!=null)try{stmt.close();}catch(Exception e){}
          if(con!=null)try{con.close();}catch(Exception e){}
     }
%>
</body>
</html>
----------------------------------- 
###################################
4. 과제
-----------------------------------
4-1
/BeanApp/WebContent/fileCounter.jsp
1.Bean으로 처리
2.10명당 한번씩 파일에 저장하겠끔 만들기
----------------------------------- 
4-2
/DBApp/WebContent/v1/index.jsp
검색 기능 완성
v2 버전, statment를 
PreparedStatement로 바꿔
----------------------------------- 
4-3
----------------------------------- 
4-4
----------------------------------- 
4-5
-----------------------------------
###################################
5. 과제 해결
-----------------------------------
5-1
-----------------------------------
5-2
----------------------------------- 
5-3
-----------------------------------
5-4
-----------------------------------
###################################
6. 기타
----------------------------------- 

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