Devlog
article thumbnail

위 글은 해당 카테고리의 수업 강의 자료를 정리한 것입니다. 

 

 

 

 

Model2 방식

  • 정의: 모든 요청을 controller에게 함
  • 요청이 들어오면 처리를 위한 흐름 제어는 controller인 서블릿이 담당함
  • 요청 처리에 필요한 로직은 서비스 클래스가 담당함
  • 요청 결과는 view만 jsp를 통해 출력함
  • 장단점
장점
단점
출력을 위한 뷰코드와 로직처리를 위한 자바 코드 가 분리되어있다.
모델1에 비해 복잡하지 않다. 분업이 용이하다
구조가 복잡하고 습득이 어렵고 작업량이 많다. java에 대한 깊은 이해가 필요하다.
  • 모델2 방식 예제 (emaillist)

 

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>메일 리스트 가입</h1>
	<p>
		메일 리스트에 가입하려면,<br> 아래 항목을 기입하고 submit 버튼을 클릭하세요.
	</p>
	<form action="insert.jsp" method="post">
		Last name(성): <input type="text" name="ln" value=""><br>
		First name(이름): <input type="text" name="fn" value=""><br>
		Email address: <input type="text" name="email" value=""><br>
		<input type="submit" value="등록">
	</form>
	<br>
	<p>
		<a href="list.jsp">리스트 바로가기</a>
	</p>
</body>
</html>

 

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

<%@ page import="com.javaex.dao.EmaillistDao"%>
<%@ page import="com.javaex.vo.EmaillistVo"%>
<%@ page import="java.util.List"%>

<%
	EmaillistDao dao = new EmaillistDao();
	List<EmaillistVo> list = dao.getList();
	System.out.println(list.toString());
%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>메일 리스트에 가입되었습니다.</h1>
	<p>입력한 정보 내역입니다.</p>
	<!-- 메일정보 리스트 -->
	<%-- list에서 하나씩 빼서 테이블를 채운다--%>
	<% 
		for(EmaillistVo vo : list) {
	%>
	<table border="1" cellpadding="5" cellspacing="2">
		<tr>
      <td align=right width="110">No:</td>
      <td width="170"> <a href="delete.jsp?no=<%=vo.getNo() %>">삭제</a> </td>
    </tr>
    <tr>
			<td align=right width="110">Last name:</td>
			<td width="170"><%=vo.getLastName() %></td>
		</tr>
		<tr>
			<td align=right>First name:</td>
			<td><%=vo.getFirstName() %></td>
		</tr>
		<tr>
			<td align=right>Email address:</td>
			<td><%=vo.getEmail() %></td>
		</tr>
	</table>
	<br>
	<%		
		}
	%>
	<p>
		<a href="form.jsp?no">추가메일 등록</a>
	</p>
	<br>
</body>
</html>

 

  • insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ page import="com.javaex.dao.EmaillistDao"%>
<%@ page import="com.javaex.vo.EmaillistVo"%>

<% 
	request.setCharacterEncoding("UTF-8");
	String lastName = request.getParameter("ln");
	String firstName = request.getParameter("fn");
	String email = request.getParameter("email");
	
	EmaillistVo vo = new EmaillistVo(lastName, firstName, email);
	
	EmaillistDao dao = new EmaillistDao();
	dao.insert(vo);

	response.sendRedirect("list.jsp");
	
%>

 

  • delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ page import="com.javaex.dao.EmaillistDao"%>
<%@ page import="com.javaex.vo.EmaillistVo"%>

<% 
	request.setCharacterEncoding("UTF-8");
	String no = request.getParameter("no");
	
	//out.println(no);
	
  EmaillistDao dao = new EmaillistDao();
	dao.delete(no);
  
  

	response.sendRedirect("list.jsp");
	
%>

 

  • EmaillistDao.java
package helloJSP;

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

import com.javaex.vo.EmaillistVo;

public class EmaillistDao {
  private Connection getConnection() throws SQLException {
    Connection conn = null;
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      String dburl = "jdbc:oracle:thin:@localhost:1521:xe";
      conn = DriverManager.getConnection(dburl, "webdb", "1234");
    } catch (ClassNotFoundException e) {
      System.err.println("JDBC 드라이버 로드 실패!");
    }
    return conn;
  }
  
	public int insert(EmaillistVo vo) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		int count = 0 ;
		
		try {
			conn = getConnection();
			
			String query ="insert into emaillist values (seq_emaillist_no.nextval, ?, ?, ?)";
			pstmt = conn.prepareStatement(query);	
			
			pstmt.setString(1, vo.getLastName());
			pstmt.setString(2, vo.getFirstName());
			pstmt.setString(3, vo.getEmail());
		
			count = pstmt.executeUpdate();
			
			System.out.println(count + "건 등록");
			
		} catch (SQLException e) {
			System.out.println("error:" + e);
		} finally {
			try {
				if (pstmt != null) pstmt.close();
				if (conn != null) conn.close();
			} catch (SQLException e) {
				System.out.println("error:" + e);
			}
		}
		return count;
	}
	
	public void delete(String no) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    int count = 0 ;
    
    try {
      conn = getConnection();
      
      String query ="delete from emaillist where no = ?";
      pstmt = conn.prepareStatement(query); 
      
      pstmt.setInt(1, Integer.parseInt(no));
    
      count = pstmt.executeUpdate();
      
      System.out.println(count + "건 삭제");
      
    } catch (SQLException e) {
      System.out.println("error:" + e);
    } finally {
      try {
        if (pstmt != null) pstmt.close();
        if (conn != null) conn.close();
      } catch (SQLException e) {
        System.out.println("error:" + e);
      }
    }
  }
	
	public List<EmaillistVo> getList() {

		// 0. import java.sql.*;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<EmaillistVo> list = new ArrayList<EmaillistVo>();

		try {
		  conn = getConnection();
			
			// 3. SQL문 준비 / 바인딩 / 실행
			String query = "select no, last_name, first_name, email "
						       + "from emaillist "
					         + "order by no desc" ;
			pstmt = conn.prepareStatement(query);
			
			rs = pstmt.executeQuery();
			// 4.결과처리
			while(rs.next()) {
				int no = rs.getInt("no");
				String lastName = rs.getString("last_name");
				String firstName = rs.getString("first_name");
				String email = rs.getString("email");
				
				EmaillistVo vo = new EmaillistVo(no, lastName, firstName, email);
				list.add(vo);
			}
			
			
		} catch (SQLException e) {
			System.out.println("error:" + e);
		} finally {
			// 5. 자원정리
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				System.out.println("error:" + e);
			}

		}

		return list;
	}

}

 

  • EmailistVo.java
package helloJSP;

public class EmaillistVo {

	private int no;
	private String lastName;
	private String firstName;
	private String email;

	
	public EmaillistVo() {}

	public EmaillistVo(int no, String lastName, String firstName, String email) {
		this.no = no;
		this.lastName = lastName;
		this.firstName = firstName;
		this.email = email;
	}

	public EmaillistVo(String lastName, String firstName, String email) {
		this.lastName = lastName;
		this.firstName = firstName;
		this.email = email;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "EmaillistVo [no=" + no + ", lastName=" + lastName + ", firstName=" + firstName + ", email=" + email
				+ "]";
	}
}

 


  • 모델2 방식 예제 (guestbook)
  • list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="helloJSP.GuestbookVo"%>
<%@ page import="helloJSP.GuestBookDaoImpl"%>
<%@ page import="java.util.List"%>

<% 
	GuestBookDaoImpl Impl = new GuestBookDaoImpl();
	List<GuestbookVo> list = Impl.getList();
	System.out.println(list.toString());
%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>방명록</title>
</head>
<body>
	<form action="add.jsp" method=post>
	<table border=1 width=500>
		<tr>
			<td>이름</td><td><input type="text" name="name"></td>
			<td>비밀번호</td><td><input type="password" name="pass"></td>
		</tr>
		<tr>
			<td colspan=4><textarea name="content" cols=60 rows=5></textarea></td>
		</tr>
		<tr>
			<td colspan=4 align=right><input type="submit" VALUE=" 확인 "></td>
		</tr>
	</table>
	</form>
	<br/>

	<% 
		for(GuestbookVo vo: list){
	%>
	<table width=510 border=1>
		<tr>
			<td><%= vo.getNo() %></td>
			<td><%= vo.getName() %></td>
			<td><%= vo.getDate() %></td>
			<td><a href="deleteForm.jsp?no=<%= vo.getNo()%>&name=<%= vo.getName()%>" >삭제</a></td>
		</tr>
		<tr>
			<td colspan=4><%= vo.getContent() %></td>
		</tr>
	</table>
        <br/>
	<% 
		}
	%>
</body>
</html>

 

  • add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ page import="helloJSP.GuestbookDao"%>
<%@ page import="helloJSP.GuestbookVo"%>
<%@ page import="helloJSP.GuestBookDaoImpl"%>
<%@ page import="java.time.LocalDate" %>
<%@ page import="java.time.ZoneId" %>

<%
	request.setCharacterEncoding("UTF-8");
	String name = request.getParameter("name");
	String password = request.getParameter("pass");
	String content = request.getParameter("content");
	/* String date = request.getParameter("content"); */
	
	GuestbookVo vo = new GuestbookVo(name, password, content);
	
	GuestBookDaoImpl Impl = new GuestBookDaoImpl();
	Impl.insert(vo);
	
	response.sendRedirect("list.jsp");
%>

 

  • deleteform.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>방명록</title>
</head>
<body>
	<form method="post" action="delete.jsp?no=<%=request.getParameter("no") %>">
	<input type="hidden" name="id" value="<%=request.getParameter("name")%>">
	<table>
		<tr>
			<td>비밀번호</td>
			<td><input type="password" name="password"></td>
			<td><input type="submit" value="삭제"></td>
			<td><a href="list.jsp">확인</a></td>
		</tr>
	</table>
	</form>
</body>
</html>

 

  • delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ page import="helloJSP.GuestbookDao"%>
<%@ page import="helloJSP.GuestbookVo"%>
<%@ page import="helloJSP.GuestBookDaoImpl" %>

<% 
	request.setCharacterEncoding("UTF-8");
	int no = Integer.parseInt(request.getParameter("no"));
	String name = request.getParameter("id");
	String password = request.getParameter("password");
	
	//out.println(no);
	
  	GuestBookDaoImpl Impl = new GuestBookDaoImpl();
  	
  	GuestbookVo vo = new GuestbookVo(no, name, password);
  	//System.out.println(vo);
	Impl.delete(vo);
  
	response.sendRedirect("list.jsp");
%>

 

  • GusestBookDao.java (interface)
package helloJSP;

import java.sql.Connection;
import java.util.List;

import helloJSP.GuestbookVo;


public interface GuestbookDao {
	
	public List<GuestbookVo> getList();

	public int insert(GuestbookVo vo);

	public int delete(GuestbookVo vo);

}

 

  • GuestBookDaoImpl.java
package helloJSP;

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

public class GuestBookDaoImpl implements GuestbookDao {
	private Connection getConnection() throws SQLException {
	       Connection conn = null;
	       try {
	         Class.forName("oracle.jdbc.driver.OracleDriver");
	         String dburl = "jdbc:oracle:thin:@localhost:1521:xe";
	         conn = DriverManager.getConnection(dburl, "webdb", "1234");
	       } catch (ClassNotFoundException e) {
	         System.err.println("JDBC 드라이버 로드 실패!");
	       }
	       return conn;
	   }
	
	@Override
	public int insert(GuestbookVo vo) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		int count=0;
		
		try {
			conn = getConnection();
			
			System.out.println(vo.getPassword());
			
			String query = " insert into guestbook values (seq_guestbook_no.nextval, ?, ?, ?, sysdate) ";
			pstmt = conn.prepareStatement(query);
			
			pstmt.setString(1, vo.getName());
			pstmt.setString(2, vo.getPassword());
			pstmt.setString(3, vo.getContent());
//			pstmt.setString(4, vo.getDate());
			
			count = pstmt.executeUpdate();
			
			System.out.println(count + "건 등록");
			
		} catch (SQLException e) {
			System.out.println("error:" + e);
		} finally {
			try {
				if (pstmt != null) pstmt.close();
				if (conn != null) conn.close();
			} catch (SQLException e) {
				System.out.println("error:" + e);
			}
		}
		return count;
	}
	
	
	@Override
	public List<GuestbookVo> getList(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<GuestbookVo> list = new ArrayList<GuestbookVo>();

		try {
		  conn = getConnection();
			
			// 3. SQL문 준비 / 바인딩 / 실행
			String query = " select * from guestbook order by reg_date desc";
			pstmt = conn.prepareStatement(query);
			
			rs = pstmt.executeQuery();
			// 4.결과처리
			while(rs.next()) {
				int no = rs.getInt("no");
				String name = rs.getString("name");
				String content = rs.getString("content");
				String date = rs.getString("REG_DATE");
				
				GuestbookVo vo = new GuestbookVo(no, name, content, date);
				list.add(vo);
			}
			
			
		} catch (SQLException e) {
			System.out.println("error:" + e);
		} finally {
			// 5. 자원정리
			try {
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				System.out.println("error:" + e);
			}

		}

		return list;
	}

	@Override
	public int delete(GuestbookVo vo) {
		Connection conn = null;
	    PreparedStatement pstmt = null;
	    int count = 0 ;
	    
	    try {
	      conn = getConnection();
	      System.out.println(vo.getName());
	      System.out.println(vo.getPassword());
	      
	      String query ="delete from guestbook where \"name\" = ? and \"password\" = ? ";
	      pstmt = conn.prepareStatement(query); 
	      
//	      pstmt.setInt(1, vo.getNo());
	      pstmt.setString(1, vo.getName());
	      pstmt.setString(2, vo.getPassword());
	      
	      
	      count = pstmt.executeUpdate();
	      
	      System.out.println(count + "건 삭제");
	      
	    } catch (SQLException e) {
	      System.out.println("error:" + e);
	    } finally {
	      try {
	        if (pstmt != null) pstmt.close();
	        if (conn != null) conn.close();
	      } catch (SQLException e) {
	        System.out.println("error:" + e);
	      }
	    }
	    return count;
	}
}

 

  • GuestBookVo.java
package helloJSP;

public class GuestbookVo {

	private int no;
	private String name;
	private String password;
	private String content;
	private String date;
	
	public GuestbookVo() {}
	
	public GuestbookVo(int no, String name, String password, String content, String date) {
		this.no = no;
		this.name = name;
		this.password = password;
		this.content = content;
		this.date = date;
	}

	public GuestbookVo(int no, String name, String content, String date) {
		this.no = no;
		this.name = name;
		this.content = content;
		this.date = date;
	}
	
	public GuestbookVo(String name, String password, String content, String date) {
		this.name = name;
		this.password = password;
		this.content = content;
		this.date = date;
	}
	
	public GuestbookVo(int no, String name, String password) {
		this.no = no;
		this.name = name;
		this.password = password;
	}
	
	public GuestbookVo(String name, String password, String content) {
		this.name = name;
		this.password = password;
		this.content = content;
	}
	

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getName() {
		return name;
	}

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

	public String getPassword() {
		return password;
	}

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

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
	public String getDate() {
		return date;
	}
	
	public void setDate(String date) {
		this.date = date; 
	}
	

	@Override
	public String toString() {
		return "GuestbookVo [no=" + no + ", name=" + name + ", password=" + password + ", content=" + content + "]";
	}
}
profile

Devlog

@덩이

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그