본문 바로가기
코딩도전기/MVC

CODO Day23~24_JAVA_MVC(Collection Framework - ArrayList/Vector)

by 코도꼬마 2023. 3. 6.

Collection Framework(interface)

  • Collection interface를 최상위로 하는 자료구조 interface 
  • List, Set, Map interface를 implements하여 각 collection으로 사용
  • 다양한 자료구조를 가짐
  • 초기선언 시 크기를 지정하지 않아 유동적으로 사용가능(크기 무한)
  • 최상위 collection과 하위 List, Set, Map interface를 구현하기 때문에
    Collection Framework에서 데이터 추가,삭제, 검색 방법은 거의 비슷

 

 

 

List Collection - ArrayList

  • Array List는 index로 객체를 관리한다는 점에서는 Array와 유사
  • But  Array와 달리 index가 유연(지정한 크기 넘어도 됨)
  • 크기가 무제한(10개 이하의 객체 저장시 Array 사용/그이상은 arrayList 사용)
  • <>(Generic) : 해당 자료구조에 들어갈 데이터 타입을 강제함(클래스타입으로 지정해줘야 함(Integer, Long))
  • Array List는 객체 삭제/추가 시 인덱스가 1씩 당겨지거나 미뤄지기 때문에 
    빈번한 객체의 추가, 삭제가 일어날 때 다소 무리

 

  • list.jsp(arrayList를 이용한 todoList 만들기)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<style>
   table, th, td{
      width: 500px;
      border: 1px solid black;
      border-collapse: collapse;
      padding: 5px 10px;
   }
   input[type="text"]{
      width: 100%;
   }
   button{
      width: 100%;
   }
</style>
</head>
<body>
   <h3>TO DO LIST</h3>
   <form action="add" method="post">
      <table class="input">
         <colgroup>
            <col width="80%"/>
            <col width="20%"/>
         </colgroup>
         <tr>
            <td><input type="text" name="todo"/></td>
            <td><button>입력</button></td>
         </tr>
      </table>
   </form>
   
   <c:if test="${list.size() == 0}">나만의 할 일을 입력 해 보세요!</c:if>
   <c:if test="${list.size() > 0}">
   <table>
      <colgroup>
         <col width="15%"/>
         <col width="70%"/>
         <col width="15%"/>
      </colgroup>
      <thead>
         <tr>
            <th>번호</th>
            <th>할일</th>
            <th>삭제</th>
         </tr>
      </thead>
      <tbody>
      <c:forEach items="${list}" var="todo" varStatus="stat">
      <tr>
         <td>${stat.index}</td>
         <td>${todo}</td>
         <!-- remove라는 요청주소로 idx라는 파라메터 이름으로 값을 전송(GET) -->
         <td><a href="remove?idx=${stat.index}">삭제</a></td>
      </tr>
      </c:forEach>
      </tbody>      
   </table>
   </c:if>
   
</body>
<script>
	var msg = "${msg}";
	if(msg != ""){
		alert(msg);
	}
</script>
</html>

 

  • ListModel
package kr.co.web.model;

import java.util.ArrayList;

public class ListModel {
		//객체화하여도 한 곳에 저장되도록
		static ArrayList<String> list = new ArrayList<String>(); 
		
		public void listAdd(String todo) {
			list.add(todo); //리스트의 맨 마지막에 데이터를 추가
			//System.out.println("list 0번 인덱스 : " + list.get(0));
			//list.add(0, todo);  특정 인덱스에 값을 넣어줄 수도 있음
		}
		
		public ArrayList<String> getList(){
			return list;
		}

		public void listDel(String idx) {
			//list.remove(index); : 지운 값 반환(String)
			//list.remove(value); : 지우기 성공여부(boolean)
			String value = list.remove(Integer.parseInt(idx));
			System.out.println("remove : "+ value);
		}
}

 

  • ListController
package kr.co.web.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
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 kr.co.web.model.ListModel;

@WebServlet(urlPatterns = {"/", "/add","/remove"})
public class ListController extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		String uri = req.getRequestURI();
		String ctx = req.getContextPath();
		String addr = uri.substring(ctx.length());
		System.out.println(addr);
		
		ListModel model = new ListModel();
		
		if(addr.equals("/")) {
			System.out.println("root호출");			
			RequestDispatcher dis = req.getRequestDispatcher("list.jsp");
			ArrayList<String> list = model.getList();
			//System.out.println("list 0번 인덱스 : " + list.get(0));
			req.setAttribute("list", list);	
			dis.forward(req, resp);
		}
		
		if(addr.equals("/remove")) {
			System.out.println("삭제요청");
			String idx = req.getParameter("idx");
			model.listDel(idx);
			//forward로 보내보기
			//resp.sendRedirect(ctx);
			String msg = "정상적으로 삭제되었습니다.";
			
			req.setAttribute("msg", msg);		
			RequestDispatcher dis = req.getRequestDispatcher("/");
			dis.forward(req, resp);
		}				
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		
		String todo = req.getParameter("todo"); //client로 부터 받아온 파라메터를
		//System.out.println(todo);
		
		//model에 저장하라고 전달
		ListModel model = new ListModel();
		model.listAdd(todo);
		
		//단순하게 이동만 할 경우 or 서버에 요청을 할 경우에는 sendRedirect 사용
        //redirect는 context 경로를 포함해서 보내야 함
		resp.sendRedirect(req.getContextPath()); 
	}
}

 

 

 

Vector

  • Array List와 달리 특정 Thread가 접근하고 있을 경우 다른 Thread가 접근할 수 없음
  • 쉽게 말하면 누군가 사용하고 있으면 다른 사람은 사용할 수 없음
  • becuase 한번에 한명만 사용해야 할 경우 사용

 

  • list.jsp(vector를 이용한 todoList 만들기/수정$전체삭제 기능 추가)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<style>
   table, th, td{
      width: 500px;
      border: 1px solid black;
      border-collapse: collapse;
      padding: 5px 10px;
   }
   input[type="text"]{
      width: 100%;
   }
   button{
      width: 100%;
   }
   input[name="todo"]{
   	border-width: 0px;
   }
</style>
</head>
<body>
   <h3>TO DO LIST</h3>
   <form action="add" method="post">
      <table class="input">
         <colgroup>
            <col width="80%"/>
            <col width="20%"/>
         </colgroup>
         <tr>
            <td><input type="text" name="todo"/></td>
            <td><button>입력</button></td>
         </tr>
      </table>
   </form>
   
   <c:if test="${list.size() == 0}">나만의 할 일을 입력해보세요!</c:if>
   <c:if test="${list.size() > 0}">
   <table>
      <colgroup>
         <col width="15%"/>
         <col width="55%"/>
         <col width="15%"/>
         <col width="15%"/>
      </colgroup>
      <thead>
         <tr>
            <th>번호</th>
            <th>할일</th>
            <th>수정</th>
            <th>삭제</th>
         </tr>
      </thead>
      <tbody>
      <c:forEach items="${list}" var="todo" varStatus="stat">
      <tr>
         <th>${stat.index}</th>
         <td>
         	<input type="text" name="todo" value="${todo}"/>
       	</td>
         <td>
         	<button onclick="update(${stat.index}, this)">수정</button>
         </td>
         <!-- remove라는 요청주소로 idx라는 파라메터 이름으로 값을 전송(GET) -->
         <td><a href="remove?idx=${stat.index}">삭제</a></td>
      </tr>
      </c:forEach>
      </tbody>      
   </table>
   </c:if> 
   <br/><br/>
   <a href="clear">모두삭제</a>  
</body>
<script>
	function update(idx, elem) {
		console.log(idx,elem);  //idx, content
		var val = $(elem).closest('tr').find('input[name="todo"]').val();
		console.log(idx,val);
		location.href='update?idx='+idx+'&todo='+val;
	}	
	
	var msg = "${msg}";
	if(msg != ""){
		alert(msg);
	}
</script>
</html>

 

  • VectorModel
package kr.co.web.model;

import java.util.Vector;

public class VectorModel {

	private static Vector<String> vector = new Vector<String>();
	
	public void listAdd(String todo) {
		vector.add(todo);
	}
	
	public Vector<String> getList(){
		return vector;
	}
	
	public void listDel(int idx) {
		String result = vector.remove(idx);
		System.out.println("remove : " + result);
	}

	public void listUpdate(String idx, String todo) {
		//대상인덱스, 바꿀값 : 이전값
		String value = vector.set(Integer.parseInt(idx), todo); 
		System.out.println(value);
	}

	public void listClear() {
		
		if(!vector.isEmpty()) { //비워져있어?
			vector.clear(); //모두 지워
		}
	}

}

 

  • VectorController
package kr.co.web.controller;

import java.io.IOException;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
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.websocket.SendResult;

import kr.co.web.model.VectorModel;

@WebServlet(urlPatterns = {"/", "/add", "/remove","/update"})
public class VectorController extends HttpServlet {
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		dual(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		dual(req, resp);
	}
	
	VectorModel model = new VectorModel();
	
	//get으로 오던지 post로 오던지 이 메서드에서 처리
	private void dual(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		req.setCharacterEncoding("UTF-8");
		
		String uri = req.getRequestURI();
		String ctx = req.getContextPath();
		String addr = uri.substring(ctx.length());
		//System.out.println(addr);
		String idx = req.getParameter("idx");
		String todo = req.getParameter("todo");

		if(addr.equals("/")) {			
			Vector<String> list = model.getList();
			System.out.println(list);
			req.setAttribute("list", list);
			RequestDispatcher dis = req.getRequestDispatcher("list.jsp");
			dis.forward(req, resp);			
		}
		
		if(addr.equals("/add")) {
			//String todo = req.getParameter("todo");
			System.out.println(todo);
			model.listAdd(todo);
			req.setAttribute("todo", todo);
			resp.sendRedirect(req.getContextPath());	
			System.out.println(req.getContextPath());
		}
		
		if(addr.equals("/remove")) {			
			//String idx = req.getParameter("idx");
			model.listDel(Integer.parseInt(idx));
			String msg = "정상적으로 삭제되었습니다.";
			req.setAttribute("msg", msg);
			RequestDispatcher dis = req.getRequestDispatcher("/");
			dis.forward(req, resp);
		}
		
		if(addr.equals("/update")) {
			System.out.println("update : "+idx+" : "+todo);
			model.listUpdate(idx, todo);
			resp.sendRedirect(ctx);
		}
		
		if(addr.equals("/clear")) {
			model.listClear();
			resp.sendRedirect(ctx);
		}
		
	}

}