jstl, MVC

문이빈·2023년 9월 7일
0

jstl

Java 에서는

  • NumberFormat
  • SimpleDateFormat

jstl 에서는

  • formatNumber: 숫자 형식을 바꿈
  • maxFractionDigits: "1" 소수점 이하 첫째자리까지 출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>숫자 형식</h2>
<fmt:formatNumber type="number" value="123456789"></fmt:formatNumber><br>
<fmt:formatNumber type="number" value="123456789.88"></fmt:formatNumber><br>
<fmt:formatNumber type="number" value="123456789.88" maxFractionDigits="1"></fmt:formatNumber><br>
<br>


<fmt:formatNumber type="number" value="123456.78" pattern="#,###"></fmt:formatNumber><br>
<fmt:formatNumber type="number" value="123456.789" pattern=".##"></fmt:formatNumber><br>
<fmt:formatNumber type="number" value="123456.789" pattern="#,###.##"></fmt:formatNumber><br>
<br>

<fmt:formatNumber type="number" value="0000.00" pattern="#,###.##"/><br>
<fmt:formatNumber type="number" value="0000.00" pattern="0,000.00"/><br> <!-- 강제로 0을 표시 -->
<fmt:formatNumber type="number" value="12.3" pattern="000.00"/><br>
<br>

<h2>날짜 형식</h2>
<c:set var="now" value="<%=new java.util.Date() %>"/>

<c:out value="${now }"/><br>
date : <fmt:formatDate value="${now }" type="date"/><br>
time : <fmt:formatDate value="${now }" type="time"/><br>
both : <fmt:formatDate value="${now }" type="both"/><br>
<br>

<fmt:formatDate value="${now }" pattern="yyyy-MM-dd hh:mm" type="both"/><br>
<fmt:formatDate value="${now }" pattern="yyyy-MM-dd" type="date"/><br>
<fmt:formatDate value="${now }" pattern="yy-MM-dd E요일 a" type="date"/><br>
<fmt:formatDate value="${now }" pattern="HH:mm:ss" type="time"/><br>
<br>

</body>
</html>


sendRediredct 와 forward의 차이

page - pageScope < request - requestScope < session - sessionScope < applicationScope
원래 단어 + Scope

순서로 호출(찾는다) : pageScope -> requestScope -> sessionScope -> applicationScope

-----------------------jstlStart.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<font color="red"><b>
start.jsp - sendProc.jsp - sendResult.jsp 페이지 이동합니다.<br>
sendRedirect로 이동하므로 데이터는 공유하지 않습니다.<br>
주소는 sendResult.jsp가 보인다<br>
</b></font>
<br>

<font color="blue"><b>
start.jsp - forwardProc.jsp - forwardResult.jsp 페이지 이동합니다.<br>
forward로 이동하므로 데이터는 공유합니다.<br>
주소는 forwardProc.jsp로 보이지만 결과는 forwardResult.jsp가 나온다<br>
</b></font>
<br>

<input type="button" value="sendRedirect" onclick="location.href='sendProc.jsp'">
<input type="button" value="forward" onclick="location.href='forwardProc.jsp'">

</body>
</html>

-----------------------sendProc.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>


<%
// 자바의 역할만 하는 페이지

List<String> list = new ArrayList<String>();
list.add("호랑이");
list.add("사자");
list.add("기린");
list.add("코끼리");
list.add("타조");
list.add("코알라");
list.add("여우");

/* 
// 페이지 이동
response.sendRedirect("sendResult.jsp?list=" + list); 객체는 주소를 통해서 넘길 수 가 없다. 
*/

// 페이지 이동 - 객체는 주소를 통해서 넘길 수 가 없다.
request.setAttribute("list", list);

%>

-----------------------sendResult.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
결과 = ${ requestScope.list} <!-- 웹으로 처리하면 값이 비어잇다... -->
</body>
</html>

-----------------------forwardProc.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>

<%
// 자바의 역할만 하는 페이지

List<String> list = new ArrayList<String>();
list.add("호랑이");
list.add("사자");
list.add("기린");
list.add("코끼리");
list.add("타조");
list.add("코알라");
list.add("여우");


// 페이지 이동 - 객체는 주소를 통해서 넘길 수 가 없다.
request.setAttribute("list", list);

// 페이지 이동
RequestDispatcher dispatcher = request.getRequestDispatcher("forwardResult.jsp"); // 상대번지
dispatcher.forward(request, response); // 제어권 넘기기
%>

<%-- <jsp:forward page="forwardResult.jsp"></jsp:forward> --%>

-----------------------forwardResult.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
결과 = ${ requestScope.list}
</body>
</html>

request.getAttribute() ==== ${ requestScope}
sendProc는 안나오고 forward만 나옴 - sendRedirect 와 forword의 차이

다른 애임 데이터 공유 없음.
jsp 태그 잘 안씀

객체는 주소를 통해서 넘길수가 없다. - request 객체에 담아서 보낸다.

위 작업에서 추가적으로

-----------------------forwardProc.jsp-----------------------

<%@ page import="com.jstl.PersonDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>

<%
// 자바의 역할만 하는 페이지

List<String> list = new ArrayList<String>();
list.add("호랑이");
list.add("사자");
list.add("기린");
list.add("코끼리");
list.add("타조");
list.add("코알라");
list.add("여우");

PersonDTO aa = new PersonDTO("홍길동", 25);
PersonDTO bb = new PersonDTO("라이언", 23);
PersonDTO cc = new PersonDTO("프로도", 30);

List<PersonDTO> list2 = new ArrayList<PersonDTO>();
list2.add(aa);
list2.add(bb);
list2.add(cc);

// 페이지 이동 - 객체는 주소를 통해서 넘길 수 가 없다.
request.setAttribute("list", list);
request.setAttribute("list2", list2);

// 페이지 이동
RequestDispatcher dispatcher = request.getRequestDispatcher("forwardResult.jsp"); // 상대번지
dispatcher.forward(request, response); // 제어권 넘기기
%>

<%-- <jsp:forward page="forwardResult.jsp"></jsp:forward> --%>

-----------------------forwardResult.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
결과 = ${ requestScope.list}<br><br>

세번째 항목 = ${ requestScope.list[2] }<br><br>

결과 list2 = ${ requestScope.list2 }<br><br>

이름 = ${ requestScope.list2[0].getName() } &emsp; 나이 = ${ requestScope.list2[0].getAge() }<br>
이름 = ${ requestScope.list2[1].getName() } &emsp; 나이 = ${ requestScope.list2[1].getAge() }<br>
이름 = ${ requestScope.list2[2].getName() } &emsp; 나이 = ${ requestScope.list2[2].getAge() }<br>
<br>

<h3>메소드명을 변수명처럼 사용</h3> 
이름 = ${ requestScope.list2[0].name } &emsp; 나이 = ${ requestScope.list2[0].age }<br>
이름 = ${ requestScope.list2[1].name } &emsp; 나이 = ${ requestScope.list2[1].age }<br>
이름 = ${ requestScope.list2[2].name } &emsp; 나이 = ${ requestScope.list2[2].age }<br>
<!-- getName() = name ,  getAge() = age -->
<br>

<h3>forEach</h3>
<h5>list2를 pageScope -> requestScope -> sessionScope -> applicationScope 순으로 찾는다.</h5>
<c:forEach var="personDTO" items="${ requestScope.list2 }"> 
<!-- for(PersonDTO personDTO : list2){}과 같은 식 -->
	이름 = ${ personDTO.name } &emsp; 나이 = ${ personDTO.age }<br>
</c:forEach>

</body>
</html>

-----------------------PersonDTO.java-----------------------

package com.jstl;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@Setter
@Getter
@AllArgsConstructor 	 /* 생성자 */
@NoArgsConstructor 		 /* 기본 생성자 */
@RequiredArgsConstructor /* 내가 원하는 생성자만 */

public class PersonDTO {
	
	@NonNull 			 /* 내가 원하는 생성자만 근데 대신 name은 null이 아님 */
	private String name;
	private int age;
	
}


MVC(모델 2 기법)

jsp 파일명이 꼭 들어와야지 jsp로 보낼수 있음

회원가입도 로그인도 서블릿으로 보내고, 클래스가 아닌 이름을 부여한다.

환경설정 파일 만들기 -> 만들었으니까 web.xml에 등록해줘야 됨

-----------------------ContorlServlet.servlet-----------------------

package com.control;

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;


@WebServlet("/ContorlServelt")
public class ContorlServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath());
			
			execute(request, response); // get방식으로 요청하면 execute 보내버려 
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { doGet(request, response);
			
			execute(request, response); // post방식으로 요청해도 execute 보내버려 ★한글 처리 신경써야됨★
		
	}
	
	protected void execute(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { doGet(request, response);
			// 한글처리
			if(request.getMethod().equals("POST")){ // form태그에 method를 가져왔는데 post랑 같으면~
				request.setCharacterEncoding("UTF-8");
			}//if
	}

}


-----------------------loginForm.do.jsp-----------------------
memberJSP에서 했던거 가져와서 form태그 안에 action 지움

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse:collapse;
}

#memberloginForm div{
	font-size: 8pt;
	font-weight: bold;
	color: red;
}
</style>
</head>
<body>
<form id="memberloginForm" method="post">
	<table border="1" cellspacing ="0" cellpadding ="7">
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" id="id" name="id" placeholder="아이디 입력" size="30">
				<div id="idDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>비밀번호</th>
			<td >
				<input type="password" id="pwd" name="pwd" size="40">
				<div id="pwdDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th colspan="2">
				<button type="button" id="loginBtn">로그인</button>
				<button type="button" onclick="location.href='writeForm.jsp'">회원가입</button>
			</th>
		</tr>
	</table>
</form>

<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(function(){
	$('#loginBtn').click(function(){
		$('#idDiv').empty();
		$('#pwdDiv').empty();
		
		if($('#id').val()==''){
			$('#idDiv').text('아이디를 입력하세요.');
			$('#id').focus();
			
		}else if($('#pwd').val()==''){
			$('#pwdDiv').text('비밀번호를 입력하세요.');
			$('#pwd').focus();
			
		}else{
			$('#memberloginForm').submit();
		}
	});
});
</script>
</body>
</html>


-----------------------wirteForm.do.jsp-----------------------
memberJSP에서 했던거 가져와서 form태그 안에 action 지움

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse:collapse;
}

#memberWriteForm div{
	font-size: 8pt;
	font-weight: bold;
	color: red;
}
</style>
</head>
<body>
<form id = "memberWriteForm" method="post">
	<table border="1" cellspacing ="0" cellpadding ="7">
		<tr>
			<td width="100" align ="center">이 름</td>
			<td>
				<input type="text" id="name" name="name" placeholder= "이름 입력">
				<div id="nameDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>아이디</th>
			<td>
				<input type="text" id="id" name="id" placeholder="아이디 입력" size="30">
				<input type="button" value="중복체크" onclick="checkID()">
				<input type="text" id="sw"> 
				<div id="idDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>비밀번호</th>
			<td>
				<input type="password" id="pwd" name="pwd" size="40">
				<div id="pwdDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>재확인</th>
			<td>
				<input type="password" name="repwd" id="repwd" size="40">
				<div id="repwdDiv"></div>					
			</td>
		</tr>
		
		<tr>
			<td align = "center">성 별</td>
			<td>
					<input type="radio" name="gender" value="0">남성
					<input type="radio" name="gender" value="1">여성				
			</td>
		</tr>
		
		
		<tr>
			<th><label>이메일</label></th>
			<td>
				<input type="text" name="email1" id="email1" style="width:120px;">
				@
				<input type="text" name="email2" id="email2" style="width:120px;">
				<select name="email3" id="email3" style="width:120px;">
				<option value="직접입력">직접입력</option>
				<option value="naver.com">naver.com</option>
				<option value="gmail.com">gmail.com</option>
				<option value="nate.com">nate.com</option>
				</select>
			</td>
				
		</tr>
		
		<tr>
			<td><label>휴대폰</label></td>
			<td>
				<select name="tel1" id="tel1">
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="019">019</option>
				</select>
				<input type="tel" id="tel2" name="tel2">	
				<input type="tel" id="tel3" name="tel3">	
			</td>
				
		</tr>
		
		
		<tr>
			<th><label>주 소</label></th>
			<td>
				<input type= "text" name="zipcode" id="zipcode"readonly>
				<input type= "button" value="우편번호검색" id="checkPostBtn"><br>
				<input type= "text" name="addr1" id="addr1" style="width: 400px;" placeholder="주소" readonly/><br>
				<input type= "text" name="addr2" id="addr2" style="width: 400px;" placeholder="상세주소"><br>
			</td>
		</tr>
		
		<tr>
			<th colspan="2">
				<button type="button" id="writeBtn">회원가입</button>
				<button type="button">다시작성</button>
			</th>
		</tr>
	</table>
</form>

<script type="text/javascript">
function checkID(){
//	var id = document.폼이름.name속성명.value;
//	var id = document.getElementById("id명").value;
	var id = document.getElementById("id").value;
	
	if(id =="")
		document.getElementById("idDiv").innerText = "먼저 아이디를 입력하세요.";
	else
		window.open("checkId.jsp?id=" +id, "checkId", "width=400 height=150 top=300 left=700");
}
</script>

<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="http://localhost:8080/memberJSP/js/write.js"></script>
<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script src="http://localhost:8080/memberJSP/js/post.js"></script>
</body>
</html>

-----------------------command.properties-----------------------
properties오타내면 안됨 (띄어쓰기 절대 ㄴ)

/member/writeForm.do=member.service.WriteFormService
/member/loginForm.do=member.service.LoginFormService

-----------------------CommandProcess.interface-----------------------

package com.control;

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

public interface CommandProcess { //abstract 생략가능
   
   public abstract String requestPro(HttpServletRequest request, HttpServletResponse response);//추상메소드
   
}

-----------------------WriteFormService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

public class WriteFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/writeForm.jsp";
   }
}

-----------------------loginFormService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

public class LoginFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/loginForm.jsp";
   }
}

-----------------------web.xml-----------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  
  <!-- 
  <servlet>
  	<servlet-name>ContorlServelt</servlet-name>
  	<servlet-class>com.control.ContorlServelt</servlet-class> 서블릿은 command.properties의 도움을 받겠다~
  	<init-param>
  		<param-name>propertyConfig</param-name>
  		<param-value>D:/web/workspace/memberMVC/src/main/webapp/WEB-INF/command.properties</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ContorlServelt</servlet-name>
  	<url-pattern>*.do</url-pattern> 
  	앞에는 상관없는데 .do로 끝나면 서블릿(com.control.ContorlServelt)을 요청하는 것으로 판단하겠다
  </servlet-mapping> 
  -->
 <display-name>memberMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
</web-app>

-----------------------ContorlServelt.servelt-----------------------

package com.control;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

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


@WebServlet(
		urlPatterns = {"*.do"},
		initParams = { @WebInitParam(name="propertyConfig", value="command.properties") }
		)
public class ContorlServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Map<String, Object> map = new HashMap<String, Object>();
	
	@Override
	public void init(ServletConfig config) throws ServletException { // init
		
		String propertyConfig = config.getInitParameter("propertyConfig");
		System.out.println("propertyConfig = " + propertyConfig);
		
		// 만약에 web.xml로 설정하면 아래의 3줄이 필요가 없음.--------------------------------
		String realFolder = config.getServletContext().getRealPath("/WEB-INF");  
		String realPath = realFolder + "/" + propertyConfig; // realPath로 WEB-INF위치를 가져와 서 propertyConfig랑 같은 이름을 가져오세요
		System.out.println("realPath = " + realPath);
		// ------------------------------------------------------------------------
		
		FileInputStream fin = null;
		Properties properties = new Properties(); 
		
		
		try {
			// 만약에 web.xml로 설정하면 fin = new FileInputStream(propertyConfig);로 바껴야된다.
			fin = new FileInputStream(realPath);
	                  
	         properties.load(fin); // /member/writeForm.do=member.service.WriteFormService여기에 있는 내용을 읽고 가져와라
	         System.out.println("properties = " + properties);
	         
	      } catch (IOException e) {
	         e.printStackTrace();
	      }finally{
	         try {
	            fin.close();
	         } catch (IOException e) {
	            e.printStackTrace();
	         }
	      }
	      System.out.println();
	      
	      Iterator it = properties.keySet().iterator();
	      while(it.hasNext()) {
	         String key = (String)it.next();
	         System.out.println("key = "+key);
	         
	         String className = properties.getProperty(key);
	         System.out.println("className = "+className);
	         
	         try {
	            Class<?> classType = Class.forName(className);
	            Object ob = classType.newInstance();
	            
	            System.out.println("ob = "+ob);
	            
	            map.put(key, ob);
	            
	         } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	         } catch (InstantiationException e) {
	            e.printStackTrace();
	         } catch (IllegalAccessException e) {
	            e.printStackTrace();
	         } catch (IllegalArgumentException e) {
	            e.printStackTrace();
	         } 
	         
	         System.out.println();
	      }//while
	}
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
			execute(request, response); // get방식으로 요청하면 execute 보내버려 
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
			execute(request, response); // post방식으로 요청해도 execute 보내버려 ★한글 처리 신경써야됨★
		
	}
	
	protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// 한글처리
			if(request.getMethod().equals("POST")){ // form태그에 method를 가져왔는데 post랑 같으면~
			request.setCharacterEncoding("UTF-8");
			}//if
			
			//요청이 들어왔을 때 => http://localhost:8080/memberMVC/member/writeForm.do
			String category = request.getServletPath(); // 딱 프로젝트명 뒤에만 얻어온다.
			System.out.println("category = " + category); // 결과가 /member/writeForm.do 나온다.
			
			CommandProcess com = (CommandProcess)map.get(category); //member.service.WriteFormService 자바파일을 얻어옴
			String view = null;
			
			try {
				view = com.requestPro(request, response); // "/member/writeForm.jsp"
			} catch (Throwable e) {
				e.printStackTrace();
			}
			
			//forward
			RequestDispatcher dispatcher = request.getRequestDispatcher(view);//상대번지
			dispatcher.forward(request, response);//제어권 넘기기		
	}
}

추가

-----------------------loginForm.jsp-----------------------

```<form id="memberloginForm" method="post" 
	action="http://localhost:8080/memberMVC/member/login.do">```

-----------------------command.properties-----------------------

/member/writeForm.do=member.service.WriteFormService

/member/loginForm.do=member.service.LoginFormService
/member/login.do=member.service.LoginService
/member/logout.do=member.service.LogoutService

-----------------------loginOk.jsp-----------------------

<body>

<h3>${sessionScope.memName }님이 로그인 하셨습니다.</h3>

<input type="button" value="로그아웃" onclick="location.href='/memberMVC/member/logout.do'">

</body>

-----------------------logout.jsp-----------------------

<body>
<h3>로그아웃</h3>
</body>

-----------------------loginFail.jsp-----------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>아이디 또는 비밀번호가 일치하지 않습니다.</h3>
</body>
</html>

-----------------------LoginService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

import member.bean.MemberDTO;
import member.dao.MemberDAO;

public class LoginService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {
		// 데이터
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		
		// DB
		MemberDAO memberDAO = new MemberDAO();
		MemberDTO memberDTO = memberDAO.login(id, pwd);
		
		// 응답
		if(memberDTO == null) {
			return "/member/loginFail.jsp";
		}else {
			// 세션
			HttpSession session = request.getSession(); // 세션 생성
			session.setAttribute("memName", memberDTO.getName());
			session.setAttribute("memId", id);
			session.setAttribute("memEmail", memberDTO.getEmail1()+"@"+memberDTO.getEmail2()); // 세션 등록
			
			return "/member/loginOk.jsp";
		}
	}

}

-----------------------LogoutService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

import member.bean.MemberDTO;
import member.dao.MemberDAO;

public class LoginService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) {
		// 데이터
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		
		// DB
		MemberDAO memberDAO = new MemberDAO();
		MemberDTO memberDTO = memberDAO.login(id, pwd);
		
		// 응답
		if(memberDTO == null) {
			return "/member/loginFail.jsp";
		}else {
			// 세션
			HttpSession session = request.getSession(); // 세션 생성
			session.setAttribute("memName", memberDTO.getName());
			session.setAttribute("memId", id);
			session.setAttribute("memEmail", memberDTO.getEmail1()+"@"+memberDTO.getEmail2()); // 세션 등록
			
			return "/member/loginOk.jsp";
		}
	}

}
-----------------------LoginFormService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

public class LoginFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/loginForm.jsp";
   }
}

-----------------------WriteFormService.java-----------------------

package member.service;

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

import com.control.CommandProcess;

public class WriteFormService implements CommandProcess{

   @Override
   public String requestPro(HttpServletRequest request, HttpServletResponse response) {
      return "/member/writeForm.jsp";
   }
}

-----------------------commandProcess.java-----------------------

package com.control;

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

public interface CommandProcess { //abstract 생략가능
   
   public abstract String requestPro(HttpServletRequest request, HttpServletResponse response);//추상메소드
   
}

-----------------------MemberDAO.java-----------------------

package member.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import member.bean.MemberDTO;

public class MemberDAO {

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private DataSource ds;
	
	public MemberDAO() {
		try {
			Context context = new InitialContext();
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle"); 
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isExistId(String id){
		boolean exist = false;
		String sql = "select * from member where id = ?";
		
		try {
			conn = ds.getConnection(); //DataSource로 부터 Connection을 가져온다. try catch 안으로 
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) exist = true;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return exist;
	}
	
	public void write(MemberDTO memberDTO) {
		String sql = "insert into member values(?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
		
		
		try {
			conn = ds.getConnection();
			
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, memberDTO.getName());
			pstmt.setString(2, memberDTO.getId());
			pstmt.setString(3, memberDTO.getPwd());
			pstmt.setString(4, memberDTO.getGender());
			pstmt.setString(5, memberDTO.getEmail1());
			pstmt.setString(6, memberDTO.getEmail2());
			pstmt.setString(7, memberDTO.getTel1());
			pstmt.setString(8, memberDTO.getTel2());
			pstmt.setString(9, memberDTO.getTel3());
			pstmt.setString(10, memberDTO.getZipcode());
			pstmt.setString(11, memberDTO.getAddr1());
			pstmt.setString(12, memberDTO.getAddr2());
			
			pstmt.executeUpdate();//실행			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public MemberDTO login(String id, String pwd){
		MemberDTO memberDTO = null;
		String sql = "SELECT * FROM MEMBER WHERE ID=? AND PWD=?";
		
		try {
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				memberDTO = new MemberDTO();
				memberDTO.setName(rs.getString("name"));
				memberDTO.setId(rs.getString("id"));
				memberDTO.setPwd(rs.getString("pwd"));
				memberDTO.setGender(rs.getString("gender"));
				memberDTO.setEmail1(rs.getString("email1"));
				memberDTO.setEmail2(rs.getString("email2"));
				memberDTO.setTel1(rs.getString("tel1"));
				memberDTO.setTel2(rs.getString("tel2"));
				memberDTO.setTel3(rs.getString("tel3"));
				memberDTO.setZipcode(rs.getString("zipcode"));
				memberDTO.setAddr1(rs.getString("addr1"));
				memberDTO.setAddr2(rs.getString("addr2"));
			}//if
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
		
		return memberDTO;
	}
}

-----------------------MemberDTO.java-----------------------

package member.bean;

import java.util.Date;

import lombok.Data;

@Data
public class MemberDTO {
	private String name;
	private String id;
	private String pwd;
	private String gender;
	private String email1;
	private String email2;
	private String tel1;
	private String tel2;
	private String tel3;
	private String zipcode;
	private String addr1;
	private String addr2;
	private	Date logtime;
}

-----------------------context.xml-----------------------

<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="memberMVC" 
		 path="/memberMVC" 
		 reloadable="true" 
		 source="org.eclipse.jst.jee.server:memberMVC">
		 
<Resource name="jdbc/oracle"
		 type="javax.sql.DataSource"
		 driverClassName="oracle.jdbc.driver.OracleDriver" 
		 url="jdbc:oracle:thin:@localhost:1521:xe"
		 username="c##java"
		 password="1234"
		 maxActive="20"
		 maxIdle="3"
		 removeAbandoned="true" />
</Context>

-----------------------context.xml-----------------------

0개의 댓글