접기
package servlet.cookie;
import java.io.IOException; import java.net.URLEncoder;
import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.Cookies;
public class SetCookieServlet2 extends HttpServlet { private static final long serialVersionUID = 1L;
public SetCookieServlet2() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Cookie값에 한글이 들어간 경우 encoding처리가 필요 //java.net.URLEncoder.encode() String name = URLEncoder.encode("홍길동"); //한글을 encode String address = URLEncoder.encode("서울시 가락동"); //두개의 쿠기값 사용 Cookie c1 = new Cookie("name",name); Cookie c2 = new Cookie("address",address); //client로 전송 response.addCookie(c1); response.addCookie(c2); //응답 response.sendRedirect("/myweb/cookie/req.html"); }
}
접기
접기
package servlet.cookie;
import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder;
import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class GetCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L;
public GetCookieServlet() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // SetCookieServlet에서 설정한 쿠키 값을 조회하여 출력 // 1. 쿠키 조회 Cookie[] cs = request.getCookies(); // 2. 출력 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<html><body>"); for(Cookie c : cs){ String name = c.getName(); String value = c.getValue(); if(name.equals("name") || name.equals("address")){ value = URLDecoder.decode(value); } out.println(name + " - "+ value+"<br>"); }
out.println("</body></html>"); //name="name"인 값만 뽑아 내기 out.println("<hr>"); String value=null; for(int i=0;i<cs.length;i++){ if(cs[i].getName().equals("name")){ value = cs[i].getValue(); } } if(value!=null){ out.println(URLDecoder.decode(value)+"님 환영합니다."); }else{ out.println("이름이 없습니다."); } }
}
접기