javaboiii의 Web/JSP

Web - JSP 예제2

javaboiii 2024. 8. 8. 22:21

JSP

[요구사항]

MemberDTO
MID
PASSWORD
NAME

a.jsp
아이디[ ]
비밀번호[ ]
로그인 버튼 / 회원 가입

b.jsp
로그인 버튼을 누르면 도착하는 페이지
NAME님, 안녕하세요
=== 이 사이트의 회원 목록 ===
teemo 작은 티모
ari 김아리
amumu 아무무

c.jsp
회원가입 버튼을 누르면 도착하는 페이지
아이디[ ]
비밀번호[ ]
이름[ ]
회원 가입 버튼
처음으로 돌아가기

request, response,out,session,JSP 흐름 이해

d.jsp 로그인 기능
e.jsp 회원 가입 기능

 

을 MVC 패턴으로 구현해 주세요

 

[MemberDTO]

package member;

public class MemberDTO {
	private String mid;
	private String password;
	private String name;
	private String condition;
	public String getCondition() {
		return condition;
	}
	public void setCondition(String condition) {
		this.condition = condition;
	}
	public String getMid() {
		return mid;
	}
	public void setMid(String mid) {
		this.mid = mid;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "MemberDTO [mid=" + mid + ", password=" + password + ", name=" + name + ", condition=" + condition + "]";
	}
}

 

[MemberDAO]

package member;

import java.util.ArrayList;

public class MemberDAO {
	private static ArrayList<MemberDTO> datas=new ArrayList<MemberDTO>();

	public boolean insert(MemberDTO memberDTO) {
		MemberDTO data = new MemberDTO();
		data.setMid(memberDTO.getMid());
		data.setPassword(memberDTO.getPassword());
		data.setName(memberDTO.getName());
		MemberDAO.datas.add(data);
		return true;
	}
	public ArrayList<MemberDTO> selectAll(MemberDTO memberDTO){
		ArrayList<MemberDTO> datas = new ArrayList<MemberDTO>();
		for(MemberDTO data:MemberDAO.datas) {
			MemberDTO data1 = new MemberDTO();
			data1.setMid(data.getMid());
			data1.setPassword(data.getPassword());
			data1.setName(data.getName());
			datas.add(data1);
		}
		return datas;
	}
	public MemberDTO selectOne(MemberDTO memberDTO) {
		for(MemberDTO data:MemberDAO.datas) {
			if(memberDTO.getCondition().equals("ID_CHECK")) {
				if(data.getMid().equals(memberDTO.getMid())) {
					return data;
				}
			}
			else if(memberDTO.getCondition().equals("LOGIN")) {
				if(data.getMid().equals(memberDTO.getMid())) {
					if(data.getPassword().equals(memberDTO.getPassword())) {
						return data;
					}
				}
			}
		}
		return null;
	}
}

 

[b.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.ArrayList, member.MemberDTO"%>
<jsp:useBean class="member.MemberDAO" id="memberDAO" />
<jsp:useBean class="member.MemberDTO" id="memberDTO" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String name = (String)session.getAttribute("name");
		
		ArrayList<MemberDTO> datas =memberDAO.selectAll(memberDTO);
	%>
	<h1><%=name%>님 안녕하세요</h1>
	<hr>
	<h3>이 사이트 회원목록</h3>
	<ul>
		<%
			for(MemberDTO data:datas){
		%>
				<li><span><%=data.getMid() %></span>&nbsp;&nbsp;&nbsp;<span><%=data.getName()%></span></li>
		<%
			}
		%>
	</ul>
	<hr>
	<a href="a.jsp">처음으로 돌아가기</a>
</body>
</html>

 

[d.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"
	import="java.util.ArrayList, member.MemberDTO, member.MemberDAO"%>
<jsp:useBean class="member.MemberDAO" id="memberDAO" />
<jsp:useBean class="member.MemberDTO" id="memberDTO" />
<% 
	String id = request.getParameter("mid");
	String pw = request.getParameter("password");
	ArrayList<MemberDTO> datas=memberDAO.selectAll(memberDTO);
	if(datas ==null){
		out.println("<script>alert('로그인 실패');history.go(-1);</script>");
	}
	else {
    	boolean flag = false;
	    memberDTO.setMid(id);
	    memberDTO.setPassword(pw);
	    memberDTO.setCondition("LOGIN");
	    memberDTO = memberDAO.selectOne(memberDTO);
	    
		if(memberDTO != null){
	    	flag=true;
           	session.setAttribute("name", memberDTO.getName());
		}
	     
		if(flag){
	    	response.sendRedirect("b.jsp");
		}
		else{
			out.println("<script>alert('로그인에 실패했습니다!');history.go(-1);</script>");
		}
	}
%>

 

[e.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.ArrayList, member.MemberDTO, member.MemberDAO"%>
<jsp:useBean class="member.MemberDAO" id="memberDAO" />
<%
	String id = request.getParameter("mid");
	String pw = request.getParameter("password");
	String name = request.getParameter("name");
	
	MemberDTO memberDTO = new MemberDTO();
	memberDTO.setMid(id);
	memberDTO.setCondition("ID_CHECK");
	memberDTO = memberDAO.selectOne(memberDTO); 
	
	boolean flag = false;
	if(memberDTO != null){
		out.println("<script>alert('아이디 중복');history.go(-1);</script>");
	}
	else{
		MemberDTO data = new MemberDTO();
		data.setMid(id);
		data.setPassword(pw);
		data.setName(name);
		flag=memberDAO.insert(data);
	}
	if(flag){
		out.println("<script>alert('회원가입 성공');location.href='a.jsp';</script>");
	}
	else{
		out.println("<script>alert('회원가입 실패');history.go(-1);</script>");
	}
%>

useBean의 역할은 new임

<jsp:useBean class="member.MemberDAO" id="memberDAO" />

이 코드는

MemberDAO memberDAO = new MemberDAO();

와 같은 코드

== 생성자  -복선-

 

사건의 시작은 여기부터임 회원가입을 하고

로그인 시도를 하니까 계속 실패가 뜸

회원가입은 성공인데

실패가 계속 나옴

 

아니 왜 대체 왜 왜왜왜왜ㅗ애ㅗ애ㅙ왜왜왜 왜냐고

를 한 삼십분 ?

 

결국 깊은 산속의 고수를 찾아감

 

고수의 답변은 정말 유쾌 상쾌 통쾌 했음

 

 a.jsp, c.jsp 빼고는

useBean을 쓰고 있는데

이 것이 문제 였음

 

useBean을 쓰면 생성자를 호출함

본인은 처음 DAO를 만들 때 생성자 메서드를 만들어서 초기화를 했음

 

자자

처음 브라우저에 접속해서 회원가입을 시도하면 d.jsp에서 생성자를 호출함

 

근데 ?????????????

 

로그인에서 또 useBean이 생성자를 호출하는게 아니겠음???

 

그래서 DAO안 list를 static으로 쓰게 된거였고

 

더 쉬운 방법이 있음

 

[b.jsp], [d.jsp], [e.jsp] 를 이렇게 만들면 조금 더 맛있어짐

 

[b.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.ArrayList, member.MemberDTO" %>
<jsp:useBean id="memberDAO" class="member.MemberDAO" scope="session" />
<jsp:useBean id="memberDTO" class="member.MemberDTO" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    String member = (String)session.getAttribute("member");
    ArrayList<MemberDTO> datas=memberDAO.selectAll(memberDTO);
%>
<%
    if(datas == null){
        out.println("아직 가입한 회원이 없습니다!");
    }
    else{
%>
    <p>### 이 사이트의 회원목록 ###</p>
	<ul>    
        <%
            for(MemberDTO data:datas){
                out.println("<li>"+data.getMid()+" "+data.getName()+"</li>");
            }
        %>
    </ul>
<% } %>

</body>
</html>

 

[d.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.ArrayList, member.MemberDTO" %>
<jsp:useBean id="memberDAO" class="member.MemberDAO" scope="session" />
<jsp:useBean id="memberDTO" class="member.MemberDTO" />
<jsp:setProperty property="*" name="memberDTO" />
<%
	memberDTO=memberDAO.selectOne(memberDTO);
		
	if(memberDTO != null){
		session.setAttribute("member", memberDTO.getName());
		response.sendRedirect("b.jsp");
	}
	else{
		out.println("<script>alert('로그인에 실패했습니다!');history.go(-1);</script>");
	}
%>

 

[e.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.ArrayList, member.MemberDTO" %>
<jsp:useBean id="memberDAO" class="member.MemberDAO" scope="session" />
<jsp:useBean id="memberDTO" class="member.MemberDTO" />
<jsp:setProperty property="*" name="memberDTO" />
<%
	memberDAO.insert(memberDTO);
	out.println("<script>alert('회원가입이 완료되었습니다!');location.href='a.jsp';</script>");
%>

 

주석이 없는게 좀 짜치긴 하는데

맛있는 코드 완성임

 

결론

useBean class="apple.Apple" id="banana"
new 연산자
== Apple banana=new Apple();

 

useBean은
.jsp 코드를 처음부터 끝까지 수행함

하나의 브라우저동안
한번만 만들어라
유지하게
유효 범위를 브라우저 단위로 변경
scope를 sessionScope로 변경

'javaboiii의 Web > JSP' 카테고리의 다른 글

Web - JSP 페이지 처리  (0) 2024.08.12
Web - JSP 페이지 이동 및 데이터 전송 방법  (0) 2024.08.09
Web - JSP) 내장 객체  (0) 2024.08.07
Web - JSP 예제1  (0) 2024.08.07
Web - JSP 기초  (0) 2024.08.06