IT story/JSP

[Jsp 강의] L06Forward

jason719 2016. 10. 27. 16:02

L06Forward

로그인 과정을 통해 Forward에 대해 알아보자

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//Client가 요청한 URL
RequestDispatcher dispatcher = request.getRequestDispatcher("./L01LoginForm.jsp");
dispatcher.forward(request, response);
//브라우저 상단 URL은 변동이 없다. -> 가로채서 변동시켰기 때문에
//1.parameter를 post타입으로 전달하기 위해-> Object타입으로 전달 가능
//    -> header 정보로 파라미터를 넘길 수 있다.
//    -> get방식: 문자를 URL이 byte타입으로 변형해서 넘기는데 이때 인코딩이 "8859_1" 이라
//    ->              문자열의 인코딩을 변형해야한다. -> 한글깨짐이 심하다.
//2.request 객체와 response 객체가 유지된다.
//    -> dispatcher.forward에 그대로 담아서 넘기기 때문에
%>
</body>
</html>
cs


예제 1. L01LoginForm.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>servlet을 이용해서 로그인을 성공하자</title>
</head>
<body>
    <h1>로그인 form</h1>
    <%-- 제출한 파라미터와 db에서 가져온 id와 pw를 L02LoginController.java에서 검사 
        같으면 true를 파라미터로 L03LoginResult.jsp로 보낸다. -> 성공 메시지
        실패하면 L01LoginForm.jsp 페이지로 와서 id와 pwd가 틀렸습니다. 메시지 출력 
        
        이때 L03LoginResult.jsp 페이지에 id를 출력하기 위해 forward 방식을 이동해라.
        
         L03LoginResult.jsp에서 파라미터 true가 없으면 접근할 수 없도록해라
         (강제로 L01LoginForm.jsp)로 이동
         
         이전 페이지의 request 객체를 유지하려면 forward 방식
         유지할 필요가 없으면 redirect 방식을 사용
    --%>
    <%     String login = request.getParameter("msg");
        if(login != null){
    %>
        <h3 style="color: red"><%=login %></h3>
    <%        
        }
    %>
    
    <form action="./loginCtrl" method="post">
        <p>
            <label>아이디:</label>
            <input type="text" name="id" value="jsp">
        </p>
        <p>
            <label>비밀번호:</label>
            <input type="password" name="pwd" value="admin1234">
        </p>
        <button type="submit">제출</button>
    </form>
    
</body>
</html>
cs


예제 2. L02SignupController.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
package com.jsp.controller;
 
import java.io.IOException;
 
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;
 
 
@WebServlet("/loginCtrl")
public class L02SignupController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String db_id = "jsp";
        String db_pwd= "admin1234";
        
        
        response.setContentType("text/html; charset=utf-8");
        String id = request.getParameter("id");
        String pwd = request.getParameter("pwd");
        System.out.println("id: "+id+" //pwd: "+pwd);
        if(id.equals(db_id) && pwd.equals(db_pwd)){
            request.setAttribute("login"1); //Object type으로 넘어온다
            RequestDispatcher dispatcher = request.getRequestDispatcher("./L03LoginResult.jsp");
            dispatcher.forward(request, response);
            //login이 1이면 true, 0이면 false
 
        }else{
            response.sendRedirect("./L01LoginForm.jsp?msg=login failed");
        }
    }
 
}
 
cs


예제 3. L03LoginResult.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=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>login 성공 페이지</title>
</head>
<body>
    <%-- parameter login이 오지 않으면 이 페이지에 접근할 수 없다.
          이때 login은 세션 또는 쿠키 대신이다.
          세션 or 쿠키는 브라우저가 유지하고 있는 파라미터이다. --%>
          <%
          //Object는 모든 class의 부모이기 때문에 casting으로 형변환 가능
          Object login = request.getAttribute("login");
          boolean access = false;
          if(login != null){
              if((int)login == 1){
                  access = true;
              }
          }
          if(!access){
              response.sendRedirect("./L01LoginForm.jsp?msg=access failed");
          }
          %>
    <h1><%=request.getParameter("id"%>로그인 성공 페이지</h1>
    
</body>
</html>
cs


'IT story > JSP' 카테고리의 다른 글

[Jsp 강의] L08Session  (0) 2016.10.27
[Jsp 강의] L07Template  (0) 2016.10.27
[Jsp 강의] L05Redirect  (0) 2016.10.27
[Jsp 강의] L04JSP  (0) 2016.10.27
[Jsp 강의] L03ServletMethod  (0) 2016.10.27