-
JSP : 사용자 action을 session, cookie에 따라서 추적하기 (To Do, 쿠키 사이트)Spring 2021. 6. 18. 17:51
사용자의 각각의 세션에 따라서 액션이 이루어지도록 하자.
세션은 사이트에 들어오는 세션마다 새로이 정보를 저장하고 가져올 것이다.
먼저 todo-demo.jsp파일을 만든다.
<html> <body> <!-- Step 1: Create HTML form --> <form action = "todo-demo.jsp"> Add new item : <input type="text" name = "theItem"/> <input type="submit" value="Submit"/> </form> <br/> Item entered: <%= request.getParameter("theItem") %> <!-- Step 2: Add new item to "To Do" list --> <!-- Step 3: Display all "To Do" item from session --> </body> </html>
이제 내가 입력한 정보 이외에도 세션 데이터가 있다면 추가해주고,
없으면 방금 작성한 내용만 추가해주는 코드를 작성해준다.
<%@ page import = "java.util.*" %> <html> <body> <!-- Step 1: Create HTML form --> <form action = "todo-demo.jsp"> Add new item : <input type="text" name = "theItem"/> <input type="submit" value="Submit"/> </form> <br/> Item entered: <%= request.getParameter("theItem") %> <!-- Step 2: Add new item to "To Do" list --> <% //get the To Do items from the session List<String> items = (List<String>) session.getAttribute("myToDoList"); //if the To Do items doesn't exist, then create a new one if(items ==null){ items = new ArrayList<String>(); session.setAttribute("myToDoList", items); } //see if there is form data to add String theItem = request.getParameter("theItem"); if(theItem != null){ items.add(theItem); } %> <!-- Step 3: Display all "To Do" item from session --> </body> </html>
이제 화면창에 내가 가져온 정보들을 보여주도록 하자.
<%@ page import = "java.util.*" %> <html> <body> <!-- Step 1: Create HTML form --> <form action = "todo-demo.jsp"> Add new item : <input type="text" name = "theItem"/> <input type="submit" value="Submit"/> </form> <!-- Step 2: Add new item to "To Do" list --> <% //get the To Do items from the session List<String> items = (List<String>) session.getAttribute("myToDoList"); //if the To Do items doesn't exist, then create a new one if(items ==null){ items = new ArrayList<String>(); session.setAttribute("myToDoList", items); } //see if there is form data to add String theItem = request.getParameter("theItem"); if(theItem != null && (!theItem.trim().equals(""))){ items.add(theItem); } %> <!-- Step 3: Display all "To Do" item from session --> <hr> <b>To List Items : </b> <ol> <% for(String temp: items){ out.println("<li>" + temp +"</li>"); } %> </ol> </body> </html>
추가로 여기서 페이지를 새로고침할때 이전에 작성한 내용이 추가되지 않도록 하자.
<%@ page import = "java.util.*" %> <html> <body> <!-- Step 1: Create HTML form --> <form action = "todo-demo.jsp"> Add new item : <input type="text" name = "theItem"/> <input type="submit" value="Submit"/> </form> <!-- Step 2: Add new item to "To Do" list --> <% //get the To Do items from the session List<String> items = (List<String>) session.getAttribute("myToDoList"); //if the To Do items doesn't exist, then create a new one if(items ==null){ items = new ArrayList<String>(); session.setAttribute("myToDoList", items); } //see if there is form data to add String theItem = request.getParameter("theItem"); boolean isItemNotEmpty = theItem !=null && theItem.trim().length()>0; boolean isItemNotDuplicate = theItem !=null && !items.contains(theItem.trim()); if(isItemNotEmpty && isItemNotDuplicate){ items.add(theItem.trim()); } %> <!-- Step 3: Display all "To Do" item from session --> <hr> <b>To List Items : </b> <ol> <% for(String temp: items){ out.println("<li>" + temp +"</li>"); } %> </ol> </body> </html>
이제 쿠키를 이용해서 사이트에서 정보를 저장하는 방법을 배우자.
쿠키는 도메인에 따라서 저장 기간을 설정해서 사용자 정보를 불러오는 방식이다.
cookies-personalize-form.html
<html> <head> <title>Personalize The Site</title> </head> <body> <form action="cookies-personalize-response.jsp"> Select your Favorite Programming Language <select name = "favoriteLanguage"> <option>Java</option> <option>C++</option> <option>Python</option> <option>Javascript</option> </select> <br/> <input type="submit" value="Submit"/> </form> </body> </html>
cookies-personalize-response.jsp
<html> <head> <title>Confirmation</title> </head> <% //read from data String favLang = request.getParameter("favoriteLanguage"); //create the cookie Cookie theCookie = new Cookie("myApp.favoriteLanguage", favLang); //set the life span ... totla number of seconds (yuk!)->1year theCookie.setMaxAge(60*60*24*365); //send cookie to browser response.addCookie(theCookie); %> <body> Thanks! We set your favorite language to : ${param.favoriteLanguage } <br/><br/> <a href = "cookies-homepage.jsp">Return to homepage.</a> </body> </html>
이제 홈페이지를 작성하자.
<html> <body> <h3>Training Portal</h3> <!-- read the favorite programming language cookie --> <% //the default ... if there are no cookies String favLang = "Java"; //get the cookies from the browser request Cookie[] theCookies = request.getCookies(); //find our favorite language cookie if(theCookies!=null){ for(Cookie tempCookie: theCookies){ if("myApp.favoriteLanguage".equals(tempCookie.getName())){ favLang = tempCookie.getValue(); break; } } } %> <!-- now show a personalized page ... use the "favLang" variable --> <!-- show new books for this lang --> <h4>New Books for <%=favLang %></h4> <ul> <li>blah blah blah</li> </ul> <h4>Latest News Reports for <%=favLang %></h4> <ul> <li>blah blah blah</li> <li>blah blah blah</li> </ul> <h4>Hot Jobs for <%=favLang %></h4> <ul> <li>blah blah blah</li> <li>blah blah blah</li> <li>blah blah blah</li> </ul> <hr> <a href = "cookies-personalize-form.html" >Personalize this page.</a> </body> </html>
쿠키가 잘 저장된 것을 확인할 수 있다.
추가로 만약에 쿠키 속성이름(Java, Python...의 이름)의 공백처리를 하고 싶다면 다음과 같이 수정해준다.
cookies-hompage.jsp
<%@ page import="java.net.URLDecoder" %> <html> <body> <h3>Training Portal</h3> <!-- read the favorite programming language cookie --> <% // the default ... if there are no cookies String favLang = "Java"; // get the cookies from the browser request Cookie[] theCookies = request.getCookies(); // find our favorite language cookie if (theCookies != null) { for (Cookie tempCookie : theCookies) { if ("myApp.favoriteLanguage".equals(tempCookie.getName())) { // decode cookie data ... handle case of languages with spaces in them favLang = URLDecoder.decode(tempCookie.getValue(), "UTF-8"); break; } } } %> <!-- now show a personalized page ... use the "favLang" variable --> <!-- show new books for this lang --> <h4>New Books for <%= favLang %></h4> <ul> <li>blah blah blah</li> <li>blah blah blah</li> </ul> <h4>Latest News Reports for <%= favLang %></h4> <ul> <li>blah blah blah</li> <li>blah blah blah</li> </ul> <h4>Hot Jobs for <%= favLang %></h4> <ul> <li>blah blah blah</li> <li>blah blah blah</li> </ul> <hr> <a href="cookies-personalize-form.html">Personalize this page</a> </body> </html>
cookies-personalize-response.jsp
<%@ page import="java.net.URLEncoder" %> <html> <head><title>Confirmation</title></head> <% // read form data String favLang = request.getParameter("favoriteLanguage"); // encode cookie data ... handle case of languages with spaces in them favLang = URLEncoder.encode(favLang, "UTF-8"); // create the cookie Cookie theCookie = new Cookie("myApp.favoriteLanguage", favLang); // set the life span ... total number of seconds (yuk!) theCookie.setMaxAge(60*60*24*365); // <-- for one year // send cookie to browser response.addCookie(theCookie); %> <body> Thanks! We set your favorite language to: ${param.favoriteLanguage} <br/><br/> <a href="cookies-homepage.jsp">Return to homepage.</a> </body> </html>
cookies-personalize-form.html
다음의 공백도 잘 처리되서 나온다.
<html> <head> <title>Personalize The Site</title> </head> <body> <form action="cookies-personalize-response.jsp"> Select your Favorite Programming Language <select name="favoriteLanguage"> <option>Active Server Pages</option> <option>Java</option> <option>C#</option> <option> Common Business-Oriented Language</option> <option>PHP</option> <option>Ruby</option> <option>Hypertext Markup Language</option> </select> <br/><br/> <input type="submit" value="Submit" /> </form> </body> </html>
'Spring' 카테고리의 다른 글
JSP : Standard JSP Tag Library (JSTL) - Functional Tags (0) 2021.06.18 JSP : Standard JSP Tag Library (JSTL) - Core Tags (0) 2021.06.18 JSP의 기본 사용 방법 (0) 2021.06.18 Instagram 클론 -3) backend와 frontend 합치기 (0) 2021.06.12 Instagram 클론 -2) status, post, comment모델 만들기 (0) 2021.06.12