
--쿠키
HTTP 프로토콜의 문제점을 해결하기 위해 클라이언트측에 데이터를 저장하여 사용하는 방법
전달한 데이터를 웹 브라우저로 보냈다가 웹 서버 쪽으로 되돌려 받는 방법
클라이언트에 데이터를 저장
--cookie
--loginForm.jsp
<form action="loginProc.jsp" method="post">
아이디 : <input type="text" name="id">
비밀번호 : <input type="text" name="pass">
<input type="submit" value="로그인">
</form>
--loginProc.jsp
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String m_id = "kosta";
String m_pw = "1234";
String m_name = "홍길동";
String id = request.getParameter("id");
String pass = request.getParameter("pass");
String name = URLEncoder.encode(m_name, "UTF-8");//인코딩해서 쿠키에 저장
if(id.equals(m_id) && pass.equals(m_pw)){
Cookie cookie = new Cookie("name",name);
response.addCookie(cookie);
response.sendRedirect("main.jsp");
}else{
response.sendRedirect("loginForm.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href ="main.jsp">메인페이지 이동</a>
</body>
</html>
--main.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
String name = "";
if(cookies !=null){
for(int i=0; i<cookies.length; i++){
if(cookies[i].getName().equals("name")){
name = URLDecoder.decode(cookies[i].getValue(),"UTF-8");
}else if (cookies.length ==1 && cookies[i].getName().equals("JESSIONID")){
response.sendRedirect("loginForm.jsp");
}
}
}else{
response.sendRedirect("loginForm.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= name %>님 반갑습니다.
<a href = "logout.jsp">로그아웃</a>
</body>
</html>
--logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(int i=0;i<cookies.length; i++){
if(cookies[i].getName().equals("name")){
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
}else if(cookies.length ==1 && cookies[i].getName().equals("JSESSIONID")){
response.sendRedirect("loginForm.jsp");
}
}
}else{
response.sendRedirect("loginFrom.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
-- 세션
서버에 데이터를 저장
쿠키를 이용하는 것보다 세션을 이용하는 것이 편리함(Session이란 내장객체를 사용할 수 있기 때문에). setAttribute, getAttribute
데이터를 초과해서 사용할 경우
JSP에서 request 어떻게 사용했다. -> 내장객체 사용함. response.sendRedirect
Servlet & JSP 에서는 doGet, doPost 사용 -> request, response객체를 가짐
--loginForm.jsp
<form action="loginProc.jsp" method="post">
아이디 : <input type="text" name="id">
비밀번호 : <input type="text" name="pass">
<input type="submit" value="로그인">
</form>
--loginProc.jsp
<%
String m_id = "kosta";
String m_pw = "1234";
String name = "홍길동";//인코딩할필요x
String id = request.getParameter("id");
String pass = request.getParameter("pass");
//String name = URLEncoder.encode(m_name, "UTF-8");//인코딩해서 쿠키에 저장
if(id.equals(m_id) && pass.equals(m_pw)){
session.setAttribute("name", name); //key-value
//response.sendRedirect("main.jsp");
}else{
response.sendRedirect("loginForm.jsp");
}
%>
--main.jsp
<%
String name = (String)session.getAttribute("name");
if(name == null){
response.sendRedirect("loginForm.jsp");
}
%>
--logout.jsp
<%
String name = (String)session.getAttribute("name");
if(name == null){
response.sendRedirect("loginForm.jsp");
}else{
session.invalidate();
}
%>
--login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch06 : login.jsp</title>
</head>
<body>
<div align="center">
<H2>로그인</H2>
<form name="form1" method="POST" action="selProduct.jsp">
<input type="text" name="username"/>
<input type="submit" value="로그인"/>
</form>
</div>
</body>
</html>
--selProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
session.setAttribute("username", username);
%>
http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<title>ch06 : selProduct.jsp</title>
</head>
<body>
<div align="center">
<H2>상품선택</H2>
<HR>
${username} 님 환영합니다!!!!
<HR>
<form name="form1" method="POST" action="add.jsp">
<SELECT name="product">
<option>사과</option>
<option>귤</option>
<option>파인애플</option>
<option>자몽</option>
<option>레몬</option>
</SELECT>
<input type="submit" value="추가"/>
</form>
<a href="checkOut.jsp">계산</a>
</div>
</body>
</html>
--add.jsp
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//세션에서 List객체를 구하기
//list->null => List생성, 추가
//list != null => List추가
request.setCharacterEncoding("utf-8");
String product = request.getParameter("product");
List<String> list = (List)session.getAttribute("productlist");
if(list == null){
list = new ArrayList<String>();
session.setAttribute("productlist", list);
}
list.add(product);
%>
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="javascript:history.back()">뒤로가기</a>
<%=product %>
</body>
</html>
--checkOut.jsp
<%
List<String> list = (List)session.getAttribute("productlist");
if(list == null){
out.println("선택한 상품이 없습니다.");
}else{
for(int i=0;i<list.size();i++){
out.println(list.get(i)+"
");
}
}
%>
<% //EL태그버전
List<String> list = (List)session.getAttribute("productlist");
request.setAttribute("list", list);
%>
<body>
<c:if test="${list == null }">
<b>선택한 상품이 없습니다.</b>
</c:if>
<c:if test="${list !=null }">
<ul>
<c:forEach var = "s" items = "${list}">
<li>${s}</li>
</c:forEach>
</ul>
</c:if>
</body>
--selProduct.jsp(+수량, 가격)
가격 : <input type="text" name="price"/>
수량 : <input type="text" name="amount"/>
<input type="submit" value="추가"/>
**Product.java 추가
public class Product {
private String fruit;
private int price;
private int amount;
}
--add.jsp
<%
request.setCharacterEncoding("utf-8");
String fruit = request.getParameter("fruit");
int price = Integer.parseInt(request.getParameter("price"));
int amount =Integer.parseInt(request.getParameter("amount"));
Product p = new Product();
p.setFruit(fruit);
p.setPrice(price);
p.setAmount(amount);
List<Product> list = (List)session.getAttribute("productlist");
if(list == null){
list = new ArrayList<Product>();
session.setAttribute("productlist", list);
}
list.add(p);
%>
--checkOut.jsp
<%
List<Product> list = (List)session.getAttribute("productlist");
request.setAttribute("list", list);
%>
<body>
<c:if test="${list == null }">
<b>선택한 상품이 없습니다.</b>
</c:if>
<c:if test="${list !=null }">
<ul>
<c:set var ="total" value="0"/>
<% int total = 0; %>
<c:forEach var = "s" items = "${list}">
<li>${s.fruit} * ${s.amount} = ${s.price * s.amount }원</li>
<c:set var ="total" value="${total +(s.price * s.amount)}"></c:set>
</c:forEach>
</ul>
결과 : <c:out value="${total}"></c:out>
</c:if>
</body>
<결과>
- 사과 * 2 = 20000원
- 사과 * 2 = 20000원
- 자몽 * 2 = 20000원
- 사과 * 13 = 17329원
- 레몬 * 15 = 48330원
- 사과 * 3 = 100365원
- 파인애플 * 2 = 644원
결과 : 226668
'FULLSTACK > SERVLET&JSP' 카테고리의 다른 글
SERVLET&JSP 6차시 - 페이징처리, 검색, 파일, 이미지 (0) | 2020.11.13 |
---|---|
SERVLET&JSP 6차시 - MVC모델(CRUD) (0) | 2020.11.13 |
SERVLET&JSP 4차시 - memberCRUD 복습, 동적쿼리, 익스프레션언어, JSTL(EL태그) (0) | 2020.11.13 |
SERVLET&JSP 3차시 - CRUD(JSP, MYBATIS) (0) | 2020.11.13 |
SERVLET&JSP 2차시 - 액션태그, 자바빈, JDBC (0) | 2020.11.13 |