52.JSP(3)

sumin·2023년 9월 18일
0

아카데미

목록 보기
53/82
post-thumbnail

Session

html(login + cart)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
  src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script>
//<body>태그를 모두 읽은 뒤 funtcion(){}을 실행한다. 
$(function() {
  $('#btn_logout').click(function() {
    location.href = '${contextPath}/logout';
  })
  
})
</script>
</head>
<body>
<%-- 로그인 안 된 상태 --%>
<c:if test="${sessionScope.id == null}">
  <div>
    <form method="post" action="${contextPath}/login">
      <div>
        <label for="id">아이디</label>
        <input type="text" name="id" id="id">
      </div>
      <div>
        <label for="pw">비밀번호</label>
        <input type="password" name="pw" id="pw">
      </div>
      <div>
        <button type="submit">로그인</button>
      </div>
    </form>
  </div>
<%-- 로그인 된 상태  --%>  
</c:if>
<c:if test="${sessionScope.id != null }">
  <div>${sessionScope.id}님 환영합니다.</div>
  <div>
    <button type="button" id="btn_logout">로그아웃</button>
  </div>
</c:if>
<hr>

<div>
  <form method="get" action="${contextPath}/addToCart">
    <h4> 쇼핑목록</h4>
    <div>
      <select name="item">
        <option>진라면</option>
        <option>신라면</option>
        <option>삼양라면</option>      
      </select>
      <input type="text" name="ea" placeholder="구매개수">
    </div> 
    <div>
      <button type="submit">장바구니추가</button>
    </div>   
  </form>
</div>

</body>
</html>

Login

package ex06_session;

import java.io.IOException;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  // 요청 인코딩
	  request.setCharacterEncoding("UTF-8");
	  
	  // 요청 파라미터 
	  String id = request.getParameter("id");
	  String pw = request.getParameter("pw");
	  
	  //로그인 성공 규칙 :id 와 pw 가 동일 하면 로그인 성공으로 가정하고 풀이 
	  if(id.equals(pw)) {
	  
	    //로그인 처리 : session에 id를 저장해 두기 
	    HttpSession session = request.getSession();
	    session.setAttribute("id", id);
	    session.setMaxInactiveInterval(10 * 60); // 10분간 세션 유지 
	  }
	  
	  // 로그인 화면으로 되돌아가기 
	  response.sendRedirect(request.getContextPath() + "/ex06_session/main.jsp"); //request.getContextPath() = /jsp	    
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

Logout

package ex06_session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Logout
 */
@WebServlet("/logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  
	  // 로그아웃 :session 초기화
	  HttpSession session =request.getSession();
	  session.invalidate();
	  
	  // 로그인 화면으로 돌아가기 
	  response.sendRedirect(request.getContextPath() + "/ex06_session/main.jsp"); //request.getContextPath() = /jsp

	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

Cart 추가하기

package ex06_session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * Servlet implementation class AddToCart
 */
@WebServlet("/addToCart")
public class AddToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//요청 인코딩
	  request.setCharacterEncoding("UTF-8");
	  
	  //요청 파라미터
	  String item = request.getParameter("item");
	  int ea = Integer.parseInt(request.getParameter("ea"));
	  
	  //item + ea -> Map
	  Map<String, Object> map = new HashMap<String, Object>();
	  map.put("item", item);
	  map.put("ea", ea);
	  
	  // 장바구니 처리 방법 : session에 cart 속성을 저장하고 cart에 [item + ea -> Map] 저장하기
	  HttpSession session = request.getSession();
	  List<Map<String, Object>> cart = (List<Map<String, Object>>)session.getAttribute("cart");
	  if(cart == null) {
	    cart = new ArrayList<Map<String,Object>>();
	    session.setAttribute("cart", cart);
	  }
	  
	  // cart에 Map 저장하기 
	  cart.add(map);
	  
	  // 응답 타입과 인코딩
	  response.setContentType("text/html; charset=UTF-8");
	  
	  //응답 출력 스트림
	  PrintWriter out = response.getWriter();
	  
	  // 응답하기 
	  out.println("<script>");       //confirm() 창은 확인창에 취소가 있다. if 와 같이 쓴다. 
	  out.println("if(confirm('" + item + "을 장바구니에 담았습니다. 장바구니로 가려면 \"확인\" 계속 쇼핑하려면 \"취소\" 버튼을 누르세요')){");    
	  out.println("location.href='"+request.getContextPath()+"/ex06_session/cart.jsp'");
	  out.println("}else{"); 
	  out.println("location.href='" + request.getContextPath()+"/ex06_session/main.jsp'");
	  out.println("}");
	  out.println("</script>");
	  out.flush();
	  out.close();
	  
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

cart 비우기

package ex06_session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ClearCart
 */
@WebServlet("/clearCart")
public class ClearCart extends HttpServlet {
	private static final long serialVersionUID = 1L;       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClearCart() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  //장바구니 비우기 :Session에 저장된 cart 지우기 
	  HttpSession session = request.getSession();
	  session.removeAttribute("cart");
	  
	  // main화면으로 되돌아가기 
	  response.sendRedirect(request.getContextPath() + "/ex06_session/main.jsp");
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

MVC

MVC는 Model, View, Controller 의 약자이다.
Model2 방식중에 가장 많이 사용하는 방식이다.

Model1

비지니스 로직과 화면 처리를 모두 JSP로 처리하는 웹 애플리케이션 모델이다.
기능 구형이 쉽고 편리하다. 하지만 디자이너와 개발자 모두 Jsp를 사용하기 때문에 각각의 코드가 섞이므로 유지보수가 어렵고 코드 재사용이 어렵다.

Model2

비지니스 로직과 화면 처리를 Java와 JSP로 분히하여 처리하는 웹 애플리케이션 모델이다.
각 기능이 모듈화 되어 처리되며 디자이너는 화면 기능을 구현하고 개발자는 비지니스 로직을 구현하기 때문에 업무 분할이 가능해진다. 개발 및 유지보수가 쉽고 코드 재사용이 가능하다.

Model2 방식으로 날짜와 시간 나오게 하기

경로
java 아래에 controller와 service 폴더를 만든다. 따로 패키지를 만들지는 않는다.
views 아래에는 결과가 나오는 페이지가 들어간다.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
  src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script>
  $(function(){
    $('#btn').click(function(){
      if($('#type').val() === '1'){
        location.href = '${contextPath}/getDate.do';
      } else if($('#type').val() === '2'){
        location.href = '${contextPath}/getTime.do';
      } else if($('#type').val() === '3'){
        location.href = '${contextPath}/getDatetime.do';
      }
    })
  })
</script>
</head>
<body>

  <div>
  <form method="get">  
    <select id="type">
      <option value="1">현재날짜</option>
      <option value="2">현재시간</option>
      <option value="3">현재날짜시간</option>
    </select>
    <button id="btn" type="button">요청</button>
  </form>
  </div>
</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script
  src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
</head>
<body>

 <c:if test="${today != null}">
  ${today}
</c:if>

<c:if test="${now != null}">
  ${now}
</c:if>  

</body>
</html>

MvcController.java

package controller;

import java.io.IOException;

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

import common.ActionForward;
import service.MvcService;
import service.MvcServiceImpl;

/**
 * Servlet implementation class MvcController
 */
@WebServlet("*.do")
public class MvcController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MvcController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 요청 인코딩 +  응답 타입과 잍코딩
	  request.setCharacterEncoding("UTF-8");
	  response.setContentType("text/html; charset=UTF-8");
	  
	  //요청 확인(URLMApping 확인)
	  String requestURI =request.getRequestURI();        /* /mvc/getData.do */
	  String contextPath = request.getContextPath();     /* /mvc  */
	  String urlMapping  = requestURI.substring(contextPath.length()); /*/getDate.do*/
	  
	  // 서비스 객체  생성(MVC Pattern 에서 Model에 해당함)
	  MvcService mvcService = new MvcServiceImpl();
	  //서비스 실행 결과 (어디로 어떻게 이동해야 하는가)
	 ActionForward af = null;
	   
	  switch(urlMapping) {
	  case "/getDate.do":
	    af = mvcService.getDate(request);
	    break;
	  case "/getTime.do":
	    af = mvcService.getTime(request);
	    break;
	  case "/getDatetime.do":
	    mvcService.getDatetime(request, response); // 반환타입이 void 라서 af 안붙임     
	    break;	      
	  }
	  
	  // 서비스 실행 경과에 의한 이동(redirect와  forward의 선택은 서비스에서 결정함
	  if(af != null) {
	    if(af.isRedirect()) {
	      response.sendRedirect(af.getPath());
	    } else {
	      request.getRequestDispatcher(af.getPath()).forward(request, response);	      
	    }	    
	  }	  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

MvsService.java(interface)

package service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.ActionForward;

public interface MvcService {
  public ActionForward getDate(HttpServletRequest request);
  public ActionForward getTime(HttpServletRequest request);
  public void getDatetime(HttpServletRequest request, HttpServletResponse response);
}

MvcServiceImpl

package service;

import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.ActionForward;

public class MvcServiceImpl implements MvcService {

  @Override
  public ActionForward getDate(HttpServletRequest request) {
    request.setAttribute("today", LocalDate.now().toString());
    return new ActionForward("views/date.jsp", false); //false forward 하겠다. 
    
  }

  @Override
  public ActionForward getTime(HttpServletRequest request) {
    request.setAttribute("now", LocalTime.now().toString());
    return new ActionForward("views/time.jsp", false);
  }
  @Override
  public void getDatetime(HttpServletRequest request, HttpServletResponse response) {
     String datetime = LocalDateTime.now().toString();
     PrintWriter out = null;
     try {
     out = response.getWriter();
     out.println("<script>");
     out.println("alert('" + datetime + "')");                          //요청 결과 보여주기
     out.println("location.href = '" + request.getContextPath() + "'"); //이동하기 (redirect와 같은 방식의 이동)
     out.println("</script>");
     out.flush();
     out.close();
     } catch(Exception e) {
       e.printStackTrace();
     }
}   
}

ActionForward

package common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data     // getter setter 모두 포함 
public class ActionForward {
  private String path; // 어디로 갈 것인가?
  private boolean isRedirect; //redirect는 true, forward 는 false
}

동작 순서

index -> MvcController -> MvcService (MvcServiceImppl) -> result.jsp

profile
백엔드 준비생의 막 블로그

0개의 댓글