괴발개발

Collection Framework 메서드 정리 (Arraylist, vector, bean) 본문

BACK END/SPRING

Collection Framework 메서드 정리 (Arraylist, vector, bean)

dinoelll 2023. 3. 8. 23:30

[1.list ]

0. list.jsp

더보기
<%@ 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>
<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>
<!--        // ******번호 지정해주기!!  varStatus-->
        <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>

1.   listAdd

public void listAdd(String todo) {
		list.add(todo);//리스트의 맨 마지막에 데이터를 추가한다.
		//list.add(0, todo);
<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>
protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            String todo = req.getParameter("todo");//client로 부터 받아온 파라메터를...

            //model에 저장하라고 전달해준다.
            ListModel model = new ListModel();
            model.listAdd(todo);
            resp.sendRedirect(req.getContextPath());
		}
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>${todo}</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
		
</c:forEach>

2. getList

public ArrayList<String> getList(){
		return list;
	}
if (addr.equals("/")) {
			
			System.out.println("root 호출");
			RequestDispatcher dis = req.getRequestDispatcher("list.jsp");
			ArrayList<String> list = model.getList();
			req.setAttribute("list", list);
			dis.forward(req, resp);
		}

 

3. listDel

public void listDel(String idx) {
		//list.remove(index); : 지운 값 반환
		//list.remove(value); : 지우기 성공 여부
		String value = list.remove(Integer.parseInt(idx));
		System.out.println("remove : "+ value);
if(addr.equals("/remove")) {
                System.out.println("삭제 요청");
                String idx = req.getParameter("idx");
                model.listDel(idx);
                resp.sendRedirect(ctx);
<c:forEach items="${list}" var="todo" varStatus="stat">
            <tr>
                <td>${stat.index}</td>
                <td>${todo}</td>
                <td><a href="remove?idx=${stat.index}">삭제</a></td>
            </tr>	
</c:forEach>

[2. vector ]

0. index.jsp

더보기
 
<%@ 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>
<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="10%"/>
            <col width="60%"/>
            <col width="15%"/>
            <col width="15%"/>
        </colgroup>
        <thead>
            <tr>
                <th>번호</th>
                <th>할일</th>
                <th>수정</th>
                <th>삭제</th>
            </tr>
        </thead>
        <tbody>
<!--        // ******번호 지정해주기!!  varStatus-->
        <c:forEach items="${list}" var="todo" varStatus="stat">
        <tr>
            <td>${stat.index}</td>
            <td>
                <input type="text" name ="todo" value= "${todo}"/>
            </td>
            <td>
<!--***1)버튼에 온클릭 이벤트를 걸어주고, update 함수안에 다가 stat. 인덱스  값과, 이 클릭된 당사자의
           를 (=${todo})를 넣어줍니다. -->
                <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>
    <a href="clear">모두 삭제</a>
   
   
</body>
<script>
//2)그 다음 function으로 update 함수를 실행하고, idx와 elem을 넣어줍니다..
function update(idx, elem){
    console.log(idx, elem);//idx, todo
   
    //제이커리
   
    //3 ) 그리고 제이커리를 이용해서 elem에 closest를 써서 선택한요소로부터 부모요소들 중에'tr'을 가
    //진것 중에 가장 먼저 나오는것을 찾습니다. 그리고 다시 find를 쓰서 input 타입에 name이 todo 인것을
    // 찾습니다. 그리고 거기서 .val을 써서 밸류값을 가져옵니다. 그 값을 val 변수에 넣어줍니댜ㅏ.
    //그 다음 location.href를 사용해서 특정 url링크를 호출해주고
    //update라는 요청에 get방식으로 파라미터를 넣어주기 위해서 ?를 넣어줍니다.
    // 그리고 idx라는 이름으로 idx변수값을 넣어주고, todo라는 **이름으로 val을 넣어줍니다.
    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);
           
        }
///***** 대 실수..,, update인데 undate라고 침.. ;;;; 진짜;

 

</script>
</html>

1. listAdd

public void listAdd(String todo) {
			vector.add(todo);
<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>
if (addr.equals("/add")) {
			 req.setCharacterEncoding("UTF-8");
			 String todo =req.getParameter("todo");
			 System.out.println(todo);
			 model.listAdd(todo);
			 resp.sendRedirect(ctx);
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>
				<input type="text" name ="todo" value= "${todo}"/>
			</td>
			<td>
				<button onclick="update(${stat.index},this)">수정</button>
			</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
</c:forEach>

2. getList

public  Vector<String> getList(){
			return vector;
		}

 

if (addr.equals("/")) {
			
			System.out.println("root 호출");
			RequestDispatcher dis = req.getRequestDispatcher("list.jsp");
			ArrayList<String> list = model.getList();
			req.setAttribute("list", list);
			dis.forward(req, resp);
		}
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>
				<input type="text" name ="todo" value= "${todo}"/>
			</td>
			<td>
				<button onclick="update(${stat.index},this)">수정</button>
			</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
</c:forEach>

3. listRemove

public void listRemove(int idx){
			String value = vector.remove(idx);
				System.out.println("remove : " +  value);
if (addr.equals("/remove")) {
			String idx = req.getParameter("idx");
			
			System.out.println("idx : "+idx);
			
			model.listRemove(Integer.parseInt(idx));
			resp.sendRedirect(ctx);
		}
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>
				<input type="text" name ="todo" value= "${todo}"/>
			</td>
			<td>
				<button onclick="update(${stat.index},this)">수정</button>
			</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
</c:forEach>

4. listUpdate

public void listUpdate(String idx, String todo) { // 수정 시켜주는거임
			vector.set(Integer.parseInt(idx), todo);//(대상 인덱스, 바꿀 값 ): 이전 값
			
		}
if (addr.equals("/update")) {
			String idx = req.getParameter("idx");
			String todo =req.getParameter("todo");
			System.out.println("update : "+ idx+" : " +todo);
			model.listUpdate(idx, todo);
			resp.sendRedirect(ctx);
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>
				<input type="text" name ="todo" value= "${todo}"/>
			</td>
			<td>
				<button onclick="update(${stat.index},this)">수정</button>
			</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
</c:forEach>
function update(idx, elem){
	console.log(idx, elem);//idx, todo
	var val = $(elem).closest('tr').find('input[name="todo"]').val();
	console.log(idx,val);
	location.href='update?idx='+idx+'&todo='+val;

5. listClear

public void listClear() {
			if(vector.isEmpty() == false) {//비워져 있는가?
				
				vector.clear();// 모두 지우기
<c:forEach items="${list}" var="todo" varStatus="stat">
		<tr>
			<td>${stat.index}</td>
			<td>
				<input type="text" name ="todo" value= "${todo}"/>
			</td>
			<td>
				<button onclick="update(${stat.index},this)">수정</button>
			</td>
			<td><a href="remove?idx=${stat.index}">삭제</a></td>
		</tr>
</c:forEach>

 

[3. board ]

0.1 writeForm.jsp

더보기
<%@ 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>
<style>
table, th, td{
        border: 1px solid black;
        border-collapse: collapse;
        padding: 5px 10px;
       
   
    }
    button{
        margin: 5px;
   
    }
    table{
        width: 500px;
    }
    input[type="text"]{
        width: 100%;
    }
    textarea{
        width: 100%;
        height: 150px;
        resize: none;
    }

 

</style>
</head>
<body>

 

<!--    1) write라는 요청 보냈을때 컨트롤러에서 받을 수 있도록 폼에 action속성을 넣고 write를 넣어주었습니다
 -->

 

    <form action="write" method="post">
        <table>
            <tr>
                <th>작성자</th>
                <td><input type="text" name="user_name"/></td>
            </tr>
            <tr>
                <th>제목</th>
                <td><input type="text" name="subject"/></td>
            </tr>
            <tr>
                <th>내용</th>
                <td><textarea name="content"></textarea></td>
            </tr>
            <tr>
                <th colspan="2"><button>작성</button></th>
               
            </tr>
           
        </table>
    </form>

 

</body>
<script></script>
</html>

0.2. list.jsp

더보기
<%@ 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>
<style>
    table, th, td{
        border: 1px solid black;
        border-collapse: collapse;
        padding: 5px 10px;
       
   
    }
    button{
        margin: 5px;
   
    }
</style>
</head>
<body>
    <button onclick="location.href='writeForm.jsp'">글쓰기</button>
    <table>
        <colgroup>
            <col width="10%"/>
            <col width="50%"/>
            <col width="20%"/>
            <col width="20%"/>
           
        </colgroup>
        <thead>
            <tr>
                <th>no</th>
                <th>제목</th>
                <th>작성자</th>
                <th>삭제</th>
            </tr>
        </thead>
        <tbody>
            <c:if test="${list.size()==0 }">
                <tr>
                    <th colspan="4">작성된 글이 존재하지 않습니다.</th>
                </tr>
            </c:if>
<!--                el 태그에서는 객체 내 private필드를 getter()를 사용하지 않고 꺼내올 수 있다. -->
            <c:if test="${list.size()>0 }">
<!--            // 3:1:20 ?? 뭐 어쩍 들고 올 수 잇는거-->
                <c:forEach items="${list }" var="board" varStatus="stat">
                <tr>    
                    <td>${stat.index }</td>
                    <td><a href="detail?idx=${stat.index}">${board.subject }</a></td>
<!--                    그냥 board만 쓰면 객체이기 때문에 뒤에 .subject를 넣어야 한다. (안그러면 @12312뭐
이런 식으로 나옴), 필요한건 유저 언더바 밑ㅇ에 서브잭트와 유저네임임 그래서 겟 어쩌구 해서 들어와야함. 원래는
근데 이엘태그에서는 쩜 찍고 필드명만 써도 객에 안의 값을 가져올 수 있음 이엘태그니까 가능한거임. 프라이빗으로 해놨기때문에
원래는 안된다. 프라이빗에는 쩜찍고 해당속성에서 접근 가능함.
** 당연히 겟터와 셋터가 열려잇어야함.-->
                    <td>${board.user_name }</td>
                    <td><a href="remove?idx=${stat.index}">삭제</a></td>
                </tr>
                </c:forEach>
               
           
            </c:if>
        </tbody>
    </table>

 

</body>
<script></script>
</html>

0.3.detail.jsp

더보기
<%@ 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>
<style>
table, th, td{
        border: 1px solid black;
        border-collapse: collapse;
        padding: 5px 10px;
       
   
    }
    button{
        margin: 5px;
   
    }
    table{
        width: 500px;
    }
   

 

</style>
</head>
<body>



   
        <table>
            <tr>
                <th>작성자</th>
                <td>${board.user_name }</td>
               
<!--                ** r게서 셋터 없으면 저거 안된다.! el xorm -->
            </tr>
            <tr>
                <th>제목</th>
                <td>${board.subject }</td>
            </tr>
            <tr>
                <th>내용</th>
                <td>${board.content }</td>
            </tr>
            <tr>
                <th colspan="2">
                    <a href="./">리스트로 돌아가기</a>
                </th>
               
            </tr>
           
        </table>
   

 

</body>
<script></script>
</html>

+boardbean

더보기
//*** (캡슐과)빈 규약 - private으로 생성하고 ***getter(열기) 와 setter로 데이터를 다룰 것
public class BoardBean {
    private String user_name;
    private String subject;
    private String content;
   
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

1. write

public void write (String user_name, String subject, String content) {
		// 1. 객체 생성해서
		BoardBean bean = new BoardBean();
		//2.  받아온 값을 넣고
		bean.setUser_name(user_name);
		bean.setSubject(subject);
		bean.setContent(content);
		
		// 3.해당 객체를 리스트에 넣는다.
		list.add(bean); //1] 리스트에 추가해 줄껀데 해줄려면 객체화 필요하고 비어잇으니가
		
		
	}

2. getList

public ArrayList<BoardBean> getList() {
		
		return list;
	}
더보기
if (addr.equals("/")) {
            req.setAttribute("list", model.getList()); // 리스트란 이름으로 아아 던진거 오키오키
            dis = req.getRequestDispatcher("list.jsp");
            dis.forward(req, resp);
           
 

3. detail

public  BoardBean detail(String idx) {
		
		//두가지 방법
		<1>
        //BoardBean bean = list.get(Integer.parseInt(idx));
       		 return bean
        
        <2>
		return list.get(Integer.parseInt(idx));
	}
더보기
if(addr.equals("/detail")) {
            String idx = req.getParameter("idx");
            System.out.println("detail :"+idx);
            req.setAttribute("board", model.detail(idx));
            dis = req.getRequestDispatcher("detail.jsp");
            dis.forward(req, resp);

4. remove

public void remove(String idx) {
		list.remove(Integer.parseInt(idx));
		
	}
더보기
if(addr.equals("/remove")) {
            String idx = req.getParameter("idx");
            model.remove(idx);
            //반환하는 값 없으니까 그냥 메서드만 써줘도 됨.
            System.out.println("remove"+idx);
            resp.sendRedirect(ctx);
        }
Comments