본문 바로가기

IT&코딩/자바 프로젝트

자바 프로젝트 8일차 - MVC 1 (mvcStudent)

728x90
반응형

■ student package (소스)

 

□ StudentDTO.java

 

package student;

public class StudentDTO {
	private String id;
	private String name;
	private String cname;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	
}

 

□ StudentDAO.java

 

package student;

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

public class StudentDAO {
	Connection con;
	PreparedStatement ps;
	ResultSet rs;
	
	String url, user, pass;
	
	public StudentDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
		url = "jdbc:oracle:thin:@localhost:1521:xe";
		user = "web01";
		pass = "web01";
		
	}
	
	public int insertStudent(StudentDTO dto)
				throws SQLException {
		try {
			con = DriverManager.getConnection(url, user, pass);
			String sql = "insert into student values(?, ?, ?)";
			ps = con.prepareStatement(sql);
			ps.setString(1, dto.getId());
			ps.setString(2, dto.getName());
			ps.setString(3, dto.getCname());
			int res = ps.executeUpdate();
			return res;
		}finally {
			if (ps != null) ps.close();
			if (con != null) con.close();
		}
	
	}
	
	public List<StudentDTO> listStudent() throws SQLException {
		try {
			con = DriverManager.getConnection(url, user, pass);
			String sql = "select * from student";
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			List<StudentDTO> list = makeList(rs);
			return list;
		}finally {
			if (rs != null) rs.close();
			if (ps != null) ps.close();
			if (con != null) con.close();
		}
	}
	
	public int deleteStudent(String id) throws SQLException {
		try {
			con = DriverManager.getConnection(url, user, pass);
			String sql = "delete from student where id = ?";
			ps = con.prepareStatement(sql);
			ps.setString(1, id);
			int res = ps.executeUpdate();
			return res;
		}finally {
			if (ps != null) ps.close();
			if (con != null) con.close();
		}
	}
	
	public List<StudentDTO> findStudent(String cname) throws SQLException{
		try {
			con = DriverManager.getConnection(url, user, pass);
			String sql = "select * from student where cname = ?";
			ps = con.prepareStatement(sql);
			ps.setString(1, cname);
			rs = ps.executeQuery();
			List<StudentDTO> list = makeList(rs);
			return list;
		}finally {
			if (rs != null) rs.close();
			if (ps != null) ps.close();
			if (con != null) con.close();
		}
	}
	
	protected List<StudentDTO> 
							makeList(ResultSet rs) throws SQLException {
		List<StudentDTO> list = new ArrayList<>();
		while(rs.next()) {
			StudentDTO dto = new StudentDTO();
			dto.setId(rs.getString("id"));
			dto.setName(rs.getString("name"));
			dto.setCname(rs.getString("cname"));
			list.add(dto);
		}
		return list;
	}
}

 

□ CommandIf.java (인터페이스)

 

package student;

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

public interface CommandIf {
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp);
}

 

□ CommandFactory.java (팩토리)

 

package student;

public class CommandFactory {
	
	private CommandFactory() {} // private 생성자를 하나 만든다.
	
	private static CommandFactory instance = new CommandFactory();
	// static을 이용해서 메모리에 올린다. 하지만 아직도 외부에서는 쓸 수 없다.
	
	public static CommandFactory getInstance() {
		return instance;
	}
	
	public CommandIf createCommand(String cmd) {
		
		CommandIf cmdIf = null;
		
		if (cmd.equals("student")) {
			cmdIf = new StudentCommand();
		}else if (cmd.equals("list")) {
			cmdIf = new ListCommand();	
		}else if (cmd.equals("insert")) {
			cmdIf = new InsertCommand();
		}else if (cmd.equals("delete")) {
			cmdIf = new DeleteCommand();
		}else if (cmd.equals("find")) {
			cmdIf = new FindCommand();
		}
		
		return cmdIf;
	}
	
	
}

// 팩토리패턴을 이용하는 클래스는 싱글톤 객체를 이용하여 만들어준다.
// 클래스를 한번만 객체로 만들 수 있다 (싱글톤)

 

□ StudentServlet.java

 

package student;

import java.io.IOException;
import java.util.*;

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

public class StudentServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		
		String cmd = req.getParameter("command");
		
		CommandFactory factory = CommandFactory.getInstance();
		CommandIf cmdIf = factory.createCommand(cmd);
		
		String nextPage = (String)cmdIf.processCommand(req, resp);
		RequestDispatcher view = req.getRequestDispatcher(nextPage);
		view.forward(req, resp);
	}
	
}

 

□ StudentCommand.java

 

package student;

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

public class StudentCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp) {
		
		return "WEB-INF/student/student.jsp";
	}

}

 

□ InsertCommand.java

 

package student;

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

public class InsertCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp) {
		
		StudentDTO dto = new StudentDTO();
		dto.setId(req.getParameter("id"));
		dto.setName(req.getParameter("name"));
		dto.setCname(req.getParameter("cname"));
		
		StudentDAO dao = new StudentDAO();
		
		try {
			int res = dao.insertStudent(dto);
			if(res > 0) {
				req.setAttribute("msg", "학생등록 성공! 학생목록페이지로 이동합니다.");
				req.setAttribute("url", "student.do?command=list");
			} else {
				req.setAttribute("msg", "학생등록 실패! 학생관리페이지로 이동합니다.");
				req.setAttribute("url", "student.do?command=student");
			}
		} catch(Exception e) {
			System.out.println("insert 실행 중 오류 발생");
			e.printStackTrace();
			req.setAttribute("msg", "DB 서버 오류 발생! 관리자에게 문의하세요.");
			req.setAttribute("url", "student.do?command=student");
		}
		return "message.jsp";
	}

}

 

□ DeleteCommand.java

 

package student;

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

public class DeleteCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		
		StudentDAO dao = new StudentDAO();
		
		try{
			int res = dao.deleteStudent(id);
			
			if(res > 0) {
				req.setAttribute("msg", "학생삭제 성공! 학생목록페이지로 이동합니다.");
				req.setAttribute("url", "student.do?command=list");
			} else {
				req.setAttribute("msg", "학생삭제 실패! 학생관리페이지로 이동합니다.");
				req.setAttribute("url", "student.do?command=student");
			}
		} catch(Exception e) {
			System.out.println("delete 실행 중 오류 발생");
			e.printStackTrace();
			req.setAttribute("msg", "DB 서버 오류 발생! 관리자에게 문의하세요.");
			req.setAttribute("url", "student.do?command=student");
		}
		
		return "message.jsp";
	}

}

 

□ FindCommand.java

 

package student;

import java.util.List;

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

public class FindCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp) {
		
		String cname = req.getParameter("cname");
		StudentDAO dao = new StudentDAO();
		
		try{
			List<StudentDTO> list = dao.findStudent(cname);
			req.setAttribute("listStudent", list);
			return "WEB-INF/student/list.jsp";
		} catch(Exception e) {
			System.out.println("find 실행 중 오류 발생!!");
			e.printStackTrace();
			req.setAttribute("msg", "DB서버 오류 발생!! 관리자에게 문의하세요");
			req.setAttribute("url", "student.do?command=student");
			return "message.jsp";
		}

	}

}

 

□ ListCommand.java

 

package student;

import java.util.List;

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

public class ListCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp) {
		
		StudentDAO dao = new StudentDAO();
		try {
			List<StudentDTO> list = dao.listStudent();
			req.setAttribute("listStudent", list);
			return "WEB-INF/student/list.jsp";  
		} catch(Exception e) {
			System.out.println("list 실행 중 오류 발생");
			e.printStackTrace();
			req.setAttribute("msg", "DB 서버 오류 발생! 관리자에게 문의하세요.");
			req.setAttribute("url", "student.do?command=student");
			return "message.jsp";
		}
	}
}

 


 

■ view 페이지

 

□ index.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
    
<!-- index.jsp -->
<html>
<head>
	<title>mvc 학생관리</title>
</head>
<body>
	<h1 align="center">MVC로 연습하는 학생관리 프로그램</h1>
	<ul>	
		<li><a href="student.do?command=student">학생관리페이지로 이동</a>
	</ul>
</body>
</html>

 

□ message.jsp

 

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

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

<script type="text/javascript">
	alert("<%=msg%>")
	location.href="<%=url%>"
</script>

 

□ /WEB-INF/student/student.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- student.jsp -->
<html>
<head>
	<title>학생관리</title>
</head>
<body>
	<div align="center">
		<hr color="green" width="300">
		<h2>학 생 등 록 페 이 지</h2>
		<hr color="green" width="300">
		<form name="f" action="student.do" method="post">
			<input type="hidden" name="command" value="insert"/>
			<table border="1">
				<tr>
					<td align="center">
						아이디 : <input type="text" name="id"><br>
						학생명 : <input type="text" name="name"><br>
						학급명 : <input type="text" name="cname"><br>
						<input type="submit" value="전송">
						<input type="reset" value="취소">
					</td>
				</tr>			
			</table>
		</form>
		<hr color="green" width="300">
		<h2>학 생 삭 제 페 이 지</h2>
		<hr color="green" width="300">
		<form name="f" action="student.do" method="post">
			<input type="hidden" name="command" value="delete"/>
			<table border="1">
				<tr>
					<td align="center">
						아이디 : <input type="text" name="id">
						<input type="submit" value="삭제">
					</td>
				</tr>			
			</table>
		</form>
		<hr color="green" width="300">
		<h2>학 생 찾 기 페 이 지</h2>
		<hr color="green" width="300">
		<form name="f" action="student.do" method="post">
			<input type="hidden" name="command" value="find"/>
			<table border="1">
				<tr>
					<td align="center">
						학급명 : <input type="text" name="cname">
						<input type="submit" value="찾기">
					</td>
				</tr>			
			</table>
		</form>
		<hr color="green" width="300">
		<h2>학 생 목 록 페 이 지</h2>
		<hr color="green" width="300">
		<form name="f" action="student.do" method="post">
			<input type="hidden" name="command" value="list"/>
			<table border="1">
				<tr>
					<td align="center">
						<input type="submit" value="학생목록페이지로 이동">
					</td>
				</tr>			
			</table>
		</form>
	</div>
</body>
</html>

 

□ WEB-INF/student/list.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"  import="java.util.*, student.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- list.jsp -->
<html>
<head>
	<title>학생목록</title>
</head>
<body>
	<div align="center">
		<hr color="green" width="300">
		<h2>학 생 목 록 페 이 지</h2>
		<hr color="green" width="300">
		<table border="1" width="500">
			<tr>
				<th>아이디</th>
				<th>학생명</th>
				<th>학급명</th>
			</tr>
		<c:if test="${empty listStudent}">
			<tr>
				<td colspan="3">등록된 학생이 없습니다.</td>
			</tr>	
		</c:if>
		<c:forEach var="dto" items="${listStudent }">
			<tr>
				<td>${dto.id }</td>
				<td>${dto.name }</td>
				<td>${dto.cname }</td>
			</tr>	
		</c:forEach>
		
		</table>
	</div>
</body>
</html>

 

□ web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
	<servlet-name>student</servlet-name>
	<servlet-class>student.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>student</servlet-name>
	<url-pattern>/student.do</url-pattern>
</servlet-mapping>
</web-app>

 

728x90
반응형