본문 바로가기

IT&코딩/국비지원

Servlet - 2 (frontcontroller)

728x90
반응형

■ 시작 전 servlet 파일과 함꼐 보는 메모

 

package com.wooricom.main;

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

/**
 * Servlet implementation class FrontController2
 */
// FrontController로 가겠다고 action에 써주면 여기로 온다.
// 지금은 aa.do, bb.do, cc.do 형태로 만들 것이고
// FrontController가 모든 것을 다 하기 때문에
// 전부 여기로 찾아온다.
// 그러므로 아래 문장을 변경시켜주어야 한다.
// @WebServlet("/FrontController2")
// 그래서 getAllInfo.jsp에서 action="getAllInfo.do"이므로 여기로 온다.
@WebServlet("/hello.jsp") 
public class FrontController2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontController2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		// 프로젝트명 + /.do 파일명
		System.out.println(request.getRequestURI());
		// getAllInfo.jsp를 실행해보자. 그리고 모두 보기를 눌러보자.
		// 결과 : /MVC2_frontcontroller/getAllInfo.do
		// getAllInfo.jsp -> @WebServlet("*.do") -> sysout -> 프로젝트명/getAllInfo.do
		// 원래 url은 http://localhost:8080/MVC2_frontcontroller/getAllInfo.do
		// jsp쪽에서 totsearch.do (전체검색), update.do(수정), delete.do(삭제) 등이 사용되면서 
		// FrontController2에게 넘어올 텐데 front controller는 무엇이 넘어왔는지 구분해야 됨
		// 넘어올 때 http://localhost:8080/프로젝트명/totsearch.do
		// or http://localhost:8080/프로젝트명/totsearch.do 등으로 넘어옴으로 맨뒤에 .do가 어떤 이름인지 인식되어야 거기에 합당한 작업을 할 수 있다.
		
		// 프로젝트명 only
		System.out.println(request.getContextPath()); // 프로젝트 이름
		
		// 그렇다면 프로젝트이름을 제외시키면 .do 파일명만 남으므로
		// 프로젝트 이름의 길이를 재서 제외시키자
		// 만일 프로젝트명이 10글자라면 substring(0, 2)를 활용해보자 (cf) substring(2, 8)
		// 10번째부터 제일 끝까지를 의미
		// 예) /naproject/aa.do ==> 10번째는 /aa.do를 의미하므로 파일명만 남음
		// 이것을 앞의 문법을 통해 표현하면
		// request.getRequestURI() : 프로젝트명/파일명
		// request.getContextPath().length() : 프로젝트명의 길이
		String c = request.getRequestURI().substring(request.getContextPath().length());
		System.out.println(c);
		
		/*
		 * switch(c) { case "/getAllinfo.do": 전체검색 stmt break; case "/update.do": 수정작업
		 * stmt break; case "/delete.do": 삭제작업 stmt break; }
		 */
		
	}

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

}

 

■ telinfoVO

 

TelInfoVO.java

 

package telinfoVO;

import java.util.Date;

//VO (Value Object) 

public class TelInfoVo {

	private int id;			//number(5)
	private String name;	//varchar2(20)
	private String tel;		//varchar2(20)
	private Date d;			//date
	
	// =======================================================
	public TelInfoVo(int id, String name, String tel, Date d) {
		//super();
		this.id = id;
		this.name = name;
		this.tel = tel;
		this.d = d;
	}
	
	public TelInfoVo() { }
	// =======================================================


	// getter , setter ===========================================
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public Date getD() {
		return d;
	}
	public void setD(Date d) {
		this.d = d;
	}
	// getter , setter ===========================================
	
}

 

■ telinfoDBConn

 

□ TelInfoDBConn.java

 

package telinfoDBConn;

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

//DB에 접속 하고 끊기 만들어 두고 사용할 때마다 불러쓰자

public class TelInfoDBConn {
	
	private Connection con;	//접속객체 con 선언
	
	//getConnection() 메소드	: 반환타입은 Connection
	public Connection getConnection() {
		return con;	//접속객체 return
	}
	
	//생성자
	public TelInfoDBConn() throws ClassNotFoundException, SQLException {
		Class.forName("oracle.jdbc.driver.OracleDriver"); // 드라이버 메모리로딩 선언
		con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
	}
}

 

■ com.woori.main

 

□ Sawonfrontcontroller.java

 

package com.wooricom.main;

import java.io.IOException;

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

import com.haeva.my.HaevaGetAllInfo;
import com.haeva.my.HaevaImpl;
import com.haeva.my.HaevaInsert;
import com.haeva.my.HaevaSearchone;
import com.haeva.my.HaevaUpdate;
import com.haeva.my.haevaDelete;

/**
 * Servlet implementation class Sawonfrontcontroller
 */
@WebServlet("*.do")
public class Sawonfrontcontroller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Sawonfrontcontroller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String c = request.getRequestURI().substring(request.getContextPath().length());
		String str = null;
		
		HaevaImpl scmd1 = null;
		
		// frontcontroller가 너무 길어지므로 호출을 해서 하도록 
		// cf. execute() getAction()
		
		switch(c) {
		
		case "/getAllInfo.do":
			scmd1 = new HaevaGetAllInfo();
			try {
				scmd1.haeva(request, response);
			} catch(Exception e) {
				e.printStackTrace();
			}
			str = "getAllInfo.jsp";
			break;
			
		case "/telSearchOne.do":
			scmd1 = new HaevaSearchone();
			try {
				scmd1.haeva(request, response);
			} catch(Exception e) {
				e.printStackTrace();
			}
			str = "sawonUpdateForm.jsp";
			break;
			
		case "/telInsert.do":
			scmd1 = new HaevaInsert();
			try {
				scmd1.haeva(request, response);
			} catch(Exception e) {
				e.printStackTrace();
			}
			str = "getAllInfo.jsp";
			break;
			
		case "/telDelete.do":
			scmd1 = new haevaDelete();
			try {
				scmd1.haeva(request, response);
			} catch(Exception e) {
				e.printStackTrace();
			}
			str = "getAllInfo.jsp";
			break;
			
		case "/telUpdate.do":
			scmd1 = new HaevaUpdate();
			try {
				scmd1.haeva(request, response);
			} catch(Exception e) {
				e.printStackTrace();
			}
			str = "getAllInfo.jsp";
			break;
		} // switch-end
		
		RequestDispatcher rd1 = request.getRequestDispatcher(str);
		rd1.forward(request, response);
		
	} // doGet-end

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

}

 

■ telinfoDAO

 

□ TelInfoDAO.java

 

package telinfoDAO;

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

import telinfoDBConn.TelInfoDBConn;
import telinfoVO.TelInfoVo;


public class TelInfoDAO {

	private Connection con;			
	PreparedStatement pstmt = null;
	ResultSet rs = null;				
	
	
	public TelInfoDAO() throws ClassNotFoundException, SQLException {
		con = new TelInfoDBConn().getConnection(); 									
	} 
	
	public boolean insert_nametel(int id, String name, String tel, String d) throws SQLException {
		
		String sql="insert into teltable5 values(?, ?, ?, ?)";
			
		pstmt=con.prepareStatement(sql);
		pstmt.setInt(1, id);
		pstmt.setString(2, name);
		pstmt.setString(3, tel);
		
		int year = Integer.parseInt(d.substring(0, 4)) - 1900;
		int month = Integer.parseInt(d.substring(4, 6)) - 1;
		int day = Integer.parseInt(d.substring(6, 8));
		Date date = new Date(year, month, day);
		pstmt.setDate(4, date);
		pstmt.executeUpdate();
			
		return true;
	}
	
	public boolean update_all(int id1, String name1, String tel1, String d, String sname) throws SQLException {
	
		String sql="update teltable5 set id = ?, name = ?, tel = ?,"
				       + " d = TO_DATE(?,'YYYY-MM-DD') where name = ?";

		pstmt=con.prepareStatement(sql);
		
		pstmt.setInt(1, id1);
		pstmt.setString(2, name1);
		pstmt.setString(3, tel1);
		pstmt.setString(4, d);// 문자 넣기는 같은데 to_date 사용
		pstmt.setString(5, sname);
		
		pstmt.executeUpdate();
		return true;
	}
	
	public boolean delete_nametel(String name) throws SQLException {
		
		String sql="delete from TelTable5 where name = ?";
		pstmt = con.prepareStatement(sql);
		pstmt.setString(1, name);
		pstmt.executeUpdate();
		return true;
	} 
		
	public ArrayList<TelInfoVo> getAllInfo() throws SQLException{
		
		ArrayList<TelInfoVo> tiarray = new ArrayList<TelInfoVo>();
		String sql="select * from teltable5 order by id";
		
		pstmt=con.prepareStatement(sql);
		rs=pstmt.executeQuery();
		while(rs.next()) {
			int id = rs.getInt("id");
			String name = rs.getString("name");
			String tel = rs.getString("tel");
			Date d = rs.getDate("d");
			TelInfoVo tv = new TelInfoVo(id,name,tel,d);
			tiarray.add(tv);
		}//while-end
		return tiarray;
	}
	
	
	
	
	public TelInfoVo getInfo(String name1) throws SQLException{
		TelInfoVo tv = null;
		String sql = "SELECT * FROM TelTable5 where name = ?";	
		pstmt = con.prepareStatement(sql);
		pstmt.setString(1, name1);
		rs = pstmt.executeQuery();
		if(rs.next()){	
				int id = rs.getInt(1);
				String name = rs.getString(2);
				String tel = rs.getString(3);
				Date d = rs.getDate(4);				
				tv = new TelInfoVo(id,name,tel,d);	
				
		}else { 
			tv = null;	// null (return null) 
		}
		return tv;		
	}

	
} // TelInfoDAO-end

 

■ com.haeva.my

 

□ HaevaImpl.java

 

package com.haeva.my;

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

public interface HaevaImpl {
	
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception; 
		
}

// web : front controller pattern(지배인) + 여러개 controller
// spring : 여러개 controller + 총지배인

// interface 역할 : (1) 다중상속 (2) 함수의 원형 (3) 협업

 

□ HaevaGetAllInfo.java

 

package com.haeva.my;
import java.util.ArrayList;

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

import telinfoDAO.TelInfoDAO;
import telinfoVO.TelInfoVo;

public class HaevaGetAllInfo implements HaevaImpl {

	@Override // 인터페이스에 선언된 것을 상속받은 여기서 구현
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		TelInfoDAO tidao1 = new TelInfoDAO();
		ArrayList<TelInfoVo> alist1 = tidao1.getAllInfo();
		
		request.setAttribute("alist1", alist1);
		
	}
}

 

□ HaevaInsert.java

 

package com.haeva.my;

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

import telinfoDAO.TelInfoDAO;

public class HaevaInsert implements HaevaImpl {

	@Override
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String tel = request.getParameter("tel");
		String d = request.getParameter("sDate");
		
		TelInfoDAO tidao = new TelInfoDAO();
		tidao.insert_nametel(id, name, tel, d);
	}

}

 

□ HaevaSearchone.java

 

package com.haeva.my;

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

import telinfoDAO.TelInfoDAO;
import telinfoVO.TelInfoVo;

public class HaevaSearchone implements HaevaImpl {

	@Override
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		TelInfoDAO tidao1 = new TelInfoDAO();
		
		String name = request.getParameter("name");
		
		TelInfoVo tv = tidao1.getInfo(name);
		
		request.setAttribute("sname", name);
		request.setAttribute("stv", tv);
		
	}

}

 

□ HaevaUpdate.java

 

package com.haeva.my;

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

import telinfoDAO.TelInfoDAO;

public class HaevaUpdate implements HaevaImpl {

	@Override
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String tel = request.getParameter("tel");
		String d = request.getParameter("d");
		
		String sname = request.getParameter("sname");
		TelInfoDAO tidao1 = new TelInfoDAO();
		
		tidao1.update_all(id, name, tel, d, sname);

	}

}

 

□ haevaDelete.java

 

package com.haeva.my;

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

import telinfoDAO.TelInfoDAO;

public class haevaDelete implements HaevaImpl {

	@Override
	public void haeva(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String name = request.getParameter("name");
		TelInfoDAO tidao = new TelInfoDAO();
		tidao.delete_nametel(name);

	}

}

 


 

■ view

 

□ getAllInfo.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>
<html>
<head>
<meta charset="UTF-8">
<title>사원 전체 보기</title>
</head>
<body>  <!--  나는 getAllInfo.jsp -->
<h1>사원 전체 보기</h1>
<hr><br>

<table border=1>
	<tr>
		<td colspan=4>
			<form action="getAllInfo.do">
				<input type="submit" value="모두보기">
			</form>
		</td>
	</tr>
	
	<!--  
		우선 컨트롤러에서 파일명을 처리할 때 .do를 붙이자 + 총지배인(front controller)
		.do가 붙으면 파일 처리를 통일해서 처리
		서블릿으로 갔다가 business logic을 처리한 다음 다시 출발한 곳으로 온다.
		아래는 되돌아와서 출력하기 위한 부분
	-->

	<tr>
		<td>사번</td>
		<td>이름</td>
		<td>전화번호</td>
		<td>입사일</td>
	</tr>
	
	<c:forEach var="vo1" items="${alist1}"> <!-- request scope에 객체 전체를 ArrayList alist1에 저장 -->
		<tr>	
			<td>${vo1.id}</td>
			<td><a href="telSearchOne.do?name=${vo1.name}"> ${vo1.name} </a></td>	<!-- 전체보기 하면서 수정도 가능하게 하자 -->
			<td>${vo1.tel}</td>
			<td>${vo1.d}</td>
		</tr>
	</c:forEach>

	<table border=0>
		<tr>     
			<td><a href="sawonInsertForm.jsp">[입력]</a></td>
			<td><a href="getAllInfo.jsp">[모두보기]</a></td>
		</tr>
	</table>
</table>

</body>
</html>

 

□ sawonInsertForm.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!-- SawonInsert.jsp -->    
    
<!DOCTYPE html> 
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>사원 정보 입력</h1>
<form action="telInsert.do" method="post">

	<table border="1">
		<tr>
			<td>사번</td>
			<td><input type="text" name="id"></td>
		</tr>
		<tr>
			<td>이름</td>
			<td><input type="text" name="name"></td>
		</tr>
		<tr>
			<td>전화번호</td>
			<td><input type="text" name="tel"></td>
		</tr>
		<tr>
			<td>입사일</td>
			<td><input type="text" name="sDate"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="추가하자"></td>
		</tr>
	</table>
	<table border="0">
			<tr>
				<td><a href="sawonInsertForm.jsp">[입력]</a></td>
				<td><a href="sawonUpdateForm.jsp">[수정]</a></td>
				<td><a href="getAllInfo.jsp">[모두보기]</a></td>
		</table>
</form>

</body>
</html>

 

□ sawonUpdateForm.jsp

 

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>한명 출력</h1>
<form action="telUpdate.do?sname=${stv.name}" method="get">
	<table border="1">
		<tr>
			<th>사번</th>
			<th>이름</th>
			<th>전화번호</th>
			<th>입사일</th>
		</tr>
		<tr>
			<!-- 입출력이 가능한 상태로 -->
			<td><input type="text" name="id" value="${stv.id}"></td>
			<td><input type="text" name="name" value="${stv.name}"></td>
			<td><input type="text" name="tel" value="${stv.tel}"></td>
			<td><input type="text" name="d" value="${stv.d}"></td>
			<td><input type="hidden" name="sname" value="${stv.name}"></td>
		</tr>
		<tr>
			<td colspan="4">
				<input type="submit" value="수정">
				<input type="reset" value="취소">
			</td>	
		</tr>
	</table>
</form>
<br>
<a href="${pageContext.request.contextPath}/getAllInfo.jsp">[모두보기]</a>
<a href="telDelete.do?name=${stv.name}">[삭제]</a> <!-- 삭제를 위해 이름을 넘겨줌 -->

</body>
</html>
728x90
반응형

'IT&코딩 > 국비지원' 카테고리의 다른 글

Servlet - 4 (HttpSession)  (0) 2023.06.02
Servlet - 3 (MVC_board)  (0) 2023.06.02
Servlet - 1 (설명, no_frontcontroller)  (0) 2023.05.29
MVC1 모델 최종 (사원관리 프로그램)  (0) 2023.05.26
JSP, EL, JSTL - 2  (0) 2023.05.26