1.  JSP/Servlet 의 내장 객체

 내장 객체

리턴 타입(Return Type) 

설명 

request 

javax.servlet.http.HttpServletRequest 

웹 브라우저의 요청 정보를 저장하고 있는 객체 

response 

javax.servlet.http.HttpServletResponse 

웹 브라우저의 요청에 대한 응답 정보를 저장하고 있는 객체 

out 

javax.servlet.jsp.jsp.jspWriter 

JSP 페이지에 출력할 내용을 가지고 있는 출력 스트림 객체이다. 

session 

javax.servlet.http.HttpSession 

하나의 웹 브라우저의 정보를 유지하기 위한 세션 정보를 저장하고 있는 객체 

application 

javax.servlet.ServletContext 

웹 어플리케이션 Context의 정보를 저장하고 있는 객체 

pageContext 

javax.servlet.jsp.PageContext 

JSP 페이지에 대한 정보를 저장하고 있는 객체 

page 

java.lang.Object 

JSP 페이지를 구현한  자바 클래스 객체

config 

javax.servlet.ServletConfig 

JSP 페이지에 대한 설정 정보를 저장하고 있는 객체 

exception 

java.lang.Throwable 

JSP 페이지서 예외가 발생한 경우에 사용되는 객체 



・request

   -  요청시마다 만들어지는 객체

   -  attribute, parameter를 가지고 있음

 

  

・application

   -  톰캣구동시 webcontext별로 만들어지는 객체

   -  톰캣중지시 없어지는 객체 LifeScope가 가장 길다

   -  서블릿 API ver 정보, 실제 경로

   -  parameter, attribute 가지고 있음

 


・pageContext

   -  현재 실행중인 JSP의 정보를 담고있다. 

   -  가장 일찍 객체가 사라진다 LifeScope가 가장 짧다

   -  JAVA SE : Object, Class, File

   -  JAVA EE : ServletContext, PageContext, EJBContext

   -  attribute 가지고 있음

   -  out / request / response / session 정보 얻는게 가능

      ex) pageContext.getOut();

            pageContext.getRequest();

            pageContext.getSession();


・session

   -  클라이언트별로 만들어지는 객체

   -  클라이언트 단에서 새로운 요청이 있어도 Session객체에 속성들은 그대로 유지된다.

   -  attribute가 있음



2. attribute와 parameter 메소드의 차이점


ⅰ. 간단히 요약


-파라미터에는 String만 사용가능

-애트리뷰트에는 다른 String외에 Object, Array 등 다양한 데이터 입력이 가능

-파라미터는 request에만 저장이 가능하고, 애트리뷰트는 session, context 등에도 저장이 가능

-애트리뷰트가 좀더 유연함

-파라미터는 HTML(클라이언트)의 form 데이터 전송시 key/value 쌍으로 사용된다.



ⅱ. 자세한 비교


・ 속성이란?

  - ServletContext, HttpServletRequest, HttpServletResponse, HttpSession 객체 중 하나에 설정해 놓는 객체(Object)이다. 



・ 내장 객체의 속성(attribute)과 관련된 메소드(http://hyeonstorage.tistory.com/78 [개발이 하고 싶어요])

메소드 

리턴 타입 

설명 

setAttribute(String key, Object value)

void 

해당 내장 객체의 속성(attribute)값을 설정하는 메소드로, 속성명에 해당하는 key 매개 변수에, 속성값에 해당하는 value 매개 변수의 값을 지정한다. 

 getAttributeNames()

java.util.Enumeration 

해당 내장 객체의 속성(attribute)명을 읽어오는 메소드로, 모든 속성의 이름을 얻어낸다. 

getAttribute(String key) 

Object 

해당 내장 객체의 속성(attribute)명을 읽어오는 메소드로, 주어진 key 매개 변수에 해당하는 속성명의 값을 얻어낸다. 

removeAttribute(String key)

void 

해당 내장 객체의 속성(attribute)을 제거하는 메소드로, 주어진 key 매개 변수에 해당하는 속성명을 제거한다. 



・  속성과 파라미터의 차이점

 

속성 

 파라미터 

 타입

 Application / Context

 Request

 Session 

 Application / context 초기화 파라미터

 Request 파라미터

 Servlet 초기화 파라미터

 설정 메소드

 setAttribute(String name, Object value)

 애플리케이션과 서블릿의 초기화 파라미터 값은 런타임 시 설정할 수 없습니다. 오로지 DD(Web.xml)에서만 가능합니다. 기억나죠? (Request 파라미터를 가지고, 좀 어렵긴 하지만 쿼리 스트링을 설정할 수 있습니다. 

 리턴 타입

 Object

 String

 참조 메소드

 getAttribute(String name)

 getInitParameter(String name) 





출처: http://yooooooo7se.tistory.com/63 [Learning Machine]





















・클라이언트가 request를 보내면 was에서 자동으로 request객체를 생성 -> requestDispatcher을 사용하면 동일한 request객체를 다른 컴포넌트로 포워딩함









・RequestObj.javs의 request객체와 포워딩한 노드인 despacher.jsp의 reuqest 객체 값이 동일한 것을 볼 수 있음









・클라이언트가 request를 보내면 was에서 자동으로 request객체를 생성 -> httpServleResponse을 사용하면 새로운 request객체를 다른 컴포넌트로 포워딩함. 때문에 기존 request객체와 새로운 곳으로 포워딩한 request객체가 다름






・RequestObj.java의 request객체와 포워딩한 노드인 redirect.jsp의 reuqest 객체 값이 상이한것을 볼 수 있음











・/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


















・압축 해제 후 톰캣 라이브러리 안에 넣어주면 된다. 












































・조건연산자가 특이하므로 주목하도록 한다. ${(1>2)?1:2} -> 1>2가 참이면1, 거짓이면 2







































































・expression language는 객체에 값설정은 불가능하고, 설정된 값들을 가져오는 기능만을 할 수 있는 것 같다.


























・노드js 의 경우에는 외부 모듈이 npm install을 통해 node_modules 폴더에 쌓인다. 일반적으로 자바에서는 어디에 외부 모듈을 저장하는 건지 궁금했는데 WEB-INF안에 저장한다.


・eclipse에서 build path를 보면 알겠지만, eclipse의 web프로젝트는 톰캣의 jar들을 포함한다. 따라서, tomcat 내부에도 내가 실행한 프로젝트 패스들이 생성되어 있다.(C:\apache_tomcat\apache-tomcat-8.5.23\wtpwebapps\helloworld)







・이클립스에서 웹프로젝트를 위한 파일을 구성하면, WebContent에 html,jsp 등의 파일을 구성하는데, WebContent직하에 MultipartRequest모듈 실행시 업로드된 파일이 담기게될 디렉토리 패스를 만들어 놓는다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="22fileUpload.jsp" method="post" enctype="multipart/form-data">
        파일 : <input type="file" name="file">
        <input type="submit" value="file uplaod">
    </form>
 
</body>
</html>
cs

・클라이언트 단에서 MultipartRequest을 사용하기 위해선, enctype="multipart/form-data">을 적어주는 것이 필수적이다.

또한 <input type="file" 을 명기하여 file업로드를 위한 input태그임을 알린다.



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
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import ="java.util.*"%>
<%@ page import ="com.oreilly.servlet.multipart.DefaultFileRenamePolicy" %>
<%@ page import ="com.oreilly.servlet.MultipartRequest" %>
<!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>
 
<%
    String path = request.getRealPath("uploadedFiles");
    System.out.println(path);
    int size = 1024 * 1024 * 10;
    String file="";
    String oriFile="";
 
    try{
        MultipartRequest multi = new MultipartRequest(request,path,size,"EUC-KR",new DefaultFileRenamePolicy());
        
        Enumeration files = multi.getFileNames();
        String str =(String)files.nextElement();
 
        file = multi.getFilesystemName(str);
        oriFile = multi.getOriginalFileName(str);
        
        System.out.println(file);
        System.out.println(oriFile);
    }
    catch(Exception e){
        e.printStackTrace();
    }
 
 
%>
 
upload success!!
 
<a href="22fileUpload.html">돌아가기</a>
 
</body>
</html>
cs

MultipartRequest multi = new MultipartRequest(request,path,size,"EUC-KR",new DefaultFileRenamePolicy());

로 파일 업로딩은 끝이 난다.

multi.getOriginalFileName(str);은 유저가 업로드한 파일명을 그대로 얻어오는 함수이다.

multi.getFilesystemName(str);은 MultipartRequest모듈 내ㅣ부에서 업로드한 파일명을 얻어오는 함수이다. 

getFilesystemName는 유저가 같은명의 파일을 업로드시 MultipartRequest모듈은 내부로직으로 겹치는 파일명을 수정해주는데, 이 수정된 파일명을 얻어온다.











-DTO : 데이터 접속에 필요한 변수와 데이터를 일반적인 변수에 할당하지 않고 DTO 클래스를 통해서 일괄 관리하는 것







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
package com.javalec.daotoex;
 
public class MemberDTO {
 
    private String name;
    private String id;
    private String pw;
    private String phone1;
    private String phone2;
    private String phone3;
    private String gender;
    
    public MemberDTO(String name, String id, String pw, String phone1, String phone2, String phone3, String gender) {
        this.name = name;
        this.id = id;
        this.pw = pw;
        this.phone1 = phone1;
        this.phone2 = phone2;
        this.phone3 = phone3;
        this.gender = gender;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    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 getPhone1() {
        return phone1;
    }
 
    public void setPhone1(String phone1) {
        this.phone1 = phone1;
    }
 
    public String getPhone2() {
        return phone2;
    }
 
    public void setPhone2(String phone2) {
        this.phone2 = phone2;
    }
 
    public String getPhone3() {
        return phone3;
    }
 
    public void setPhone3(String phone3) {
        this.phone3 = phone3;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
    
}
 
cs









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
package com.javalec.daotoex;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
 
public class MemberDAO {
 
    private String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private String uid = "scott";
    private String upw = "tiger";
    
    
    public MemberDAO() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public ArrayList<MemberDTO> memberSelect() {
        
        ArrayList<MemberDTO> dtos = new ArrayList<MemberDTO>();
        
        Connection con =null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            con = DriverManager.getConnection(url, uid, upw);
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from member");
            
            while (rs.next()) {
                String name = rs.getString("name");
                String id = rs.getString("id");
                String pw = rs.getString("pw");
                String phone1 = rs.getString("phone1");
                String phone2 = rs.getString("phone2");
                String phone3 = rs.getString("phone3");
                String gender = rs.getString("gender");
                
                MemberDTO dto = new MemberDTO(name, id, pw, phone1, phone2, phone3, gender);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(con != null) con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return dtos;
    }
    
}
 
cs










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
<%@page import="com.javalec.daotoex.MemberDTO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.javalec.daotoex.MemberDAO"%>
<%@ 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>
 
    <%
        MemberDAO memberDAO = new MemberDAO();
        ArrayList<MemberDTO> dtos = memberDAO.memberSelect();
        
        for(int i=0; i<dtos.size(); i++) {
            MemberDTO dto = dtos.get(i);
            String name = dto.getName();
            String id = dto.getId();
            String pw = dto.getPw();
            String phone = dto.getPhone1() + " - "+ dto.getPhone2() + " - " + dto.getPhone3();
            String gender = dto.getGender();
            
            out.println("이름 : " + name + ", 아이디 : " + id + ", 비밀번호 : " + pw + ", 연락처 : " + phone + ",  성별 : " + gender + "<br />" );
        }
        
    %>
 
</body>
</html>
cs







-쿼리문을 작성할 때, 쿼리에 변수를 넣는 과정이 귀찮기 때문에 그것을 편리하게 하기 위해 나온 객체


1
2
3
4
5
6
7
String id = "abc"
String pw = "123"
String name = "홍길동"
String phone ="0103323123"
 
String query = "insert into member(id,pw,name,phone) values("'+id+"','"+pw+"','"+name+"','"+phone+"')"
cs





1
2
3
4
5
6
7
8
9
10
String id = "abc"
String pw = "123"
String name = "홍길동"
String phone ="0103323123"
 
String query = "insert into member(id,pw,name,phone) values(?,?,?,?)"
preparedStatement.setString(1,id)
preparedStatement.setString(2,pw)
preparedStatement.setString(3,name)
preparedStatement.setString(4,phone)
cs



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
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%!
        Connection connection;
        PreparedStatement preparedStatement;
        ResultSet resultSet;
    
        String driver = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String uid = "scott";
        String upw = "tiger";
    %>
<!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>
 
    <%
        try{
            
            Class.forName(driver);
            connection = DriverManager.getConnection(url, uid, upw);
            int n;
            String query = "insert into memberforpre (id, pw, name, phone) values (?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(query);
            
            preparedStatement.setString(1"abc");
            preparedStatement.setString(2"123");
            preparedStatement.setString(3"홍길동");
            preparedStatement.setString(4"010-1234-5678");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"def");
            preparedStatement.setString(2"456");
            preparedStatement.setString(3"홍길자");
            preparedStatement.setString(4"010-9012-3456");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"ghi");
            preparedStatement.setString(2"789");
            preparedStatement.setString(3"홍길순");
            preparedStatement.setString(4"010-7890-1234");
            n = preparedStatement.executeUpdate();
            
            preparedStatement.setString(1"AAA");
            preparedStatement.setString(2"111");
            preparedStatement.setString(3"이길동");
            preparedStatement.setString(4"010-1234-1111");
            n = preparedStatement.executeUpdate();
            
            if(n == 1) {
                out.println("insert success");
            } else { 
                out.println("insert fail");
            }
            
        } catch(Exception e) {
                e.printStackTrace();
        } finally {
            try{
                if(resultSet != null) resultSet.close();
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch(Exception e){}
        }
    %>
    
    <br />
    <a href="memberDateView.jsp">회원정보 보기</a>
 
</body>
</html>
cs















-동시에 클라이언트로부터 database connection 객체 생성 요청이 들어오와 그때그때 connection객체를 생성하면 데이터 베이스에 부하가 걸리기 때문에, 일단 커넥션풀에 connection객체를 미리 만들어놓고, 클라이언트로부터 요청이 들어오면 하나하나 배당하는 로직

-DBCP는 자바에서 존재하는 것이 아니고 tomcat WAS에 미리 만들어 놓으라고 요청하는 것. 따라서  tomcat컨테이너가  connection을 미리 만들어 놓도록 context.xml에 설정해둔다.
















-context.xml을 수정한 후에는 톰캣에 싱크를 하기 위해서 위 스크린샷의 버튼을 눌러준다.






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
package com.javalec.daotoex;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class MemberDAO {

//원래 일반적인 ODBC접속이라면  Class.forName("oracle.jdbc.driver.OracleDriver");로 디비 접속을 하지만, 톰캣커넥션 풀에 이미 //커넥션 객체를 쌓아놓은 경우라면 디비 접속하는 부분은 필요 없어진다.
//아래의 빨간색 폰트들은 커넥션풀을 이용하면서 삭제된 코드들이고, 파랑색 폰트들은 새로 추가된 코드들이다. 
 
//    private String url = "jdbc:oracle:thin:@localhost:1521:xe";
//    private String uid = "scott";
//    private String upw = "tiger";
    
    private DataSource dataSource;
    
    public MemberDAO() {
   

    
//        try {
//            Class.forName("oracle.jdbc.driver.OracleDriver");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            Context context = new InitialContext(); dataSource = (DataSource)context.lookup("java:comp/env/jdbc/Oracle11g");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public ArrayList<MemberDTO> memberSelect() {
        
        ArrayList<MemberDTO> dtos = new ArrayList<MemberDTO>();
        
        Connection con =null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
//          con = DriverManager.getConnection(url, uid, upw);
            con = dataSource.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("select * from member");
            
            while (rs.next()) {
                String name = rs.getString("name");
                String id = rs.getString("id");
                String pw = rs.getString("pw");
                String phone1 = rs.getString("phone1");
                String phone2 = rs.getString("phone2");
                String phone3 = rs.getString("phone3");
                String gender = rs.getString("gender");
                
                MemberDTO dto = new MemberDTO(name, id, pw, phone1, phone2, phone3, gender);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(con != null) con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return dtos;
    }
    
}
 
cs










19join.html

19JoinFail.html

19JoinSuccess.html

ProcessJoin19.java

19login.html

19loginFail.html

19loginSuccess.html

19loginSuccess.jsp

19processLogin.jsp

19processLogout.jsp


loginLogic.zip





19join.html

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
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="ProcessJoin" method="post">
    이름 : <input type="text" name="name" size="10"><br/>
    아이디 : <input type="text" name="id" size="10"><br/>
    비밀번호 : <input type="password" name="pw" size="10"><br/>
    전화번호 : <select name="ph1">
        <option value="010">010</option>
        <option value="010">011</option>
        <option value="010">019</option>
        <option value="010">017</option>
    </select> -
    <input type="text" name="ph2" size="4"> - <input type="text" name="ph3" size="4"><br/>
    성별 : 남<input type="radio" name="gender" value ="남" size="5">여<input type="radio" name="gender" value ="여" size="5"><br/>
    <input type="submit" value="회원가입"><input type="reset" value="취소">
    
    
    </form>
 
 
</body>
</html>
cs




ProcessJoin19.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
package com.javalec.ex;
 
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
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 ProcessJoin19
 */
@WebServlet("/ProcessJoin")
public class ProcessJoin19 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    
    private Connection conn;
    private Statement stmt;
    private String query;
    private String driver,url,uId,uPw,name,id,pw,phoneNum,gender;
    
//    String driver = "oracle.jdbc.driver.OracleDriver";
//    String url = "jdbc:oracle:thin:@localhost:1521:xe";
//    String uId ="Java_webApp";
//    String uPw ="kk5dd0ss2";
 
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessJoin19() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        actionDo(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        actionDo(request, response);
    }
 
    private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("EUC-KR");
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:xe";
        uId ="Java_webApp";
        uPw ="kk5dd0ss2";
        
        name = request.getParameter("name");
        id = request.getParameter("id");
        pw = request.getParameter("pw");
        phoneNum = request.getParameter("ph1"+ "-" +request.getParameter("ph2"+ "-" + request.getParameter("ph3");
        gender = request.getParameter("gender");
        
        query = "insert into member values('"
                +name+"', '"
                +id+"', '"
                +pw+"', '"
                +phoneNum+"', '"
                +gender+"')";
 
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uId, uPw);
            stmt = conn.createStatement();
            int i = stmt.executeUpdate(query);
            if(i==1){
                System.out.println("insert success");
                response.sendRedirect("19JoinSuccess.html");
            }
            else{
                System.out.println("insert fail");
                response.sendRedirect("19JoinFail.html");
            }
            
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("insert fail");
            response.sendRedirect("19JoinFail.html");
            
        }
        finally{
            try{
                if(stmt!=null)stmt.close();
                if(conn!=null)conn.close();
            }
            catch(Exception e){
                e.printStackTrace();
                
            }
        }
    
    }
}
 
cs



19JoinFail.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    회원가입에 실패하셨습니다 다시 작성해주세요.
    <a href="19join.html">
        <h2>돌아가기</h2>
    </a>
</body>
</html>
cs




19JoinSuccess.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    회원가입에 성공했습니다. 로그인 페이지로 이동해주세요.
    <a href="19login.html">
        <h2>로그인 페이지로 이동</h2>
    </a>
</body>
</html>
cs




19login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <form action="19processLogin.jsp" method="post">
        아이디 : <input type="text" name="id" size="10"><br/>
        비밀번호 : <input type="password" name="pw" size="10"><br/>
        <input type="submit" value="로그인"><input type="reset" value="취소">
    </form>
    
    <form action="19join.html" method="get">
        <input type="submit" value="회원가입">
    </form>
    
</body>
</html>
cs




19processLogin.jsp

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
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
 
<%!
    Connection conn;
    Statement stmt;
    ResultSet rSet;
    
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uId ="Java_webApp";
    String uPw ="kk5dd0ss2";
    String id,pw,query,result;
%>
 
 
<!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>
    
    <!-- Driver load -->
    <%
    
        request.setCharacterEncoding("EUC-KR");
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:xe";
        uId ="Java_webApp";
        uPw ="kk5dd0ss2";
        
        id = request.getParameter("id");
        pw = request.getParameter("pw");
        
        query = "select pw from member where id='" + id + "'";
        System.out.println(query);
        
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, uId, uPw);
            stmt = conn.createStatement();
            rSet = stmt.executeQuery(query);
            
            while(rSet.next()){
                result = rSet.getString("pw");
            }
            
            if(result == null){
                System.out.println("login fail");
                response.sendRedirect("19loginFail.html");
            }
            else{
                System.out.println("pw : "+pw);
                System.out.println("result : "+result);
                if(result.equals(pw)){
                    session.setAttribute("id", id);
                    session.setAttribute("pw", pw);
                    System.out.println("login success");
                    response.sendRedirect("19loginSuccess.jsp");
                }
                else{
                    System.out.println("password is not matched");
                    response.sendRedirect("19loginFail.html");
                }
            }
    
            
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("login fail");
            response.sendRedirect("19loginFail.html");
            
        }
        finally{
            try{
                if(rSet!=null){rSet.close();}
                if(stmt!=null){stmt.close();}
                if(conn!=null){conn.close();}
            }
            catch(Exception e){
                e.printStackTrace();
                
            }
        }
        
        
    
    
    
    
    %>
 
</body>
</html>
cs



 session.setAttribute("id", id);session.setAttribute("pw", pw);

:세션에 로그인 정보를 주고 다른 로그인 페이지에서 유저가 로그인을 한 후 접속하는건지 그렇지 않은지를 세션을 통해 관리한다. 만약.로그인을 성공하지 않고도 login성공화면을 get으로 받으려고 한다면 문제가 되기때문이다.



19loginSuccess.jsp


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
<%@ 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>
 
    <%
    try{
        Object id = session.getAttribute("id");
        Object pw = session.getAttribute("pw");
        
        out.println(id.toString() + "님 접속을 환영합니다");%>
        <form action="19processLogout.jsp" method="post">
            <input type="submit" value="로그아웃">
        </form>
    <%}
    catch(NullPointerException e){
        e.printStackTrace();
        out.println("올바른 경로로 엑세스해주세요");    
    }
 
 
    %>
 
</body>
</html>
cs


 Object id = session.getAttribute("id");Object pw = session.getAttribute("pw");

:세션을 통해 로그인 정보를 받고, 세션에 있는 로그인 정보와 사용자의 정보가 같을시에만 페이지를 렌더링하는 로직을 취할 수 있을 것이다. 


19processLogout.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ 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>
    <%
    session.invalidate();
    %>
    
    logout되었습니다.
</body>
</html>
cs


session.invalidate();

: 세션 객체에 저장되어 있는 세션을 제거한다.















+ Recent posts