・/Hello는 서블릿 이름 혹은 Hello.java 서블릿 파일을 Hello로 맵핑한 경우이다.


・실제 현장에서는 확장자 패턴을 많이 사용한다. Hello.do를 치건 world.do를 치건 모든 .do의 요청은 *.do 요청을 받는 서블릿으로 이동한다. 그리고 나서  *.do 서블릿 내부안에서 from이 어디 인지에 따라 다른 로직을 수행한다.







・다양한 요청을 각각의 서블릿에서 각자 받는 것이 아니라 일단 프론트 컨트롤러에서 모든 요청을 받은후, 프론트컨트롤러에서 각자의 서블릿으로 뿌려준다. 비유하자면 이런거다. 한 명한명의 고객의 자신의 니즈가 필요한 회사의 부서에 직접전화를 하면 중간에 관리해주는 사람이 없으니까 여러모로 비효율 적이다. 때문에 중간에 콜센터를 두고 콜센터에서 부서로 고객을 뿌려주는 것이다.




frontControllerEx.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <a href="insert.do">insert</a>
    <hr />
    <a href="http://localhost:8181<%=request.getContextPath()%>/update.do">update</a>
    <hr />
    <a href="http://localhost:8181/jsp_25_2_ex1_frontex/select.do">select</a>
    <hr />
    <a href="<%=request.getContextPath()%>/delete.do">delete</a>
 
</body>
</html>
cs



FrontCon.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.javalec.ex;
 
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 FrontCon
 */
@WebServlet("*.do")
public class FrontCon extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontCon() {
        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");
        actionDo(request, response);
    }
 
    /**
     * @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");
        actionDo(request, response);
    }
    
    private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        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);
 
        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("----------------");
        }
    }
 
}
 
cs


@WebServlet("*.do"): .do 로 들어오는 모든 요청을 FrontCon.java에서 받는다.

request.getContextPath(): /jsp_25_2_ex1_frontex를 나타낸다. 컨텍스트패스란, eclipse에서 클래스의 이름을 의미한다. 만약 helloworld라는  웹프로젝트 클래스를 생성하면, localhost:8090/helloworld 라는 uri가 jsp, html, servlet으로 갈 수 있는 루트 패스가 되는데 이를 컨택스트패스라고 한다.

request.getRequestURI(): /jsp_25_2_ex1_frontex/insert.do를 나타낸다. 클아이언트에서 요청한 URI를 그대로 나타내어 준다.  











・그런데 만약 위 예에서처럼 프론트 컨트롤에서 모든 로직을 처리하면, 한 서블릿 파일이 너무 길어지므로 보기 힘들다. 따라서, 

요청이 들어옴 -> 프론트 컨트롤러에서 받음 -> 프론트 컨트롤러에서 처리하지 않고 로직을 처리할 각각의 서블릿으로 보냄


jsp_25_3_ex1_commex.zip



・memersAll.jsp에서 요청 들어옴 -> FrontCon.java가 받음 -> 요청의 처리를 dao클래스에 위임 -> dao클래스에서 처리한 리턴값을 FrontCon.java에서 받음 -> memersAll.jsp에게 전달



memersAll.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <a href="membersAll.do">전체 회원 정보 조회</a>
 
</body>
</html>
cs



FrontCon.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.javalec.ex;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
 
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 FrontCon
 */
@WebServlet("*.do")
public class FrontCon extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontCon() {
        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");
        actionDo(request, response);
    }
 
    /**
     * @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");
        actionDo(request, response);
    }
    
    private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("actionDo");
        
        String uri = request.getRequestURI();
        String conPath = request.getContextPath();
        String command = uri.substring(conPath.length());
        
        if(command.equals("/membersAll.do")) {
            response.setContentType("text/html; charset=EUC-KR");
            PrintWriter writer = response.getWriter();
            writer.println("<html><head></head><body>");
            
            Service service = new MembersAllService();
            ArrayList<MemberDto> dtos = service.execute(request, response);
            
            for (int i = 0; i < dtos.size(); i++) {
                MemberDto dto = dtos.get(i);
                String id = dto.getId();
                String pw = dto.getPw();
                String name = dto.getName();
                String eMail = dto.geteMail();
                Timestamp rDate = dto.getrDate();
                String address = dto.getAddress();
                
                writer.println(id + ", " + pw + ", " + name + ", " + eMail + ", " + rDate.toLocalDateTime() + ", " + address + "<hr />");
            }
            
            writer.println("</body></html>");
        }
        
    }
 
}
 
cs




MembersAllService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.javalec.ex;
 
import java.util.ArrayList;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class MembersAllService implements Service {
    
    public MembersAllService() {
        // TODO Auto-generated constructor stub
    }
 
    @Override
    public ArrayList<MemberDto> execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        MemberDao dao = MemberDao.getInstance();
        return dao.membersAll();
    }
 
}
 
cs




Service.java(인터페이스)

1
2
3
4
5
6
7
8
9
10
11
package com.javalec.ex;
 
import java.util.ArrayList;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public interface Service {
    public ArrayList<MemberDto> execute(HttpServletRequest request, HttpServletResponse response);
}
 
cs



MemberDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package com.javalec.ex;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class MemberDao {
 
    private static MemberDao instance = new MemberDao();
    
    private MemberDao() {
    }
    
    public static MemberDao getInstance(){
        return instance;
    }
    
    public int insertMember(MemberDto dto) {
        int ri = 0;
        
        Connection connection = null;
        PreparedStatement pstmt = null;
        String query = "insert into members values (?,?,?,?,?,?)";
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            pstmt.setString(1, dto.getId());
            pstmt.setString(2, dto.getPw());
            pstmt.setString(3, dto.getName());
            pstmt.setString(4, dto.geteMail());
            pstmt.setTimestamp(5, dto.getrDate());
            pstmt.setString(6, dto.getAddress());
            pstmt.executeUpdate();
            ri = 1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(pstmt != null) pstmt.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return ri;
    }
    
    public int confirmId(String id) {
        int ri = 0;
        
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet set = null;
        String query = "select id from members where id = ?";
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            pstmt.setString(1, id);
            set = pstmt.executeQuery();
            if(set.next()){
                ri = 1;
            } else {
                ri = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                set.close();
                pstmt.close();
                connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return ri;
    }
    
    public int userCheck( String id, String pw) {
        int ri = 0;
        String dbPw;
        
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet set = null;
        String query = "select pw from members where id = ?";
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            pstmt.setString(1, id);
            set = pstmt.executeQuery();
            
            if(set.next()) {
                dbPw = set.getString("pw");
                if(dbPw.equals(pw)) {
                    ri = 1;        // 로그인 Ok
                } else {
                    ri = 0;        // 비번 X
                }
            } else {
                ri = -1;        // 회원 X    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                set.close();
                pstmt.close();
                connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return ri;
    }
    
    public MemberDto getMember(String id) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet set = null;
        String query = "select * from members where id = ?";
        MemberDto dto = null;
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            pstmt.setString(1, id);
            set = pstmt.executeQuery();
            
            if(set.next()) {
                dto = new MemberDto();
                dto.setId(set.getString("id"));
                dto.setPw(set.getString("pw"));
                dto.setName(set.getString("name"));
                dto.seteMail(set.getString("eMail"));
                dto.setrDate(set.getTimestamp("rDate"));
                dto.setAddress(set.getString("address"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                set.close();
                pstmt.close();
                connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return dto;
        
    }
    
    public int updateMember(MemberDto dto) {
        int ri = 0;
        
        Connection connection = null;
        PreparedStatement pstmt = null;
        String query = "update members set pw=?, eMail=?, address=? where id=?";
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            pstmt.setString(1, dto.getPw());
            pstmt.setString(2, dto.geteMail());
            pstmt.setString(3, dto.getAddress());
            pstmt.setString(4, dto.getId());
            ri = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return ri;
    }
    
    public ArrayList<MemberDto> membersAll() {
        
        ArrayList<MemberDto> dtos = new ArrayList<MemberDto>();
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String query = "select * from members";
        
        try {
            connection = getConnection();
            pstmt = connection.prepareStatement(query);
            rs = pstmt.executeQuery();
            
            System.out.println("============");
            while (rs.next()) {
                MemberDto dto = new MemberDto();
                dto.setId(rs.getString("id"));
                dto.setPw(rs.getString("pw"));
                dto.setName(rs.getString("name"));
                dto.seteMail(rs.getString("eMail"));
                dto.setrDate(rs.getTimestamp("rDate"));
                dto.setAddress(rs.getString("address"));
                dtos.add(dto);
            }
            System.out.println("--------------------------");
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                pstmt.close();
                connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return dtos;
        
    }
    
    private Connection getConnection() {
        
        Context context = null;
        DataSource dataSource = null;
        Connection connection = null;
        try {
            context = new InitialContext();
            dataSource = (DataSource)context.lookup("java:comp/env/jdbc/Oracle11g");
            connection = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return connection;
    }
    
}
 
cs





MemberDto.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.javalec.ex;
 
import java.sql.Timestamp;
 
public class MemberDto {
 
    private String id;
    private String pw;
    private String name;
    private String eMail;
    private Timestamp rDate;
    private String address;
    
//    public MemberDto(String id, String pw, String name, String eMail, Timestamp rDate, String address) {
//        this.id = id;
//        this.pw = pw;
//        this.name = name;
//        this.eMail = eMail;
//        this.rDate = rDate;
//        this.address = address;
//    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getPw() {
        return pw;
    }
 
    public void setPw(String pw) {
        this.pw = pw;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String geteMail() {
        return eMail;
    }
 
    public void seteMail(String eMail) {
        this.eMail = eMail;
    }
 
    public Timestamp getrDate() {
        return rDate;
    }
 
    public void setrDate(Timestamp rDate) {
        this.rDate = rDate;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
    
}
 
cs


+ Recent posts