jhs0129 2021. 8. 24. 16:28
320x100
반응형

여러개 버튼 사용하기 - 하나의 name값으로 지정하고 해당 string 값이 value와 동일한지 확인

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action = "calc" method = "post">
		<div>
			계산할 값을 입력하세요
		</div>
		<div>	
			X : 
			<input type="text" name ="x">
		</div>
		<div>	
			Y : 
			<input type="text" name ="y">
		</div>
		<div>
			<input type="submit" name="operator" value="덧셈">
			<input type="submit" name="operator" value="뺄셈">
		</div>
	</form>
</body>
</html>
String button = req.getParameter("operator");
		
		int result = 0;
		result = (button.equals("덧셈"))? x+y : x-y;

 

여러개의 값을 받기 - 버튼과 동일하게 하나의 name으로 지정을 request.getParameterValues() 메소드로 배열로 받음

 

서블릿 간에 값을 공유할 수 있도록 상태를 유지 - application, session, cookie를 사용해서 저장

 * 서블릿의 요청이 끝나면 삭제되어 데이터가 유지가 안됨 - 서블릿 context(application, session, cookie)이라는 공간에 저장

 

  • application 사용 - map사용과 비슷, 다른 서블릿에게 공유할 수 있도록 저장 할 수 있는 공간 (전역 공간으로 생각)

setAttribute로 값을 저장

getAttribute로 값을 불러옴

@WebServlet("/calc2")
public class Calc2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.setCharacterEncoding("UTF-8"); // 인코딩 방식 지정
		resp.setContentType("text/html; charset=UTF-8"); //콘텐츠타입 지정
		
		String v_ = req.getParameter("value");
		String op = req.getParameter("operator");
		ServletContext application = req.getServletContext();
		
		int v = 0;
		if(!v_.equals("")) v = Integer.parseInt(v_);
		
		//값 계산
		if(op.equals("=")) {
			int x = (Integer)application.getAttribute("value");
			int y = v;
			String operator = (String)application.getAttribute("op");
			int result = 0;
			result = (operator.equals("+"))? x+y : x-y;
			
			resp.getWriter().println("결과 값은 : " + result);
		}
		//값 저장
		else {
			
			application.setAttribute("value", v);
			application.setAttribute("op", op);
		}
	}
  • Session - 사용자를 위한 개별 공간, id를 가지고 있음 (지역 공간)

application과 동일하게 request.getSession으로 받아올 수 있음, 사용법은 동일

 

차이점 - application : 모든 서블릿이 사용할 수 있는 전역 범위

            session : 현재 접속자 마다 공간이 달라짐 ( 크롬이랑 엣지 두개로 접속하면 두개가 다른 사용자로 인식 )

                        같은 크롬에서는 하나의 사용자로 인식( 하위 스레드 개념?? )

 

웹 서버(was)가 현재 사용자(session) 구분 하는 법 - WAS가 session의 id를 부여, 해당 id를 보고 구분

 * id확인 하는 법 f12누르고  cookie에 sessionid 있음

 

* invalidate() - session에 사용되는 객체 바로 해제

* setMaxInactiveInterval(int interval) - 일정 시간이 경과하면 객체 해제

 

  • Cookie - 서블릿이 가지고 다니는 값, 서버에 저장하지 않고 클라이언트가 가지고 있음 (map처럼 사용)

Header(TCP/IP. 헤더 정보), data(사용자 데이터)설정

getCookies(), addCookie()

 

 - 여러개의 값을 가지거나 이름 중복 충돌을 막기위해서 설정할 것

    cookie.setPath(" ") - url설정해서 언제 쿠키를 가져올지 설정

    * / - root

 

 - 브라우저가 닫혀도 기간 설정하면 값을 유지하도록 할 수 있음

기간이 설정되면 브라우저에서 외부 파일로 저장됨

    cookie.setMaxAge(second)

    * 일반적으로 second는 60단위로 곱셈을 통해서 설정 ex) 1시간 : 60*60

 

package com.jhs.web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/calc2")
public class Calc2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8"); // 인코딩 방식 지정
		resp.setContentType("text/html; charset=UTF-8"); //콘텐츠타입 지정
		
		String v_ = req.getParameter("value");
		String op = req.getParameter("operator");
		
		ServletContext application = req.getServletContext();
		HttpSession session = req.getSession();
		Cookie[] cookies = req.getCookies();
		
		int v = 0;
		if(!v_.equals("")) v = Integer.parseInt(v_);
		
		//값 계산
		if(op.equals("=")) {
			//int x = (Integer)application.getAttribute("value");
			//int x = (Integer)session.getAttribute("value");
			int x = 0;
			for(Cookie c : cookies) 
				if(c.getName().equals("value")) {
					x = Integer.parseInt(c.getValue());
					break;
				}
			
			int y = v;
			
			//String operator = (String)application.getAttribute("op");
			//String operator = (String)session.getAttribute("op");
			String operator = "";
			for(Cookie c : cookies) 
				if(c.getName().equals("op")) {
					operator = c.getValue();
					break;
				}
			
			int result = 0;
			result = (operator.equals("+"))? x+y : x-y;
			
			resp.getWriter().println("결과 값은 : " + result);
		}
		//값 저장
		else {
			//application.setAttribute("value", v);
			//application.setAttribute("op", op);
			
			//session.setAttribute("value", v);
			//session.setAttribute("op", op);
			
			Cookie valueCookie = new Cookie("value", String.valueOf(v));
			Cookie opCookie = new Cookie("op", op);
			resp.addCookie(valueCookie);
			resp.addCookie(opCookie);
			
		}
	}
}

 

  • Application, Session, Cookie 차이점

application - 전역범위 저장공간, WAS시작~종료까지, WAS서버 메모리

session - 세션 범위에서 사용하는 저장공간, 세션시작~종료, WAS서버 메모리

cookie -  web browser별 지정한 apth범주, 브라우저에 전달한 시간~만료시간,  브라우저의 메모리 or 파일

 

서버에 저장할 수 있는 저장소 - Application, Session

클라이언트에 저장할 수 있는 저장소 - Cookie

320x100
반응형