Command 패턴
[url-pattern]
- 디렉터리 패턴
. 디렉토리 형태로 서버의 해당 컴포넌트를 찾아서 실행하는 패턴
url-mapping servlet url 맵핑
http://localhost:8080/jsp_Ex_3/abc -------------> /abc 서블릿
http://localhost:8080/jsp_Ex_3/ddd -------------> /ddd 서블릿
디렉토리를 찾아가는 형태
- 확장자 패턴
. 확장자 형태로 서버의 해당 컴포넌트를 찾아서 실행하는 패턴
http://localhost:8080/jsp_Ex_2/aaa.do-----------> +----------+
|*.do 서블릿 |
http://localhost:8080/jsp_Ex_3/bbb.do-----------> +----------+
do로끝나는 확장자 패턴이있으면 do가 있는 서블릿을 찾아간다.aaa.do도 bbb.do도
*.do 서블릿을 찾아간다. 한놈을 찾아간다. 한곳에 모이는 거죠.aaa.do가 실행되면
서블릿에서 내부적으로 어느곳에서 왔는지를 파악을 합니다. aaa.do에서 왔으면 내부적으로
aaa.do에 맞는코드를 실행한다.
[FrontController 패턴]
클라이언트 요청1 --------> 요청1 서블릿-------->
클라이언트 요청2 ---------> 요청2 서블릿-------->
클라이언트 요청3 ---------> 요청3 서블릿--------> DAO
클라이언트 요청4 ---------> 요청4 서블릿-------->
각각의 요청.각각의패턴이있다. 각 요청에 대한 해당 서블릿이 있다.
각 서블릿에서 처리해줘야 될 것이 있다면
위에 있는 거는 일반적인 방법:각 요청을 만들면 각 요청마다 중복되는 코드
가 있어 비효율적이다.관리상 그렇게 좋은 패턴이 아니다.
클라이언트 요청1-------->
클라이언트 요청2--------> 모든 요청을 직접
클라이언트 요청3--------> 처리하는 서블릿--------> DAO
클라이언트 요청4-------->
[Command 패턴]
interface 구현
클라이언트 요청1--------> ---> 요청1 클래스
클라이언트 요청2--------> 모든 요청을 직접 ---> 요청2 클래스
클라이언트 요청3--------> 처리하지 않는 서블릿 ---> 요청3 클래스 -----> DAO
클라이언트 요청4--------> ---> 요청4 클래스
studentAll.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="studentAll.do"> 전체 학생 조회 </a>
</body>
</html>
FrontController.java
package com.test.ex;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
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;
/**
* Servlet implementation class FrontController
*/
@WebServlet("*.do")
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FrontController() {
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
System.out.println("doGet");
try {
actionDo(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doPost");
try {
actionDo(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
System.out.println("actionDo");
String uri = request.getRequestURI();
System.out.println("uri :" + uri);
String conPath=request.getContextPath();
System.out.println("conPath : "+ conPath);
String command = uri.substring(conPath.length());
System.out.println("command :"+command);
String result = null;
if(command.equals("/insert.do")) {
System.out.println("insert");
System.out.println("------------------");
}else if(command.equals("/update.do")) {
System.out.println("update");
System.out.println("------------------");
}else if(command.equals("/select.do")) {
System.out.println("select");
System.out.println("------------------");
}else if(command.equals("/delete.do")) {
System.out.println("delete");
System.out.println("------------------");
}else if(command.equals("/studentAll.do")) {
System.out.println("스트던트올닷두");
/*result = "/printStudent.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(result);
dispatcher.forward(request, response);*/
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<html><head></head><body>");
Service svc = new StudentAllService();
ArrayList<StudentDTO> sdtos = svc.execute(request, response);
for(int i = 0; i < sdtos.size(); i++) {
StudentDTO sdto = sdtos.get(i);
String no = sdto.getHakbun();
String pw = sdto.getPw();
String name = sdto.getName();
String hp = sdto.getHp();
writer.println(no + "," + pw + "," + name + "," + hp + "<hr/>");
}
writer.println("</body></html>");
}
}
}
Service.java
package com.test.ex;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Service {
public ArrayList <StudentDTO> execute(HttpServletRequest request, HttpServletResponse response) throws SQLException;
}
StudentAllService.java
package com.test.ex;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentAllService implements Service {
public StudentAllService() {
}
public ArrayList<StudentDTO> execute(HttpServletRequest request, HttpServletResponse response) throws SQLException {
StudentDAO sdao = new StudentDAO();
return sdao.select();
}
}
StudentDAO.java
package com.test.ex;
import java.sql.*;
import java.util.*;
//DAO : DB에 접근하기위한 오브젝트(객체)
public class StudentDAO {
Connection dbconn;
PreparedStatement ps;
ResultSet rs;
String url ="jdbc:oracle:thin:@localhost:1521:orcl";
String uid ="scott", pwd = "1234";
public StudentDAO(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
dbconn = DriverManager.getConnection(url,uid,pwd);
System.out.println("데이터베이스 연결!!");
} catch (Exception e) {
e.printStackTrace();
}
}// 생성자
public int insertStudent(StudentDTO sdto) throws SQLException{
String hakbun = sdto.getHakbun();
String pw = sdto.getPw();
String name = sdto.getName();
String hp = sdto.getHp();
int n = this.insertStudent(hakbun, pw, name, hp);
return n;
}
public int insertStudent(String hakbun, String pw, String name, String hp)
throws SQLException{
try{
String sql="insert into student values(?,?,?,?)";
ps=dbconn.prepareStatement(sql);
ps.setString(1, hakbun);
ps.setString(2, pw);
ps.setString(3, name);
ps.setString(4, hp);
int n = ps.executeUpdate();
return n;
}finally{
if(ps !=null) ps.close();
if(dbconn !=null) dbconn.close();
}
}
public ArrayList<StudentDTO> select() throws SQLException{
ArrayList <StudentDTO> sdtos = new ArrayList<StudentDTO>();
try{
String sql = "select * from student";
ps = dbconn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
StudentDTO sdto = new StudentDTO();
sdto.setHakbun(rs.getString("no"));
sdto.setPw(rs.getString("pw"));
sdto.setName(rs.getString("name"));
sdto.setHp(rs.getString("hp"));
sdtos.add(sdto);
}
}finally{
if(rs !=null) rs.close();
if(ps !=null) ps.close();
if(dbconn !=null) dbconn.close();
}
return sdtos;
}
public StudentDTO[] findSt(String name) throws SQLException{
try{
String sql="select * from student where name=?";
ps=dbconn.prepareStatement(sql);
ps.setString(1, name);
rs = ps.executeQuery();
StudentDTO stArray[] = createArray(rs);
return stArray;
}finally{
if(rs !=null) rs.close();
if(ps!=null) ps.close();
if(dbconn !=null) dbconn.close();
}
}
public StudentDTO[] createArray(ResultSet rs) throws SQLException{
Vector<StudentDTO> v = new Vector<StudentDTO>();
while(rs.next()){
String hakbun=rs.getString(1);
String pw = rs.getString(2);
String name = rs.getString(3);
String hp = rs.getString(4);
StudentDTO rowSt = new StudentDTO(hakbun, pw, name, hp);
v.add(rowSt);
}//while End
int vSize = v.size();
StudentDTO stArray[] = new StudentDTO[vSize];
v.copyInto(stArray); //벡터에 저장된 데이터를 stArray배열 객체에 복사
return stArray;
}
public int delStudent(String name) throws SQLException{
try{
String sql="delete from student where name=?";
ps=dbconn.prepareStatement(sql);
ps.setString(1, name);
int n = ps.executeUpdate();
return n;
}finally{
if(ps !=null) ps.close();
if(dbconn !=null) dbconn.close();
}
}
}
StudentDTO.java
package com.test.ex;
// Data Transfer Object (VO: Value Object)
public class StudentDTO {
private String hakbun;
private String pw;
private String name;
private String hp;
public StudentDTO(){
System.out.println("Student() 객체 생성");
}
public StudentDTO(String hakbun, String pw, String name, String hp){
this.hakbun=hakbun;
this.pw=pw;
this.name=name;
this.hp=hp;
}
//get 계열
public String getHakbun() {
return hakbun;
}
public String getPw() {
return pw;
}
public String getName() {
return name;
}
public String getHp() {
return hp;
}
//set 계열
public void setHakbun(String hakbun) {
System.out.println("setHakbun() :"+hakbun);
this.hakbun = hakbun;
}
public void setPw(String pw) {
System.out.println("setPw() :"+pw);
this.pw = pw;
}
public void setName(String name) {
System.out.println("setName() :"+name);
this.name = name;
}
public void setHp(String hp) {
System.out.println("setHp() :"+hp);
this.hp = hp;
}
}
printStudent.jsp
<%@page import="com.test.ex.StudentDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.test.ex.StudentAllService"%>
<%@page import="com.test.ex.Service"%>
<%@page import="java.io.PrintWriter"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<html><head></head><body>");
Service svc = new StudentAllService();
ArrayList<StudentDTO> sdtos = svc.execute(request, response);
for(int i = 0; i < sdtos.size(); i++) {
StudentDTO sdto = sdtos.get(i);
String no = sdto.getHakbun();
String pw = sdto.getPw();
String name = sdto.getName();
String hp = sdto.getHp();
writer.println(no + "," + pw + "," + name + "," + hp + "<hr/>");
}
writer.println("</body></html>");
%>
<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html> -->