IT story/JSP

[Jsp 강의] L03ServletMethod

jason719 2016. 10. 27. 15:43

L03ServletMethod

    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
    24
    25
    <%@ 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>Servlet의 Method를 알아보자</title>
    </head>
    <body>
        <h1>Servlet 동작 원리</h1>
        <h3>
            <a href="L01CallMethod.jsp">doGet과 doPost를 호출해보자</a>
        </h3>
        <hr>
        <h3>
            <a href="L02SignupForm.jsp">회원가입 form을 만들어보자</a>
        </h3>
        <hr>
        <h3>
            <a href="L03LifeCycle">서블릿의 생명주기 확인</a>
        </h3>
        <hr>
            
    </body>
    </html>
    cs

    L01CallMethod.jsp을 통해 doGet과 doPost를 호출해보자

    예제1 L01CallMethod.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
    <%@ 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>L01MethodServlet을 호출하자</title>
    </head>
    <body>
        <h1>L01MethodServlet을 doGet 방식으로 호출하기</h1>
        <h3>
            <a href="./method?id=jsp&pass=1234">id와 pass를 doGet()에 전달</a>
        </h3>
        <hr>
        <h1>L01MethodServlet을 doPost 방식으로 호출하기</h1>
        <form action="./method" method="post">
            <p>
                <label for="userId">ID: </label>
                <input id="userId" name="id" value="jsp" type="text">
                <%-- 
                input tag는 파라미터를 post 방식으로 전달하는 도구
                name 속성은 파라미터의 key값이다. form tag 안에서 유일한 값.
                
                id속성은 html page에 유일한 값(pk와 비슷)
                for 속성은 label에만 존재하고 어떤 input의 label인지 표시함.
                 --%>
            </p>
            <p>
                <label for="userPw">PW: </label>
                <input id="userPw" name="pass" value="1234" type="password">
            </p>
            <input type="submit" value="제출">
            <%-- input type="submit" 을 서브밋 버튼이라 부른다.
                form tag 내부에 있고 누르면 form tag 내부의 파라미터를 
                action 위치에 제출 --%>
        </form>
    </body>
    </html>
    cs

    예제2 L01MethodServlet.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
    package com.jsp.method;
     
    import java.io.IOException;
    import java.io.PrintWriter;
     
    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("/method")
    public class L01MethodServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        String id, pass;
           
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //id&pass 님 환영합니다.
           response.setContentType("text/html; charset=utf-8"); 
           id = request.getParameter("id");
           pass = request.getParameter("pass");
           PrintWriter out = response.getWriter();
           out.print("<html><body>");
           out.print("<h1 style='color:blue'>doGet()"+id+"/"+pass+"님 환영합니다. </h1>");
           out.print("</body></html>");
        }
        
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html; charset=utf-8"); 
            id = request.getParameter("id");
            pass = request.getParameter("pass");
            PrintWriter out = response.getWriter();
            out.print("<html><body>");
            out.print("<h1 style='color:red'>doPost()"+id+"/"+pass+"님 환영합니다. </h1>");
            out.print("</body></html>");
        }
     
    }
     
    cs

    L02SignupForm.jsp을 통해 회원가입 form을 만들어보자

    예제3 L02SignupForm.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
    <%@ 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>회원가입 form</title>
    </head>
    <body>
        <h1>L02SignupServlet(/signup)에 회원가입 양식을 제출하자</h1>
        <form action="./signup" method="post">
            <p>
                <label>아이디:</label>
                <input type="text" name="id" value="jsp">
            </p>
            <p>
                <label>비밀번호:</label>
                <input type="password" name="pwd" value="admin1234">
            </p>
            <p>
                <label>성별:</label>
                <input type="radio" name="gender" value="0" checked="checked">남자
                <input type="radio" name="gender" value="1" >여자
                <%--radio는 name 속성의 값이 같은 것은 하나만 선택할 수 있다. --%>
            </p>
            <p>
                <label>직업</label> <br />
                <input type="checkbox" name="job" value="학생" checked="checked">학생
                <input type="checkbox" name="job" value="공무원">공무원
                <input type="checkbox" name="job" value="군인">군인 <br />
                <input type="checkbox" name="job" value="강사">강사
                <input type="checkbox" name="job" value="서비스업">서비스업
                <input type="checkbox" name="job" value="프로그래머" checked="checked">프로그래머        
            </p>
            <%--checkbox는 중복 선택이 가능, 파라미터 배열로 넘어간다.
                getParameterValues로 받는다. --%>
            <button type="submit">제출</button>
        </form>
    </body>
    </html>

    cs


    예제4 L02SignupServlet

    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
    package com.jsp.method;
     
    import java.io.IOException;
    import java.io.PrintWriter;
     
     
    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("/signup")
    public class L02SignupServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        String id, pwd, gender;
        String[] jobs;
       ;
        
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
        }
     
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            //post로 통신할 때 parameter가 header 정보에 담기면서 charset이 바뀐다.
            //그래서 request 객체에 characterEncording을 바꿔야한다.
            response.setContentType("text/html; charset=utf-8");
            id = request.getParameter("id");
            pwd = request.getParameter("pwd");
            gender = request.getParameter("gender");
            jobs = request.getParameterValues("job");
            PrintWriter out = response.getWriter();
            
            if(gender != null){
                int int_gender = Integer.parseInt(gender);
                if(int_gender==0){
                    gender = "남자";
                }else{
                    gender = "여자";
                }
            }
            
            //내가 한 것.
            out.print("<html><body>");
            out.print("<p>");
            out.print("<label>아이디 : "+id+"</label><br />");
            out.print("<label>비밀번호 : "+pwd+"</label><br />");
            out.print("<label>성별 : "+gender+"</label><br />");
            out.print("<label>직업 : ");
            for(int i=0; i<jobs.length; i++){
                out.print(jobs[i]+"\t");
            }        
            out.print("</label></p>");
            
            //先生から        
            out.print("<h1>당신이 입력한 정보는</h1><hr>");
            out.print("<p><b>아이디: </b>"+id+"</p>");
            out.print("<p><strong>비밀번호: </strong>"+pwd+"</p>");
            out.print("성별: "+gender+"</p><br />");
            out.print("<b>직업: </b>");
            if(jobs == null){
                out.println("<p>선택한 항목이 없습니다.</p>");
            }else{
                for(int i=0; i<jobs.length; i++){
                    if((i)==(jobs.length-1)){
                        out.print(jobs[i]);
                    }else{
                        out.print(jobs[i]+", ");
                    }
                }
                out.print("</p)");
            }
            out.print("</body></html>");
        }
    }
     
    cs

    L03LifeCycle을 통해 서블릿의 생명주기를 확인 하자

    L03LifeCycle.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
    package com.jsp.method;
     
    import java.io.IOException;
     
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    import javax.servlet.ServletConfig;
    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("/L03LifeCycle")
    public class L03LifeCycle extends HttpServlet {
        private static final long serialVersionUID = 1L;
        int initCount = 1//init() 함수 호출시 증가
        int doGetCount = 1//doGet() 함수 호출시 증가    
        int destroyCount = 1//destroy() 함수 호출시 증가
        int serviceCount = 1//service() 함수 호출시 증가
        
        @Override
        public void init(ServletConfig config) throws ServletException {
            System.out.println("init()호출"+(initCount++));
        }//서버가 시작되고 페이지를 최초 호출할 때 한 번 호출된다.
     
        /*@Override
        public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
            System.out.println("service()호출"+(serviceCount++));
            //doGet의 요청을 빼돌려서 매번 호출된다.
        }*/
     
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.getWriter().append("doGet()call"+(doGetCount++));
            //service가 있으면 요청이 빼앗긴다.
        }
        
        @Override
        public void destroy() {
            System.out.println("destroy()호출"+(destroyCount++));
            //서버가 종료될 때 한 번 호출된다.
        }
        
        @PostConstruct
        private void initPostConstruct() {
            System.out.println("initPostConstruct() 호출");
            //init() 호출되기 전에 한 번 호출된다.
        }
        
        @PreDestroy
        private void preDestroy() {
            System.out.println("preDestroy() 호출");
            //destroy()가 호출되고 한 번 호출된다.
        }
    }
     
    cs


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

[Jsp 강의] L05Redirect  (0) 2016.10.27
[Jsp 강의] L04JSP  (0) 2016.10.27
[Jsp 강의] L02HelloJsp  (0) 2016.10.27
[Jsp 강의] L01HelloServlet  (0) 2016.10.27
L09 Sub Query  (0) 2016.10.22