본문 바로가기

Programming/국비학원

220927 - 서블릿 - 서블릿 확장 API (ServletContext 클래스), 쿠키, 세션

https://codeofenow.tistory.com/32

https://coco-log.tistory.com/40

ServletContext 클래스

1. 서블릿 간 자원(데이터) 공유하는 데 사용
2. 컨테이너 실행 시 생성되며 컨테이너 종료 시 소멸

 

 

 

  • 서블릿 간 자원 공유
  • SetServletContext
@WebServlet("/setC")
public class SetServletContext extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ServletContext context = getServletContext(); //ServletContext 객체 가져와 변수에 저장
		List member = new ArrayList();
		member.add("홍길동");
		member.add(50);
		context.setAttribute("member", member); //데이터 세팅
		out.print("<html><body>");
		out.print("member 자원 공유");
		out.print("</body></html>");
	}

}

 

 

 

  • GetServletContext
@WebServlet("/getC")
public class GetServletContext extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ServletContext context = getServletContext();
		List member = (ArrayList) context.getAttribute("member"); //세팅한 데이터 가져옴
		String name = (String) member.get(0);
		int age = (Integer) member.get(1);
		out.print("<html><body>");
		out.print("<p>이름 : "+name+"</p>");
		out.print("<p>나이 : "+age+"</p>");
		out.print("</body></html>");
	}

}

 

 

 

 

  • 매개변수 설정 기능

=> 프로그램 시작, 초기화 시 가져와 사용

=> 공통 메뉴를 화면에 출력

 

 

 

  • web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>servletAPI</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
  <context-param> ////컨테이너 안에서 사용할 변수 선언
  	<param-name>menu_member</param-name>
  	<param-value>회원등록 회원조회 회원수정</param-value>
  </context-param>
  <context-param>
  	<param-name>menu_order</param-name>
  	<param-value>주문조회 주문등록 주문수정 주문취소</param-value>
  </context-param>
  <context-param>
  	<param-name>menu_goods</param-name>
  	<param-value>상품조회 상품등록 상품수정 상품삭제</param-value>
  </context-param>    
</web-app>

 

 

 

  • ContextParamServlet
@WebServlet("/initMenu")
public class ContextParamServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		ServletContext context = getServletContext();
		String m_member = context.getInitParameter("menu_member"); //컨테이너에 초기선언된 변수 가져옴
		String m_order = context.getInitParameter("menu_order");
		String m_goods = context.getInitParameter("menu_goods");
		out.print("<html><body>");
		out.print("<ul><li>"+m_member+"</li><li>"+m_order+"</li><li>"+m_goods+"</li></ul>");
		out.print("</body></html>");

	}

}

 

 

 

 

https://mycool0905.github.io/web/java/servlet/jsp/2020/07/12/servlet-extended-API.html

  • 파일 입출력 기능

=> 공통 메뉴를 화면에 출력

 

 

 

  • /WEB-INF/menu/initMenu.txt

회원등록 회원조회 회원수정, 주문조회 주문등록 주문수정 주문취소, 상품조회 상품등록 상품수정 상품삭제

 

 

 

  • ContextFileServlet
@WebServlet("/cFile")
public class ContextFileServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		ServletContext context = getServletContext(); //ServletContext 객체 사용 위해 가져옴
		
		InputStream inputS = context.getResourceAsStream("/WEB-INF/menu/initMenu.txt");
		//getResourceAsStream : 지정한 경로에 있는 자원 읽을 수 있는 InputStream 객체 리턴
		BufferedReader br = new BufferedReader(new InputStreamReader(inputS));
		
		String menu=null;
		String m_member=null;
		String m_order=null;
		String m_goods=null;
		
		while((menu=br.readLine()) != null) { //menu(inputS) 값 없어질 때까지 while문 실행
			StringTokenizer st = new StringTokenizer(menu,","); //쉼표로 문자열 나눔
			m_member = st.nextToken();
			m_order = st.nextToken();
			m_goods = st.nextToken();
		}
		
		out.print("<html><body>");
		out.print("<ul><li>"+m_member+"</li><li>"+m_order+"</li><li>"+m_goods+"</li></ul>");
		out.print("</body></html>");	}
}

 

 

 

 

https://mycool0905.github.io/web/java/servlet/jsp/2020/09/22/cookie-and-session.html

쿠키 & 세션
  • 웹페이지 연동 방법 (세션 트래킹)

1. hidden 태그

HTML의 hidden 태그를 이용해 웹 페이지들 사이의 정보 공유

 

2. URL Rewriting

GET 방식으로 URL 뒤에 정보를 붙여서 다른 페이지로 전송

 

3. 쿠키

클라이언트 PC의 Cookie 파일에 정보를 저장한 후 웹페이지들이 공유

 

4. 세션

서버 메모리에 정보를 저장한 후 웹페이지들이 공유

 

 

 

 

  • 쿠키

웹페이지들 간 공유된 정보를 클라이언트 PC에 저장
-> 필요할 때 여러 웹페이지들이 공유, 사용하도록 매개 역할함

 

저장용량 제한 있음 (4kb)
보안 취약
클라이언트 브라우저에서 사용 유무를 설정함
도메인 당 쿠키 만들어짐 (웹사이트 당 하나의 쿠키)

 

 

 

  • 종류

1. Persistence 쿠키
생성위치: 파일로 생성
종료시기: 쿠키를 삭제하거나 쿠키 설정 값이 종료된 경우
최초 접속 시 전송 여부: 최초 접속 시 서버로 전송
용도: 로그인 유무 또는 팝업창을 제한할 때

2. Session 쿠키
생성위치: 브라우저 메모리에 생성
종료시기: 브라우저를 종료한 경우
최초 접속 시 전송 여부: 최초 접속 시 서버로 전송 X
용도: 사이트 접속 시 Session 인증 정보를 유지할 때(Session 기능과 같이 사용)

 

 

 

  • 쿠키 실행 과정

1 클라이언트 => 브라우저로 사이트 접속
2 서버 => 사이트 정보 저장된 쿠키 생성, 브라우저로 전송
3 브라우저 => 받은 쿠키 정보를 쿠키 파일에 저장
4 클라이언트 브라우저 재접속 => 서버가 브라우저에 쿠키 전송 요청 & 브라우저는 쿠키 정보를 서버에 전달
5 서버 => 쿠키 정보 이용해 작업 수행

 

 

 

  • Cookie 클래스 메소드

getComment() : 쿠키에 대한 설명 가져옴
getDomain() : 쿠키의 유효한 도메인 정보 가져옴
getMaxAge() : 쿠키 유효 기간 가져옴
getName() : 쿠키 이름 가져옴
getPath() : 쿠키의 디렉터리 정보 가져옴
getValue() : 쿠키의 설정 값 가져옴
setComment(String) : 쿠키에 대한 설명 설정
setDomain(String) : 쿠키의 유효한 도메인 설정
setMaxAge(int) : 쿠키 유효 기간 설정
setValue(String) : 쿠키 값 설정

 

 

 

 

  • 로그인 (hidden 태그)
  • login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 창</title>
</head>
<body>
	<form action="login" method="post" name="formLogin">
		<label for="user_id">아이디 : </label>
		<input type="text" id="user_id" name="user_id">
		<label for="user_pw">비밀번호 : </label>
		<input type="text" id="user_pw" name="user_pw">
		<input type="hidden" name="phone" value="010-1111-2222">
		<input type="hidden" name="address" value="서울시 종로구">
		<input type="submit" value="로그인">
		<input type="reset" value="다시 입력">
	</form>
</body>
</html>

 

 

 

  • LoginServlet
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("user_id");
		String pw = request.getParameter("user_pw");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		
		out.print("<html><body>안녕하세요 "+id+"님<br>");
		out.print("로그인 성공하셨습니다.<br>");
		out.print("<br>로그인 정보<br>");
		out.print("아이디 : "+id);
		out.print("<br>비밀번호 : "+pw);
		out.print("<br>전화번호 : "+phone);
		out.print("<br>주소 : "+address+"</body></html>");
		
	}

}

//
안녕하세요 bb님
로그인 성공하셨습니다.

로그인 정보
아이디 : bb
비밀번호 : cc
전화번호 : 010-1111-2222
주소 : 서울시 종로구

 

 

 

 

  • 로그인 (url)
  • login.html 재사용 (action 수정)

 

 

  • LoginServlet2
@WebServlet("/login2")
public class LoginServlet2 extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("user_id");
		String pw = request.getParameter("user_pw");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		
		out.print("<html><body>안녕하세요 "+id+"님<br>");
		out.print("로그인 성공하셨습니다.<br>");
		out.print("<br>로그인 정보<br>");
		out.print("아이디 : "+id);
		out.print("<br>비밀번호 : "+pw);
		out.print("<br>전화번호 : "+phone);
		out.print("<br>주소 : "+address);
		address=URLEncoder.encode(address,"utf-8"); //한글이므로 따로 인코딩
		out.print("<br><a href='/servletLink/second?id="+id+"&pw="
		+pw+"&address="+address+"'>두번째 서블릿으로 보내기</a>"); //? => get 방식 데이터 전송 
		out.print("<br></body></html>");
		
	}

}

 

※ url get 전송 방식

매핑이름?이름=값&이름2=값2&...

 

 

 

  • SecondServlet
@WebServlet("/second")
public class SecondServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("id"); //LoginServlet에서 get방식으로 넘어온 id의 값 받음
		String pw = request.getParameter("pw");
		String address = request.getParameter("address");
		
		out.print("<html><body>");
		if (id != null && id.length() != 0) {
			out.print("<p>로그인 성공</p>");
			out.print("<p>첫번째 서블릿에서 넘겨준 아이디 : "+id+"</p>");
			out.print("<p>첫번째 서블릿에서 넘겨준 비밀번호 : "+pw+"</p>");
			out.print("<p>첫번째 서블릿에서 넘겨준 주소 : "+address+"</p>");
		} else {
			out.print("<p>로그인하지 않았습니다</p>");
			out.print("<p>다시 로그인하세요</p>");
			out.print("<a href='/servletLink/login.html'>로그인하기</a>");
		}
		out.print("</body></html>");
		
	}

}

 

 

 

 

  • 로그인 (쿠키)
  • SetCookie
@WebServlet("/setC")
public class SetCookie extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		Date d = new Date();
		Cookie c = new Cookie("cookieTest",URLEncoder.encode("오늘은 화요일","utf-8"));
		//Cookie(쿠키 이름, 저장될 내용)
		//일반적 쿠키 => Persistence 쿠키
		c.setMaxAge(24*60*60); //쿠키 유효기간 (초 기준) => 하루
		response.addCookie(c); //쿠키를 브라우저로 전송
		out.print("현재 시간 : "+d);
		out.print("<br>문자열을 Cookie에 저장");
	}

}

 

※  @WebServlet 어노테이션이 중복인 프로젝트가 하나만 서버 접속돼있으면  정상 작동

 

 

 

  • GetCookie
@WebServlet("/getC")
public class GetCookie extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		Cookie[] allValues = request.getCookies(); //쿠키는 배열로 전달됨
		
		for (int i=0;i<allValues.length;i++) {
			if(allValues[i].getName().equals("cookieTest")) { //쿠키 이름 확인
				out.print("<h2>쿠키 값 => "+
			URLDecoder.decode(allValues[i].getValue(),"utf-8")
				+"</h2>");
			}
		}
	}

}

//
쿠키 값 => 오늘은 화요일


F12 - Application - Cookies 확인

=> Expiration 다음날로 설정돼있음
=> 창 닫고 다시 켜도 쿠키 유지됨

 

 

 

 

  • 로그인 (Session 쿠키)
  • SetCookie
@WebServlet("/setC")
public class SetCookie extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		Date d = new Date();
		Cookie c = new Cookie("cookieTest",URLEncoder.encode("오늘은 화요일","utf-8"));
		c.setMaxAge(-1); //세션 쿠키 설정
		response.addCookie(c); 
		
		out.print("현재 시간 : "+d);
		out.print("<br>문자열을 Cookie에 저장");
	}

}

 

 

  • GetCookie 재사용

 

 

//
쿠키 값 => 오늘은 화요일


F12 - Cookies

=> 유효기간이 Session으로 설정돼있음
=> 브라우저 종료 후 재접속 시 쿠키 삭제돼있음