ecsimsw
JSP, Servlet / 쿠키 본문
Cookie
request에서 쿠키를 가져와 처리하고, 새로운 쿠키를 생성해 응답하는 방법
1. Get Cookies, Get Cookie Info
Cookie[] cookies = request.getCookies();
Cookie cookie = cookies[0];
cookie.getName();
cookie.getValue();
2. Create new Cookie
Cookie c = new Cookie(cookieName,cookieValue); // 쿠키 생성 (이름,값)
c.setMaxAge(sec); // 쿠키 생존 시간 설정
response.addCookie(c); // 응답에 쿠키 추가
예시 )
loginInfo 쿠키가 없으면 로그인 요구 후, 쿠키 생성
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page errorPage = "Error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
Cookie loginInfo = null;
if(cookies != null){
for(Cookie c : cookies){
if(c.getName().equals("loginInfo")){
loginInfo = c;
}
}
}
%>
<%
if(loginInfo == null){
%>
<p>먼저 로그인을 하세요</p>
<form action= "login" method ="post">
<p>
<strong>아이디</strong>
<input type="text" name="id" value="아이디 입력">
</p>
<p>
<strong>비밀번호</strong>
<input type="password" name="pw" value="비밀번호 입력">
</p>
<p>
<input type="submit" value="제출">
</p>
</form>
<%
}else{
%>
<p> 당신의 로그인 id <%= loginInfo.getValue()%> </p>
<%
}
%>
</body>
</html>
ServletEX.class
@WebServlet("/login")
public class ServletEX extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String pw = request.getParameter("pw");
Cookie[] cookies = request.getCookies();
Cookie loginCookie = null;
if(cookies != null) {
for(Cookie c : cookies) {
System.out.println(c.getName()+ " "+c.getValue());
if(c.getName().equals("loginInfo")) {
loginCookie = c;
}
}
}
if(loginCookie == null) {
System.out.println("new login");
loginCookie = new Cookie("loginInfo",id);
}
response.addCookie(loginCookie);
loginCookie.setMaxAge(60*60);
response.sendRedirect("loginForm.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
'Server application > Web, Servlet' 카테고리의 다른 글
JSP / 액션 태그 (0) | 2020.05.18 |
---|---|
JSP, Servlet / 세션 (0) | 2020.05.15 |
내장 객체 / out / exception (0) | 2020.05.13 |
내장 객체 / ServletContext / ServletConfig (0) | 2020.05.13 |
JSP / 스크립트 (0) | 2020.05.11 |
Comments