국비지원학원/HTML,JavaScript,jQ

88일차-JavaEE_parameter처리/페이지 이동(forward,redirect)

초코맛 2019. 3. 9. 01:08
반응형
*같은이름의 Parameter처리
  • 배열로 처리된다.
  • try{  //if(s!=null){
  • String[ ] s=request.getParameterValues("이름");//하나일지라도 getParameterValues이용
  • for ( int i=0; i<s.length; i++){ //s가 객체일때 값을 얻을수 있고
  •    s[i];
  • }//이름이 없으면 null이 떨어진다.->s가 null이면 NullPointerException 발생(생성)
  • //null : heap의 주소를 가지지 않음(객체가 아님)
  • }catch(NullPointerException e){  //}else{
  •    //예외 발생시 실행될 코드
  • }//객체가 적게 생성되는게 좋은코드라 if를 사용하는게 더 좋은코드가 된다.
  • 흐름도)
  • //checkbox에 체크를 하더라도 value가 없으면 on이 넘어간다
  • //폼태그에서 서블릿으로 데이터를 보내고 싶을때 쓰는 속성-action!
  • //method를 적지않으면 default값으로 get이 들어간다.
<!-- test_param_value.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="http://localhost:8080/servlet_prj/common/main_v190130.css"/>
<style type="text/css">
#wrap{margin:0px auto;width:800px; height:860px;}
#header{width:800px; height:140px; background:#FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;
           position: relative; }
#headerTitle{font-family: HY견고딕,고딕; font-size:35px;  font-weight:bold; text-align:center;
                /* padding-top: 35px */ position:absolute;  top:40px; left:290px; }
#container{width:800px; height:600px; }
#footer{width:800px; height:120px; }
#footerTitle{float: right; font-size:15px; padding-top:20px;  padding-right:20px; }
</style>
<!-- jQuery CDN -->
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
     $("#btnGet").click(function(){
           $("[method='get']").submit();//id가 가장 빠르지만  이름selector로도 검색 가능하다.
     });//click
     $("#btnPost").click(function(){
           $("[method='post']").submit();
     });//click
});//ready
</script>
</head>
<body>
<div id="wrap">
     <div id="header">
           <div id="headerTitle">SIST Class4</div>
     </div>
     
     <div id="container">
           <div>
                <h2>중복된 이름의 Prameter 처리 :GET방식</h2>
                <div>
                     <form action="../parameter_values"  method="get">
                     <table>
                           <tr>
                                <td><label>이름</label></td>
                                <td><input type="text"  name="name" class="inputBox"></td>
                           </tr>
                           <tr>
                                <td><label>취미</label></td>
                                <td>
                                     <input type="checkbox"  name="hobby" value="야구">야구<br/>
                                     <input type="checkbox"  name="hobby" value="댄스">댄스<br/>
                                     <input type="checkbox"  name="hobby" value="축구">축구<br/>
                                     <input type="checkbox"  name="hobby" value="흡연">흡연<br/>
                                </td>
                           </tr>
                           <tr>
                                <td colspan="2">
                                     <input type="button"  value="전송" class="btn" id="btnGet"/>                                     
                                </td>
                           </tr>
                     </table>
                     </form>
                </div>
           </div>
           
           
           <div>
                <h2>중복된 이름의 Prameter 처리 :POST방식</h2>
                <div>
                     <form action="../parameter_values"  method="post">
                     <table>
                           <tr>
                                <td><label>이름</label></td>
                                <td><input type="text"  name="name" class="inputBox"></td>
                           </tr>
                           <tr>
                                <td><label>취미</label></td>
                                <td>
                                     <input type="checkbox"  name="hobby" value="야구">야구<br/>
                                     <input type="checkbox"  name="hobby" value="댄스">댄스<br/>
                                     <input type="checkbox"  name="hobby" value="축구">축구<br/>
                                     <input type="checkbox"  name="hobby" value="흡연">흡연<br/>
                                </td>
                           </tr>
                           <tr>
                                <td colspan="2">
                                     <input type="button"  value="전송" class="btn" id="btnPost"/>                                    
                                </td>
                           </tr>
                     </table>
                     </form>
                </div>
           </div>
     </div>
     
     <div id="footer">
           <div id="footerTitle">copyright&copy; all right  reserved. class 4.</div>
     </div>
</div>
</body>
</html>
//UseWebParameterValues
package day0228;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class UseWebParameterValues extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter  out=response.getWriter();//MIME-Type잘못주면 다운로드가 된다,,
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           
           //HTML Form Control의 값 받기
           //이름이 유일한 경우 <input type="text
           String name=request.getParameter("name");
           //이름이 중복된 경우 <input type="checkbox"
           String[] hobby =request.getParameterValues("hobby");
           //인코딩이 안되면 알아볼수 없는 형태가 되고, 인코딩이  2번되면? ????로 나온다.지금은 8버전의 get방식이기 때문에 인코딩ㄴㄴㄴㄴ
           
           out.print("\t<strong>");
           out.print(name);
           out.println("</strong>님 께서 입력하신 취미는 아래와  같습니다.<br/>");
           
           out.println("\t<ul>");
           try {//체크박스가 선택된것이 없다면 hobby배열에는  null이 할당되므로 length키워드를 사용하게 되면  NullPointerException이 발생하게 된다.
                 for(int i=0;i<hobby.length; i++) {
                  out.print("\t\t<li>");
                  out.print(hobby[i]);
                  out.println("</li>");
                 }//end for
           }catch (NullPointerException npe) {
            out.println("<li>취미 없음</li>");
           }//end catch
           out.println("\t</ul>");
           out.println("\t<a  href='day0228/test_param_value.html'>뒤로</a>");
           
           
           out.write("\t\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
     }//doGet
     protected void doPost(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter  out=response.getWriter();//MIME-Type잘못주면 다운로드가 된다,,
           
           request.setCharacterEncoding("UTF-8");
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           
           //HTML Form Control의 값 받기
           //이름이 유일한 경우 <input type="text
           String name=request.getParameter("name");
           //이름이 중복된 경우 <input type="checkbox"
           String[] hobby =request.getParameterValues("hobby");
           //인코딩이 안되면 알아볼수 없는 형태가 되고, 인코딩이  2번되면? ????로 나온다.지금은 8버전의 get방식이기 때문에 인코딩ㄴㄴㄴㄴ
           
           out.print("\t<h2>POST방식의 요청 처리</h2>");
           out.print("\t<strong>");
           out.print(name);
           out.println("</strong>님 께서 입력하신 취미는 아래와  같습니다.<br/>");
           
           out.println("\t<ul>");
           if(hobby!=null) {//체크박스가 선택된것이 없다면  hobby배열에는 null이 할당되므로 length키워드를 사용하게 되면  NullPointerException이 발생하게 된다.
                 for(int i=0;i<hobby.length; i++) {
                  out.print("\t\t<li>");
                  out.print(hobby[i]);
                  out.println("</li>");
                 }//end for
           }else {
            out.println("<li>취미 없음</li>");
           }//end else
           ///////객체가 덜생성되어 if~else 추천!!///////
           out.println("\t</ul>");
           out.println("\t<a  href='day0228/test_param_value.html'>뒤로</a>");
           
           
           out.write("\t\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
     }//doPost
}//class




*servlet/JSP 페이지 이동
  • forward방식, redirect방식 두가지가 제공(구분해 사용할 줄 알아야)

-redirect
  • 응답시 페이지 이동.
  • 정상적인 요청을 한 페이지에서 비정상적인 요청이 발생한 경우 페이지를 이동할 때 사용.
  • 브라우저가 재요청을 하기 때문에 URL이 변경된다.
  • 이전에 요청한 값들을 이동한 페이지에서 사용할 수 없다.
  • 다른 site의 페이지로 이동 가능하다.
  • get방식의 이동만 허용한다. post방식은 X
  • //브라우저가 자동 재요청 하는것(M자)
  • 사용법)
    • response.sendRedirect("URL");
package day0228;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class TestRedirect extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        boolean flag=new Random().nextBoolean();
        
        if(!flag) {//비정상적인 요청이 있을 때
            response.sendRedirect("http://sist.co.kr");
            return;//비정상적인 경우에는 아랫줄의 코드가 실행되지 못하도록 막아준다.
        }//end if
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();//MIME-Type잘못주면 다운로드가 된다,,
        
          out.write("<!DOCTYPE html>\r\n");
          out.write("<html>\r\n");
          out.write("<head>\r\n");
          out.write("<meta charset=\"UTF-8\">\r\n");
          out.write("<title>Insert title here</title>\r\n");
          out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
          out.write("<style type=\"text/css\">\r\n");
          out.write("#wrap{ margin:0px auto; width:800px; height: 860px;  }\r\n");
          out.write("#header{  width:800px; height: 140px; background: #FFFFFF url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
          out.write("\t\t\tposition: relative; }\r\n");
          out.write("#headerTitle{ font-family: HY견고딕, 고딕; font-size: 30px; font-weight: bold;text-align: center;\r\n");
          out.write("\t\t\t\t\tposition: absolute; top:30px; left:290px}\r\n");
          out.write("#container{  width:800px; height: 600px; }\r\n");
          out.write("#footer{  width:800px; height: 120px; }\r\n");
          out.write("#footerTitle{ float:right; font-size: 15px; padding-top:20px; padding-right: 20px }\r\n");
          out.write("</style>\r\n");
          out.write("</head>\r\n");
          out.write("<body>\r\n");
          out.write("<div\tid=\"wrap\">\r\n");
          out.write("\t<div id=\"header\">\r\n");
          out.write("\t\t<div id=\"headerTitle\">SIST Class4</div>\r\n");
          out.write("\t</div>\r\n");
          out.write("\t<div id=\"container\">\r\n");
          
          out.println("<img src='common/images/img.png'/><br/>");
          out.println("정상적인 경우 서비스할 내용");
          
          out.write("\t\r\n");
          out.write("\t</div>\r\n");
          out.write("\t<div id=\"footer\">\r\n");
          out.write("\t\t<div id=\"footerTitle\">copyright&copy; all right reserved. class 4 </div>\r\n");
          out.write("\t</div>\r\n");
          out.write("</div>\r\n");
          out.write("\r\n");
          out.write("</body>\r\n");
          out.write("</html>\r\n");
          
          System.out.println(flag+"실행되었음.");
    }//doGet

}//class




-forward
  • 데이터 처리 페이지와 화면디자인 페이지를 구분하여 작성할 때 (업무구분)
  • MVC pattern에서 주로 사용
  • 코드의 복잡도를 낮출 수 있다.
  • 브라우저는 페이지의 이동을 모른다.(URL이 변경되지 않는다.)
  • 이동한 페이지로 값을 전송할 수 있다.(객체도!)
  • requestDispatcher 인터페이스를 사용.
  • 내 서버 안에서만 이동가능하다(데이터를 주고받아야 함으로)(∏자로 이동)
  • 이동한 페이지에서 이전페이지의 parameter/넘겨준 값을 받을 수 있다.

  • 문법)
    • 0.이동할 페이지로 값을 보내기 위해 값(Object)을 설정
    • request.setAttribute("이름",값);//여러개 사용 가능
    • .....
    • 1.이동할 페이지의 설정 (URI-servlet_prj/test/URL은 처음부터 test까지)
    • RequestDispatcher rd=request.getRequestDispatcher("URI");
    • 2.이동
    • rd.farward(request,response);
    • ///이동할 페이지에서 값 받기
    • request.getAttribute("이름")=>값이 Object으로 나온다.(casting해 사용)
package day0228;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ForwardA extends HttpServlet {
     //데이터 처리코드에 집중하기 위해  만들어짐.(화면디자인x-데이터 처리만!)
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           
           //처리된 데이터
           String[]  nameArr={"박","김","최","이"};
           
           List<String> list=new ArrayList<String>();
           list.add("PC방 관리 프로그램");
           list.add("영화관 예매 프로그램");
           list.add("개발자 구인구직 프로그램");
           
           //1. 처리된 데이터를 이동한 페이지로 보내기 위해  요청객체에 속성으로 설정한다.
           request.setAttribute("member", nameArr);
           request.setAttribute("project_list", list);
           //2.이동할 페이지 설정
           RequestDispatcher  rd=request.getRequestDispatcher("forward_b");
           //3.이동
           rd.forward(request, response);
           
           //out.println("<h1>브라우저 출력@!@!#!</h1>");
           //view에 대한 코드를 전혀 만들지 않는다, 데이터 처리에  집중할 수 있게 됨
     
     }//doGet
}//class
package day0228;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ForwardB extends HttpServlet {
     //디자인에 집중
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           
           out.println("<script  src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script>");
           out.println("<script type='text/javascript'>");
           out.println("$(function(){");
           
           out.println("\t$('.btn').click(function(){");
           //select의 값
           out.println("\tvar output='';");
           out.println("\tvar prj_name=$('#prj').val();");
           //checkbox의 값을 가져와서
           out.println("\toutput='프로젝트명  ['+prj_name+']<br/>참여인원 : ';");
            out.println("\t$.each($(\"[name='name']\"),function(i,obj){");
           out.println("\tif($(obj).is(':checked')){");
           out.println("\toutput+=$(obj).val()+' ';");
           out.println("\t}//end if");
           out.println("\t});//each");
           //div출력
           out.println("\t$('#prj_member').html(output);");
           
           out.println("\t});//click");
           out.println("});//ready");
           out.println("</script>");
           
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //데이터 처리 페이지에서 처리한 경과를 받아와서
           String[]  nameArr=(String[])request.getAttribute("member");
           List<String>  prjList=(List<String>)request.getAttribute("project_list");
           
           //출력부분을 만든다.
           out.println("<label>프로젝트 선택</label>");
           out.println("<select id='prj'>");
           for(String prj:prjList) {
            out.print("<option value='");//StringBuilder보다  메소드를 따로 출력하는게 속도가 빠름//+쓰면 StringBuilder
            out.print(prj);
            out.print("'>");
            out.print(prj);
            out.println("</option>");
           }//end for
       out.println("</select>");
       
       out.println("<div>");
       out.println("<h3>투입 인력</h3>");
       for(String name:nameArr) {
             out.print("<input type='checkbox' name='name'  value='");
             out.print(name);
             out.print("'>");
             out.print(name);
             out.println("&nbsp;");
       }//end for
       out.print("<input type='button' value='추가'  class='btn'/>");
       out.println("</div>");
       out.println("<div id='prj_member'></div>");
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
           
     }//doGet
}//class




*관계 유지
  • //웹은 멱등성(모든 접속자에게 같은 페이지) 비연결성/비연결 지향성?을 가짐
  • 비연결성인 웹에서 접속자의 정보를 저장하여 연결되어 있는것처럼 사용하기위한 기술
  • //비연결성 : 요청이 들어오면 응답을 해주고 연결을 끊는것
    • 장점: 모든클라이언트의 연결을 생성해놓지 않고 필요할 때에만 연결하는 방식으로 서버의 사양이 낮아도 많은 수의 클라이언트에게 서비스가 가능하다.(성능이 많이 좋지않아도 괜찮...지만 동영상서비스는 아님)
    • 단점: 접속자의 상태를 알 수 없다.(게임은 연결성)==>비연결성
  • Session,Cookie가 제공
  • =>Session : 접속자의 정보를 서버측 메모리에 저장하는 기술 (7Layer에 Session)
    • 모든 브라우저의 정보를 저장할 수 있다.
    • 브라우저 별 id를 부여하고 값을 저장한다.
    • 객체가 저장되므로 모든 값을 저장할 수 있다.
    • 사용하기 위한 객체 : HttpSession
    • 모든 접속자에게 적용시킬 수 있다.
  • =>Cookie : 접속자의 정보를 접속자의 HDD에 File로 저장
    • Cookie를 지원하지 않는 브라우저는 Cookie를 사용할 수 없다.(사용자의 설정에 따라서도 사용하지 않을 수 있다)
    • 접속자의 HDD의 File로 저장된다.
    • 문자열 데이터만 저장된다.
    • 사용하기 위한 객체 : Cookie
    • 모든 접속자에게 적용시킬 수 없다.
    • 대체기술 : Storage(SessionStorage-닫히면 날라가는, localStorage-닫혀도 유지)
  • //서버(메모리)에 정보를 저장하는게 Session, 클라이언트(File)에 정보가 저장되면 Cookie (보안때문에 문자열 데이터만)
  • //세션하이젝킹 : 쿠키를 가지고 남인양 변조하여 정보탈취
-하지 않으면 어떤일이 일어나는 가?▼
  •  Cpage에서는 Bpage에 존재하는 name,id,pass들을 사용할 수 없다. 지역변수이기 때문에.. 
  • 직접적으로 QueryString에 넣어주어도 되지만 보안상 이용x
  • 비연결성인 웹에서 앞페이지의 정보를 넘겨받기 위한것.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="http://localhost:8080/servlet_prj/common/main_v190130.css"/>
<style type="text/css">
#wrap{margin:0px auto;width:800px; height:860px;}
#header{width:800px; height:140px; background:#FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;
           position: relative; }
#headerTitle{font-family: HY견고딕,고딕; font-size:35px;  font-weight:bold; text-align:center;
                /* padding-top: 35px */ position:absolute;  top:40px; left:290px; }
#container{width:800px; height:600px; }
#footer{width:800px; height:120px; }
#footerTitle{float: right; font-size:15px; padding-top:20px;  padding-right:20px; }
</style>
<!-- jQuery CDN -->
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
     $(".btn").click(function(){
           chkNull();
     });//click
     $("[name='id']").keydown(function(evt){
           if(evt.which==13){
                chkNull();
           }//end if
     });//keydown
     $("[name='pass']").keydown(function(evt){
           if(evt.which==13){
                chkNull();
           }//end if
     });//keydown
});//ready
function chkNull(){
     var id=$("[name='id']").val();
     var pass=$("[name='pass']").val();
     
     if(id==""){
           $("[name='id']").focus();
           return;
     }//end if
     if(pass==""){
           $("[name='pass']").focus();
           return;
     }//end if
     $("form").submit();//tag selector
     
}//chkNull
</script>
</head>
<body>
<div id="wrap">
     <div id="header">
           <div id="headerTitle">SIST Class4</div>
     </div>
     
     <div id="container">
     <div>
     <form method="post" action="../why_session_b">
     <table>
           <tr>
                <td>
                     <input type="text" name="id"  placeholder="아이디" autofocus="autofocus" class="inputBox"/>
                </td>
                <td rowspan="2">
                     <input type="button" value="로그인"  class="btn" style="height:50px; width:50px;"/>
                </td>
           </tr>
           <tr>
                <td>
                     <input type="password" name="pass"  placeholder="비밀번호" class="inputBox"/>
                </td>
           </tr>
     </table>
     </form>
     </div>
     </div>
     
     <div id="footer">
           <div id="footerTitle">copyright&copy; all right  reserved. class 4.</div>
     </div>
</div>
</body>
</html>
package day0228;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class WhySessionB extends HttpServlet {
     private Map<String, String> loginMap;//한번만 생성
     
     public void init() {
           loginMap=new HashMap<String,String>();
           loginMap.put("kong", "공");
           loginMap.put("rho", "노");
           loginMap.put("kim", "김");
           loginMap.put("lee", "이");
           
     }//init
     
     protected void doPost(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
                     
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //사용자가 입력한 값을 받기
           String id=request.getParameter("id");
           String pass=request.getParameter("pass");
           
           if(loginMap.containsKey(id) && "1234".equals(pass))  {
            String name=loginMap.get(id);//지역변수이기때문에  이름값을 받아올 수 없다..!
            out.println("<div>");
            out.print("<strong>");
            out.print(id);
            out.print("</strong>(");
            out.print(name);
            out.println(")님 로그인 하셨습니다.<br/>");
//          out.println("작업페이지로<a  href='why_session_c?name="+name+">이동</a>");
            out.println("작업페이지로<a  href='why_session_c'>이동</a>");
            out.println("</div>");
           }else {
            out.println("아이디나 비밀번호를 확인해 주세요.");
            out.println("<a href='#void'  onclick='history.back();'>로그인</a>");
            
           }//end else
           
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
           
     }//doPost
}//class
package day0228;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class WhySessionC extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
                     
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //WhySessionC 서블릿에서는 이전페이지인 WhySessionB  서블릿 내의 값을 사용할 수 없다.(지역변수라 접근이 안된다.+직접  객체를 생성해도 다른객체가 되어서ㄴㄴㄴ)
           //(이전페이지에서 사용한 이름을 이동한 페이지에서  사용할 수 없다.)
           //String name=request.getParameter("name");//사용하지  않는다!!!
           out.println("님의 작업페이지 입니다.");
           
           
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
     
     }//doGet
}//class






 

반응형