Back-end/기타 (BE)

뉴렉쳐 Servlet & JSP [21~30강]

philo0407 2020. 10. 1. 21:00
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

PrintWriter out = response.getWriter();

String x_ = request.getParameter("x");
String y_ = request.getParameter("x");

int x = 0;
int y = 0;

if(!x_.equals("")) {
x = Integer.parseInt(x_);
}

if(!y_.equals("")) {
y = Integer.parseInt(y_);
}

out.println("==== 계산 결과 ====<br/>");

//왜 오류가 날까
//out.printf("%d + %d = %d", x, y, (x + y) + "<br/><br/>");

int sum = (x+y);
out.printf("%d + %d = %d <br/><br/>", x, y, sum);

출처 :

https://www.youtube.com/watch?v=QGQURnAsC5M&list=PLq8wAnVUcTFVOtENMsujSgtv2TOsMy8zd&index=21

 


서블릿/JSP 강의 21 - 학습과제(사용자 입력을 통한 계산 요청)

숙제


서블릿/JSP 강의 22 - 과제풀이(사용자 입력을 통한 계산 요청)

 

계산할 값 입력 하세요.
    <div>
      <form action="add" method="POST">
        <div><label>x:</label><input name="x" type="text" /></div>
        <div><label>y:</label><input name="y" type="text" /></div>
        <div>
          <input type="submit" value="계산" />
        </div>
      </form>
    </div>

 

 

 


서블릿/JSP 강의 23 - 여러 개의 Submit 버튼 사용하기

hint

서블릿/JSP 강의 24 - 입력 데이터 배열로 받기

"String s" 는 더블쿼터 안 붙임

"String name" 은 더블쿼터 붙임

서블릿/JSP 강의 25 - 상태 유지를 필요로 하는 경우와 구현의 어려움

서블릿은 조각이 나 있다

이 조각난 서블릿들끼리 어떻게 모여서 합칠까

서블릿/JSP 강의 26 - Application 객체와 그것을 사용한 상태 값 저장

서블릿 Context 서로간에 문맥을 어떻게 이어 나갈까

다른 말로는 서블릿이 다른 서블릿이 결과물을 이어서 만들 수 있는 공간

서블릿들끼리 자원을 공유할 수 있는 공간

ServletContext application = request.getServletContext();

application.setAttribute("value", v);
application.setAttribute("op", op);  

 

변수 v를 value에 저장한다.

 

String lastOp = (String)application.getAttribute("op"); 

 

application context에 저장된 op를 꺼내와서 lastOp에 저장한다.

서블릿/JSP 강의 27 - Session 객체로 상태 값 저장하기(그리고 Application 객체와의 차이점)

session은 "현재 접속"한 사용자 ID라고 생각하면 된다.

브라우저 별로 다르다!

구글크롬

엣지

인터넷 익스플로러

서블릿/JSP 강의 28 - WAS가 현재사용자(Session)을 구분하는 방식

SID로 구분한다!!

브라우저별 세션 테스트! + n초 뒤에 세션 풀기!

 

HttpSession session = request.getSession();
		
session.setMaxInactiveInterval(6);

String concatStr = null;

try {
if(session.getAttribute("sessionValue") == null) {
  out.println("session value : ");
  out.println(session.getAttribute("sessionValue"));
}
concatStr = request.getParameter("sVal") + " "
  + session.getAttribute("sessionValue");
  session.setAttribute("sessionValue", concatStr);

} catch (Exception e) {
	session.getAttribute("sessionValue");
}

out.println(session.getAttribute("sessionValue"));

​서블릿/JSP 강의 29 - Cookie를 이용해 상태값 유지하기

 

// 쿠키 설정
Cookie valueCookie = new Cookie("value", String.valueOf(v));
Cookie opCookie = new Cookie("op", op);

// 클라 브라우저에 쿠키 전송
response.addCookie(valueCookie);
response.addCookie(opCookie);

 

 

 

쿠키 찾기!

for(Cookie c : cookies) {
  if(c.getName().equals("value"))
  	x = Integer.parseInt(c.getValue());
	else if(c.getName().equals("op"))
		lastOp = c.getValue();
}

 

서블릿/JSP 강의 30 - Cookie의 path 옵션

 

valueCookie.setPath("/add");
opCookie.setPath("/add");

 

이곳에 들어온 곳만 쿠키를 관리하겠다.