Main funtions 

1. Connection Pool

2.  Action tags : <jsp:useBean...> / <jsp:setProperty...>

3. DTO, DAO class 

4. Session

 

Log in to Oracle, and create a new account(totoro) for a new project. 

create user totoro identified by totoro123;
grant connect, resource to totoro;

Create a new table with the new account.

create table member(
			id varchar2(20) primary key,
			passwd varchar2(20) not null,
			name varchar2(20) not null,
			jumin1 varchar2(6) not null,
			jumin2 varchar2(7) not null,
			mailid varchar2(30), 
			domain varchar2(30), 
			tel1 varchar2(5),
			tel2 varchar2(5),
			tel3 varchar2(5),
			phone1 varchar2(5),
			phone2 varchar2(5),
			phone3 varchar2(5),
			post varchar2(10),
			address varchar2(200),
			gender varchar2(20),
			hobby varchar2(50),
			intro varchar2(2000),
			register timestamp );

DTO Class

// DTO(Data Transfer Object)

package member;

import java.sql.Timestamp;

public class MemberDTO {
	private String id;
	private String passwd;
	private String name;
	private String jumin1;
	private String jumin2;
	private String mailid;
	private String domain;
	private String tel1;
	private String tel2;
	private String tel3;
	private String phone1;
	private String phone2;
	private String phone3;
	private String post;
	private String address;
	private String gender;
	private String hobby;
	private String intro;
	private Timestamp register;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJumin1() {
		return jumin1;
	}
	public void setJumin1(String jumin1) {
		this.jumin1 = jumin1;
	}
	public String getJumin2() {
		return jumin2;
	}
	public void setJumin2(String jumin2) {
		this.jumin2 = jumin2;
	}
	public String getMailid() {
		return mailid;
	}
	public void setMailid(String mailid) {
		this.mailid = mailid;
	}
	public String getDomain() {
		return domain;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}
	public String getTel1() {
		return tel1;
	}
	public void setTel1(String tel1) {
		this.tel1 = tel1;
	}
	public String getTel2() {
		return tel2;
	}
	public void setTel2(String tel2) {
		this.tel2 = tel2;
	}
	public String getTel3() {
		return tel3;
	}
	public void setTel3(String tel3) {
		this.tel3 = tel3;
	}
	public String getPhone1() {
		return phone1;
	}
	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}
	public String getPhone2() {
		return phone2;
	}
	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}
	public String getPhone3() {
		return phone3;
	}
	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}
	public String getPost() {
		return post;
	}
	public void setPost(String post) {
		this.post = post;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getIntro() {
		return intro;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}
}

memberform.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"> 
<title>회원 가입 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
//				document.getElementById('join_zip1').value = data.postcode1;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>

</head>
<body>

<form method="post" action="member.jsp"> 
<table border=1 width=450 align="center">
	<caption>회원 가입 폼</caption>
	<tr><td>ID</td>
		<td><input type=text autofocus="autofocus" id="id" name="id">
			<input type=button value="ID중복검사" id="idcheck">
			<div id="myid"></div>
		</td>
	</tr>
	<tr><td>비밀번호</td>
		<td><input type=password id="passwd" name="passwd">
		</td>
	</tr>
	<tr><td>성명</td>
		<td><input type=text id="name" name="name"></td>
	</tr>
	<tr><td>주민번호</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid">@
			<input type=text size=10 id="domain" name="domain">
			<select id="email">
				<option value="">직접입력</option>
				<option value="naver.com">네이버</option>
				<option value="daum.net">다음</option>
				<option value="nate.com">네이트</option>
				<option value="gmail.com">gmail</option>
			</select>	
		</td>
	</tr>
	<tr><td>전화번호</td>
		<td><input type=text size=4 maxlength=4 id="tel1" name="tel1">-
		    <input type=text size=4 maxlength=4 id="tel2" name="tel2">-
		    <input type=text size=4 maxlength=4 id="tel3" name="tel3">-
		</td>
	</tr>
	<tr><td>핸드폰</td>
		<td><select id="phone1" name="phone1">
				<option value="">번호선택</option>
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="018">018</option>
				<option value="019">019</option>
			</select>-
			<input type=text size=4 maxlength=4 id="phone2" name="phone2">-
		    <input type=text size=4 maxlength=4 id="phone3" name="phone3">		
		</td>	
	</tr>
	<tr><td>우편번호</td>
		<td><input type=text size=5 maxlength=5 id="post" name="post">
			<input type=button value="우편검색" onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>주소</td>
		<td><input type=text size=45 id="address" name="address"></td>
	</tr>
	<tr><td>성별</td>
		<td><input type=radio id="male" name="gender" value="남자">남자
			<input type=radio id="female" name="gender" value="여자">여자
		</td>
	</tr>
	<tr><td>취미</td>
		<td><input type=checkbox id="h1" name="hobby" value="공부">공부
			<input type=checkbox id="h2" name="hobby" value="게임">게임
			<input type=checkbox id="h3" name="hobby" value="등산">등산
			<input type=checkbox id="h4" name="hobby" value="낚시">낚시
			<input type=checkbox id="h5" name="hobby" value="쇼핑">쇼핑
		</td>
	</tr>
	<tr><td>자기소개</td>
		<td><textarea rows=5 cols=50 id="intro" name="intro"
		     placeholder="자기소개를 100자 이내로 입력하세요"></textarea>		
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="회원가입">
			<input type=reset value="취소">
		</td>
	</tr>		
</table>
</form>

</body>
</html>

member.js (Validation Check 유효성검사)

$(document).ready(function(){
		
		// ID중복검사 (popup 창으로 처리)
//		$("#idcheck").click(function(){
//			if($("#id").val()==""){
//				alert("ID를 입력하세요.");
//				$("#id").focus();
//				return false;
//			}else{
//				// open("팝업창에 실행될 문서명","윈도우이름","옵션")
//				var ref="idcheck.jsp?id="+$("#id").val();
//				window.open(ref,"mywin","width=250,height=150");
//			}			
//		});

		// ajax로  ID중복 검사
		$("#idcheck").click(function(){
			if($("#id").val() == ""){
				alert("ID를 입력 하세요.");
				$("#id").focus();
				return false;
			}else{
				
				var id = $("#id").val();	   // 사용자가 입력한 ID
				
				$.ajax({
					type : "post",   	       // get, post, put, delete
					url : "idcheck1.jsp",
					data : {"id" : id},	      // json
					success : function(data){ // callback함수로 결과를 돌려 받는다.
						alert(data);
						if(data == 1){        // 중복 ID
							$("#myid").html("<font color=red>중복 ID입니다.</font>");
							$("#id").val("").focus();
						}else{				  // 사용 가능한  ID
							$("#myid").html("<font color=red>사용 가능한 ID입니다.</font>");
							$("#passwd").focus();
						}
					}
				}); // $.ajax() end
				
			} // else end			
			
		}); // click end
		
		// 주민번호  뒷자리로 포커스 이동
		$("#jumin1").keyup(function(){
			
			if($("#jumin1").val().length == 6)
				$("#jumin2").focus();
		});
		
		// 도메인 선택
		$("#email").change(function(){
			if($("#email").val()==""){		// 직접 입력 선택
				$("#domain").attr("readOnly", false);
				$("#domain").val("").focus();
			}else{							// 도메인을 선택
				$("#domain").val($("#email").val());
				$("#domain").attr("readOnly","readOnly");				
			}
		});
		
		// 유효성 검사
		$("form").submit(function(){
			
			if($("#id").val() == ""){
				alert("ID를 입력하세요.");
				$("#id").focus();
				return false;
			}
			if($("#passwd").val()==""){
				alert("비밀번호를 입력하세요.");
				$("#passwd").focus();
				return false;
			}
			if($("#name").val()==""){
				alert("이름을 입력하세요.");
				$("#name").focus();
				return false;
			}
			if($("#jumin1").val()==""){
				alert("주민번호 앞자리를 입력하세요.");
				$("#jumin1").focus();
				return false;
			}
			if($("#jumin1").val().length != 6){
				alert("주민번호 앞자리 6자리를 입력하세요.");
				$("#jumin1").val("").focus();
				return false;
			}
			// isNaN() : 문자가 포함되면 true를 리턴하는 함수
			if(isNaN($("#jumin1").val())){
				alert("숫자만 입력하세요.");
				$("#jumin1").val("").focus();
				return false;
		    }
			if($("#jumin2").val()==""){
				alert("주민번호 뒷자리를 입력하세요.");
				$("#jumin2").focus();
				return false;
			}
			if($("#jumin2").val().length != 7){
				alert("주민번호 뒷자리 7자리를 입력하세요.");
				$("#jumin2").val("").focus();
				return false;
			}
			// isNaN() : 문자가 포함되면 true를 리턴하는 함수
			if(isNaN($("#jumin2").val())){
				alert("숫자만 입력하세요.");
				$("#jumin2").val("").focus();
				return false;
		    }
			if($("#mailid").val()==""){
				alert("EMail주소를 입력하세요.");
				$("#mailid").focus();
				return false;
			}
			if($("#domain").val()==""){
				alert("도메인을 입력하세요.");
				$("#domain").focus();
				return false;
			}
			if($("#tel1").val()==""){
				alert("전화번호 앞자리를 입력하세요.");
				$("#tel1").focus();
				return false;
			}
			if(isNaN($("#tel1").val())){
				alert("숫자만 입력하세요.");
				$("#tel1").val("").focus();
				return false;
			}
			if($("#tel2").val()==""){
				alert("전화번호 중간자리를 입력하세요.");
				$("#tel2").focus();
				return false;
			}
			if(isNaN($("#tel2").val())){
				alert("숫자만 입력하세요.");
				$("#tel2").val("").focus();
				return false;
			}
			if($("#tel3").val()==""){
				alert("전화번호 끝자리를 입력하세요.");
				$("#tel3").focus();
				return false;
			}
			if(isNaN($("#tel3").val())){
				alert("숫자만 입력하세요.");
				$("#tel3").val("").focus();
				return false;
			}
			if($("#phone1").val()==""){
				alert("핸드폰 앞자리를 선택 하세요.");
				return false;
			}
			if($("#phone2").val()==""){
				alert("핸드폰 중간자리를 입력하세요.");
				$("#phone2").focus();
				return false;
			}
			if(isNaN($("#phone2").val())){
				alert("숫자만 입력하세요.");
				$("#phone2").val("").focus();
				return false;
			}
			if($("#phone3").val()==""){
				alert("핸드폰 끝자리를 입력하세요.");
				$("#phone3").focus();
				return false;
			}
			if(isNaN($("#phone3").val())){
				alert("숫자만 입력하세요.");
				$("#phone3").val("").focus();
				return false;
			}
			if($("#post").val()==""){
				alert("우편번호를 입력하세요.");
				$("#post").focus();
				return false;
			}
			if($("#address").val()==""){
				alert("주소를 입력하세요.");
				$("#address").focus();
				return false;
			}
			if($("#male").is(":checked")==false &&
			   $("#female").is(":checked")==false){
				alert("남.여 중에서 1개를 선택 하세요");
				return false;
			}
			
			/* var cnt=0;
			if($("#h1").is(":checked")) cnt++;
			if($("#h2").is(":checked")) cnt++;
			if($("#h3").is(":checked")) cnt++;
			if($("#h4").is(":checked")) cnt++;
			if($("#h5").is(":checked")) cnt++;
			
			if(cnt < 2){
				alert("취미를 2개 이상 선택 하세요.");
				return false;
			} */
			
		if($("input:checkbox[name='hobby']:checked").length < 2){
			alert("취미를 2개 이상 선택 하세요.");
			return false;
		}
			
		if($("#intro").val()==""){
			alert("자기소개를 입력하세요.");
			$("#intro").focus();
			return false;
		}		
		if($("#intro").val().length > 100){
			alert("자기소개를 100자 이내로 입력하세요.");
			$("#intro").focus();
			return false;
		}	
			
	});	// submit() end	
		
}); // ready() end

member.jsp 

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

<%
	request.setCharacterEncoding("utf-8");
%>    
  
<jsp:useBean id="member" class="member.MemberDTO" />   
<jsp:setProperty property="*" name="member"/> 

<%
	String[] hobby = request.getParameterValues("hobby");
	String h = "";        // h = "공부-게임-등산-"
	for(String h1 : hobby){
		h += h1 + "-";		
	}
	
	member.setHobby(h);
	
	// DAO 객체 생성
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.insert(member); //insert SQL문을 실행할 메소드 호출
	
	if(result == 1){      // 회원가입 성공	
%>
		<script>
			alert("회원가입 성공");
			location.href="login.html";
		</script>

<%  }else{   //회원가입 실패        %>
		<script>
			alert("회원가입 실패");
			history.go(-1);
		</script>
<%	}%>

idcheck.jsp

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

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
	$(document).ready(function(){
		$("#close1").click(function(){ // 중복 ID인 경우의 닫기 버튼 클릭
			opener.$("#id").val("").focus();
			window.close();
		});
		
	$("#close2").click(function(){	// 사용 가능한 ID 인 경우의 닫기 버튼 클릭 
		opener.$("#passwd").focus();
		window.close();
		});
	});
</script>

<%
	String id = request.getParameter("id");

MemberDAO dao = MemberDAO.getInstance();

// id 중복검사 메소드 호출
int result = dao.memberAuth(id);

if (result == 1) { // 중복 ID : 1
%>
<%=id%>는 중복 ID 입니다.
<br>
<br>
<br>
<input type="button" value="Close" id="close1">
<%
	} else { // 사용 가능한 ID : -1
%>
<%=id%>는 사용가능한 ID 입니다.
<br>
<br>
<br>
<input type="button" value="Close" id="close2">
<%
	}
%>

idcheck1.jsp

<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<% 
	String id = request.getParameter("id");
	System.out.println("id="+id);  // Console 창에 출력 
	
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.memberAuth(id);
	System.out.println("result="+result);
	//result : 1(중복 ID)
	//result : -1(사용가능한 ID)
	
	// 웹브라우저에 출력되는 값이 callback함수로 리턴된다. 
	out.println(result);
%>

login.jsp

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

<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%
	MemberDAO dao = MemberDAO.getInstance();
	int result = dao.memberCheck(member); // 회원인증 처리 
	
if (result == 1) { // 로그인 성공
	session.setAttribute("id", member.getId());
%>
		<script>
			alert("로그인 성공");
			location.href = "main.jsp";
		</script>
<%
	} else {
%>
		<script>
			alert("로그인 실패");
			hisroty.go(-1);
		</script>
<%
	}
%>

main.jsp(세션값이 있냐 없냐에 따라서 값이 달라짐)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	String id = (String) session.getAttribute("id");

if (id != null) { //세션이 있는 경우(정상적으로 로그인)
%>
<%=id %>님 환영합니다. <br><br><br>

<a href="updateform.jsp">정보수정</a><br>
<a href="logout.jsp">로그아웃 </a><br>
<a href="deleteform.jsp">회원탈퇴</a><br>
<!-- <a href="list.jsp">글목록</a><br> -->

<%
	} else {  // 세션이 없는 경우(비정상적인 접속))
%>
<a href="memberform.html">회원가입</a><br>
<a href="loginform.html">로그인</a><br>
<%
	}
%>

세션이 없을 때 When there is no session:

세션이 있을 때 Where there is session: 

logout.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%	//세션 삭제: 서버와 클라이언트의 연결이 끊어짐
 session.invalidate();
%>

<script>
	alert("Log out");
	location.href="loginform.html";
</script>

updateform.jsp (memberform.html과 양식은 동일하지만 가입 시 등록한 정보가 입력되어있음)

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String id = (String) session.getAttribute("id");

MemberDAO dao = MemberDAO.getInstance();

// 한 사람의 상세정보 구해오기 
MemberDTO member = dao.getMember(id);

// h[0] = "공부", h[1] ="게임",...
String[] h = member.getHobby().split("-");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 수정 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
				// 우편번호와 주소 정보를 해당 필드에 넣고, 커서를 상세주소 필드로 이동한다.
				//				document.getElementById('join_zip1').value = data.postcode1;
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;

			}
		}).open();
	}
</script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>
<script>
$(document).ready(function(){	
	<%for (String s : h) {%>  // value 값이 s인 값을 구해와라 
$("input:checkbox[name='hobby'][value='<%=s%>']").attr("checked", true);
	<%}%>
});
</script>

</head>
<body>

	<form method="post" action="update.jsp">
	<input type="hidden" name="id" value="<%=member.getId() %>">
		<table border=1 width=450 align="center">
			<caption>회원 수정 폼</caption>
			<tr>
				<td>ID</td>
				<td><%=member.getId()%></td>
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type=password id="passwd" name="passwd"></td>
			</tr>
			<tr>
				<td>성명</td>
				<td><input type=text id="name" name="name"
					value="<%=member.getName()%>"></td>
			</tr>
			<tr>
				<td>주민번호</td>
				<td><input type=text size=6 maxlength=6 id="jumin1"
					name="jumin1" value="<%=member.getJumin1()%>">- <input
					type=text size=7 maxlength=7 id="jumin2" name="jumin2"
					value="<%=member.getJumin2()%>"></td>
			</tr>
			<tr>
				<td>E-Mail</td>
				<td><input type=text size=10 id="mailid" name="mailid"
					value="<%=member.getMailid()%>">@ <input type=text size=10
					id="domain" name="domain" value="<%=member.getDomain()%>">
					<select id="email">
						<option value="">직접입력</option>
						<option value="naver.com">네이버</option>
						<option value="daum.net">다음</option>
						<option value="nate.com">네이트</option>
						<option value="gmail.com">gmail</option>
				</select></td>
			</tr>
			<tr>
				<td>전화번호</td>
				<td><input type=text size=4 maxlength=4 id="tel1" name="tel1"
					value="<%=member.getTel1()%>">- <input type=text size=4
					maxlength=4 id="tel2" name="tel2" value="<%=member.getTel2()%>">-
					<input type=text size=4 maxlength=4 id="tel3" name="tel3"
					value="<%=member.getTel3()%>"></td>
			</tr>
			<tr>
				<td>핸드폰</td>
				<td><select id="phone1" name="phone1">
						<option value="">번호선택</option>
						<option value="010" <%if (member.getPhone1().equals("010")) {%>
							<%="selected"%> <%}%>>010</option>
						<option value="011" <%if (member.getPhone1().equals("011")) {%>
							<%="selected"%> <%}%>>011</option>
						<option value="016" <%if (member.getPhone1().equals("016")) {%>
							<%="selected"%> <%}%>>016</option>
						<option value="018" <%if (member.getPhone1().equals("018")) {%>
							<%="selected"%> <%}%>>018</option>
						<option value="019" <%if (member.getPhone1().equals("019")) {%>
							<%="selected"%> <%}%>>019</option>
				</select>- <input type=text size=4 maxlength=4 id="phone2" name="phone2"
					value="<%=member.getPhone2()%>">- <input type=text size=4
					maxlength=4 id="phone3" name="phone3"
					value="<%=member.getPhone3()%>"></td>
			</tr>
			<tr>
				<td>우편번호</td>
				<td><input type=text size=5 maxlength=5 id="post" name="post"
					value="<%=member.getPost()%>"> <input type=button
					value="우편검색" onClick="openDaumPostcode()"></td>
			</tr>
			<tr>
				<td>주소</td>
				<td><input type=text size=45 id="address" name="address"
					value="<%=member.getAddress()%>"></td>
			</tr>
			<tr>
				<td>성별</td>
				<td><input type=radio id="male" name="gender" value="남자"
					<%if (member.getGender().equals("남자")) {%> <%="checked"%> <%}%>>남자
					<input type=radio id="female" name="gender" value="여자"
					<%if (member.getGender().equals("여자")) {%> <%="checked"%> <%}%>>여자</td>
			</tr>
			<tr>
				<td>취미</td>
				<td><input type=checkbox id="h1" name="hobby" value="공부">공부
					<input type=checkbox id="h2" name="hobby" value="게임">게임 <input
					type=checkbox id="h3" name="hobby" value="등산">등산 <input
					type=checkbox id="h4" name="hobby" value="낚시">낚시 <input
					type=checkbox id="h5" name="hobby" value="쇼핑">쇼핑</td>
			</tr>
			<tr>
				<td>자기소개</td>
				<td><textarea rows=5 cols=50 id="intro" name="intro"
						placeholder="자기소개를 100자 이내로 입력하세요"><%=member.getIntro()%>"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan=2 align=center><input type=submit value="회원수정">
					<input type=reset value="취소"></td>
			</tr>
		</table>
	</form>

</body>
</html>

update.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%
	String[] hobby = request.getParameterValues("hobby");

// 취미를 하이픈(-)을 붙여서 저장: ex) 공부-게임-등산.. 
String h = "";
for (String h1 : hobby) {
	h += h1 + "=";
}
member.setHobby(h);

MemberDAO dao = MemberDAO.getInstance();

//한 사람의 상세 정보 구하기
MemberDTO old = dao.getMember(member.getId());

// 비번 비교
if (old.getPasswd().equals(member.getPasswd())){ // 비번 일치시
int result = dao.update(member);

if(result == 1){
%>
	<script>
		alert("회원정보 수정 성공");
		location.href="main.jsp";
	</script>
<% }
	} else {// 비번 불일치시
%>
<script>
	alert("비밀번호 불일치");
	history.go(-1);
</script>

<%
	}
%>

deleteform.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
	String id = (String) session.getAttribute("id");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 삭제 폼</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<!-- 외부 자바스크립트 파일 불러오기 -->
<script src="member.js"></script>

</head>
<body>

	<form method="post" action="delete.jsp">
		<input type="hidden" name="id" value="<%=id%>">
		<table border=1 width=450 align="center">
			<caption>회원 삭제 폼</caption>
			<td>비밀번호</td>
			<td><input type=password id="passwd" name="passwd"></td>
			</tr>

			<tr>
				<td colspan=2 align=center><input type=submit value="회원삭제">
					<input type=reset value="취소"></td>
			</tr>
		</table>
	</form>

</body>
</html>

delete.jsp

<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="member" class="member.MemberDTO" />
<jsp:setProperty property="*" name="member" />

<%

MemberDAO dao = MemberDAO.getInstance();

//한 사람의 상세 정보 구하기
MemberDTO old = dao.getMember(member.getId());

// 비번 비교
if (old.getPasswd().equals(member.getPasswd())){ // 비번 일치시
int result = dao.delete(member.getId());		// delete SQL문 싷ㄹ행

if(result == 1){
	session.invalidate(); 	// 세션 삭제 
%>
	<script>
		alert("회원 탈퇴 성공");
		location.href="main.jsp";
	</script>
<% }
	} else {// 비번 불일치시
%>
<script>
	alert("비밀번호 불일치");
	history.go(-1);
</script>

<%
	}
%>

memberDAO.java

// DAO(Data Access Object)

package member;

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

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

public class MemberDAO {

	// 싱글톤 : 객체 생성을 한번만 수행하는 것.
	private static MemberDAO instance = new MemberDAO();

	public static MemberDAO getInstance() { // 정적 메소드
		return instance;
	}

	// 컨넥션풀에서 컨넥션을 구해오는 메소드
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}

	// ID 중복 검사
	public int memberAuth(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);

			rs = pstmt.executeQuery(); // SQL문 실행

			if (rs.next()) { // 조건식을 만족하는 데이터를 구구해옴
				result = 1;
			} else {
				result = -1; // 사용 가능한 ID
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 회원 가입
	public int insert(MemberDTO member) {
		int result = 0;

		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection(); // 컨넥션풀에서 컨넥션을 구해온다.

			String sql = "insert into member ";
			sql += " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			pstmt.setString(2, member.getPasswd());
			pstmt.setString(3, member.getName());
			pstmt.setString(4, member.getJumin1());
			pstmt.setString(5, member.getJumin2());
			pstmt.setString(6, member.getMailid());
			pstmt.setString(7, member.getDomain());
			pstmt.setString(8, member.getTel1());
			pstmt.setString(9, member.getTel2());
			pstmt.setString(10, member.getTel3());
			pstmt.setString(11, member.getPhone1());
			pstmt.setString(12, member.getPhone2());
			pstmt.setString(13, member.getPhone3());
			pstmt.setString(14, member.getPost());
			pstmt.setString(15, member.getAddress());
			pstmt.setString(16, member.getGender());
			pstmt.setString(17, member.getHobby());
			pstmt.setString(18, member.getIntro());

			result = pstmt.executeUpdate(); // SQL문 실행

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 로그인(회원인증 처리)
	public int memberCheck(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			rs = pstmt.executeQuery(); // SQL문 실행

			if (rs.next()) { // ID 일치
				if (rs.getString("passwd").equals(member.getPasswd())) {
					result = 1; // ID, 비번 일치 (회원 인증 성공)
				} else {
					result = -1; // 비번 불일치
				}
			} else {
				result = -2; // ID 불일치
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		return result;
	}

	// 회원 수정폼 : 한 사람의 상세정보 구하기
	public MemberDTO getMember(String id) {
		MemberDTO member = new MemberDTO();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			String sql = "select * from member where id=?";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				// member.id = "test; 접근안됨 private 접근제어자
				member.setId(rs.getString("id"));
				member.setPasswd(rs.getString("passwd"));
				member.setName(rs.getString("name"));
				member.setJumin1(rs.getString("jumin1"));
				member.setJumin2(rs.getString("jumin2"));
				member.setMailid(rs.getString("mailid"));
				member.setDomain(rs.getString("domain"));
				member.setTel1(rs.getString("tel1"));
				member.setTel2(rs.getString("tel2"));
				member.setTel3(rs.getString("tel3"));
				member.setPhone1(rs.getString("phone1"));
				member.setPhone2(rs.getString("phone2"));
				member.setPhone3(rs.getString("phone3"));
				member.setPost(rs.getString("post"));
				member.setAddress(rs.getString("address"));
				member.setGender(rs.getString("gender"));
				member.setHobby(rs.getString("hobby"));
				member.setIntro(rs.getString("intro"));
				member.setRegister(rs.getTimestamp("register"));

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (Exception e) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}

		return member;
	}

	// 회원정보 수정
	public int update(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection();

			String sql = "update member set name=?, jumin1=?, jumin2=?, mailid=?,";
			sql += "domain=?, tel1=?, tel2=?, tel3=?, phone1=?, phone2=?, phone3=?,";
			sql += "post=?, address=?, gender=?, hobby=?, intro=? where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getName());
			pstmt.setString(2, member.getJumin1());
			pstmt.setString(3, member.getJumin2());
			pstmt.setString(4, member.getMailid());
			pstmt.setString(5, member.getDomain());
			pstmt.setString(6, member.getTel1());
			pstmt.setString(7, member.getTel2());
			pstmt.setString(8, member.getTel3());
			pstmt.setString(9, member.getPhone1());
			pstmt.setString(10, member.getPhone2());
			pstmt.setString(11, member.getPhone3());
			pstmt.setString(12, member.getPost());
			pstmt.setString(13, member.getAddress());
			pstmt.setString(14, member.getGender());
			pstmt.setString(15, member.getHobby());
			pstmt.setString(16, member.getIntro());
			pstmt.setString(17, member.getId());
			
			result = pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}

		return result;
	}

		// 회원 탈퇴
	public int delete(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="delete from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			result = pstmt.executeUpdate();
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.close();
				} catch (Exception e) {
				}
		}
		
		return result;
	}
}

What we will discuss today is this structure. It looks very complicated, but let's say it is more structured! Please look through and refer to this figure later.

There are three ways to connect to the database: JDBC(Java DataBase Connectivity), DBCP(DataBase Connection Pool), and ORM(Object Relat.ional Mapping) Frameworks like iBatis, MyBatis, , etce, JPA, etc. 

In Model2, we connected the database with the DBCP method, and in this post, we will be using the ORM Frameworks, specifically MyBatis.

 

We need to set up the plug-in in Eclipse.

Enter Eclipse Marketplace.

Search ORM and install MyBatipse.

Restart the Eclipse and create a new file

In this file, you can deal with all of the SQLs.  So, with the MyBatis, you can extract the SQL statements from the DAO Cthe lass to member.xml file. 

Now, we will import the MyBatis file. It is different from importing Dynamic Web Projects. 

You must select the Existing Projects into Workspace wizard to import the folder.

db.properties and mybatis-config.xml are connected, and you will decide the URL, username, password, etc.

In the mybatis-config.xml, there are three main tags to set : <typeAliases>, <properties>, and <mappers>.

 

<typeAliases> tag is for the alias of the project. It will be used as the parameterType in the mapper file. 

<properties> tag is to call the values to connect the database.

In the Mapper.xml, we use <resultMap> tag if the column and property names don't coch other. 

<mappers> tag is to call the mapper files. 

 

Before the exercise, refer to this figure to understand how to access a database with MyBatis.

Now, we will discuss connecting MyBatis and JSP Model 1. I will demonstrate basic login, sign up, delete and update forms with, MyBatis and I will show you partly to clarify the difference en with MyBatis and without it.

 

Import the folder first, and add dependencies. If you want to know how, please refer to my last post :

2022.09.23 - [Maven] - Maven) Configuration and Basics

 

DTO Class 

Since the column and property names are the same, we don't need to write the resultMap.

package model;

public class Member {
	private String id;
	private String password;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

 

member.xml(The DAO Class calls the id values in this mapper file.)

The mapper file starts with the <mapper> tag and closes with </mapper>.

The namespace is an area of logical names. It is used in C++ too. 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="memberns">

	<insert id="insert" parameterType="member">
		insert into member22 values (#{id}, #{password})
	</insert>
	
	<select id="list" resultType="member">
		select * from member22
	</select>
	
	<select id="select" parameterType="String" resultType="member">
		select * from member22 where id = #{id}
	</select>	
	
	<update id="update" parameterType="member">
		update member22 set password = #{password} where id = #{id}
	</update>
	
	<delete id="delete" parameterType="String">
		delete from member22 where id = #{id}
	</delete>
	
</mapper>

MemberDAO

As we extracted the SQLs in the mapper file, we don't need to includIfSQLs.

if you set the openSession value ,as "true" it will execute the commit automatically. Otherwise, you need to execute the commit whenever you need it, like this: session.commit();

We call mybatis-cofig.xml in the DAO Class, and the mybatis-cofig.xml calls the SQLSession and executes them.

insert(), update(), and delete() methods return the result with int datatypes.

Select is a bit different, selectOne() method returns the Object datatype as a result, and selectList() returns the List datatype.

Here is the complete code of the DAO Class.

package dao;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.Member;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MemberDao {
	
	private SqlSession getSession() {
		SqlSession session=null;
		Reader reader=null;
		try {
			reader = Resources.getResourceAsReader("mybatis-config.xml");
			SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(reader);
			session = sf.openSession(true);			// auto commit
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return session;
	}

	public int insert(Member member) {
		int result = 0;
		SqlSession session=null;
		try { 
			session = getSession(); 
			result = session.insert("insert", member);			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;
	}

	public int chk(Member member) {
		int result = 0;
		SqlSession session=null;
		try { session = getSession(); 
			Member mem = (Member) session.selectOne("select", member.getId());
			if (mem.getId().equals(member.getId())) {
				result = -1;
				if (mem.getPassword().equals(member.getPassword())) {
					result = 1;
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;
	}

	public Member select(String id) throws SQLException {
		Member mem = null;
		SqlSession session=null;
		try { session = getSession(); 
		mem = (Member) session.selectOne("select", id);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return mem;
	}

	public List<Member> list() {
		List<Member> list = new ArrayList<Member>();
		SqlSession session=null;
		try { session = getSession(); 
			list = session.selectList("list");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return list;
	}

	public int delete(String id) {
		int result = 0;
		SqlSession session=null;
		try { session = getSession(); 
			result = session.delete("delete", id);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;
	}

	public int update(Member mem) {
		int result = 0;
		SqlSession session=null;
		try { session = getSession(); 
			result = session.update("update", mem);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;
	}
}

mybatis-cofig.xml

Here, setting up the alias makes the project e,fficient and we set the alias as "member". 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="db.properties" />
	<typeAliases>
		<typeAlias type="model.Member" alias="member"></typeAlias>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="member.xml" />
	</mappers>
</configuration>

By using MyBatis, you will see that the codes are written in much more productive way.

The following is Model1 DAO Class without MyBatis. As you can see, the codes are way short but efficient.

// DAO(Data Access Object)

package member;

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

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

public class MemberDAO {

	// Singleton
	private static MemberDAO instance = new MemberDAO();
	
	public static MemberDAO getInstance() {		
		return instance;
	}
	
	private Connection getConnection() throws Exception{
		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		return ds.getConnection();
	}
	
	public int memberAuth(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();  
			
			String sql = "select * from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			
			rs = pstmt.executeQuery();	
			
			if(rs.next()) {		
				result = 1;     
			}else {
				result = -1;	
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(rs != null) try { rs.close();}catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return result;
	}	
	

	public int insert(MemberDTO member) {
		int result = 0;
		
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();	
			
String sql="insert into member ";
	   sql+=" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
	   
	   		pstmt = con.prepareStatement(sql);
	   		pstmt.setString(1, member.getId());
	   		pstmt.setString(2, member.getPasswd());
	   		pstmt.setString(3, member.getName());
	   		pstmt.setString(4, member.getJumin1());
	   		pstmt.setString(5, member.getJumin2());
	   		pstmt.setString(6, member.getMailid());
	   		pstmt.setString(7, member.getDomain());
	   		pstmt.setString(8, member.getTel1());
	   		pstmt.setString(9, member.getTel2());
	   		pstmt.setString(10, member.getTel3());
	   		pstmt.setString(11, member.getPhone1());
	   		pstmt.setString(12, member.getPhone2());
	   		pstmt.setString(13, member.getPhone3());
	   		pstmt.setString(14, member.getPost());
	   		pstmt.setString(15, member.getAddress());
	   		pstmt.setString(16, member.getGender());
	   		pstmt.setString(17, member.getHobby());
	   		pstmt.setString(18, member.getIntro());
	   		
	   		result = pstmt.executeUpdate();		
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return result;
	}
	
	// Log in
	public int memberCheck(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			rs = pstmt.executeQuery();		
			
			if(rs.next()) {		
				if(rs.getString("passwd").equals(member.getPasswd())) {
					result = 1;		
				}else {
					result = -1;   
				}
			}else {					
				result = -2;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(rs != null) try { rs.close();}catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return result;
	}
	
	public MemberDTO getMember(String id) {
		MemberDTO member = new MemberDTO();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();		
			
			if(rs.next()) {
				member.setId(rs.getString("id"));
				member.setPasswd(rs.getString("passwd"));
				member.setName(rs.getString("name"));
				member.setJumin1(rs.getString("jumin1"));
				member.setJumin2(rs.getString("jumin2"));
				member.setMailid(rs.getString("mailid"));
				member.setDomain(rs.getString("domain"));
				member.setTel1(rs.getString("tel1"));
				member.setTel2(rs.getString("tel2"));
				member.setTel3(rs.getString("tel3"));
				member.setPhone1(rs.getString("phone1"));
				member.setPhone2(rs.getString("phone2"));
				member.setPhone3(rs.getString("phone3"));
				member.setPost(rs.getString("post"));
				member.setAddress(rs.getString("address"));	
				member.setGender(rs.getString("gender"));
				member.setHobby(rs.getString("hobby"));
				member.setIntro(rs.getString("intro"));
				member.setRegister(rs.getTimestamp("register"));
			}			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(rs != null) try { rs.close();}catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return member;
	}
	
	public int update(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
String sql="update member set name=?,jumin1=?,jumin2=?,mailid=?,";
       sql+="domain=?,tel1=?,tel2=?,tel3=?,phone1=?,phone2=?,phone3=?,";
       sql+="post=?,address=?,gender=?,hobby=?,intro=? where id=?";
       
       		pstmt = con.prepareStatement(sql);
       		pstmt.setString(1, member.getName());
       		pstmt.setString(2, member.getJumin1());
       		pstmt.setString(3, member.getJumin2());
       		pstmt.setString(4, member.getMailid());
       		pstmt.setString(5, member.getDomain());
       		pstmt.setString(6, member.getTel1());
       		pstmt.setString(7, member.getTel2());
       		pstmt.setString(8, member.getTel3());
       		pstmt.setString(9, member.getPhone1());
       		pstmt.setString(10, member.getPhone2());
       		pstmt.setString(11, member.getPhone3());
       		pstmt.setString(12, member.getPost());
       		pstmt.setString(13, member.getAddress());
       		pstmt.setString(14, member.getGender());
       		pstmt.setString(15, member.getHobby());
       		pstmt.setString(16, member.getIntro());
       		pstmt.setString(17, member.getId());
       		
       		result = pstmt.executeUpdate();		
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return result;
	}
	

	public int delete(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="delete from member where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			result = pstmt.executeUpdate();		
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();}catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		return result;
	}
	
	
}

In the next post, we will discuss how it can be more economic by using MyBatis in Model2.  

Main functions

1. Connection Pool 

2. Reply function

3. File attachment and download function by using cos library

4. request object

5. Controller Class: Java Servlet

6. Model = Service + DAO (Service, DTO, DAO class) 

7. View(User Interface) : EL, JSLT 

 

Please refer to the figures for a better understanding of the structure of this project.

 

1. Create a Dynamic Web Project model2board.

2. Test the Connection Pool

3. Create a folder(boardupload) to save uploaded files.

4. Create a sql folder and create board.sql.

5. Create a table and a sequence.

--Model2 Bulletin Board

select * from tab;
select * from seq;
select * from model2;

create table model2(
			board_num number primary key,
			board_name varchar2(20),
			board_pass varchar2(15),
			board_subject varchar2(50),
			board_content varchar2(2000),
			board_file varchar2(50),
			board_re_ref number,
			board_re_lev number, 
			board_re_seq number, 
			board_readcount number,
			board_date timestamp );

create sequence model2_seq
			start with 1
			increment by 1
			nocache;

6. Create a BoardBean(DTO) Class in src-model.

// DTO(Data Transfer Object)

package model;

import java.sql.Timestamp;

public class BoardBean {
	private int board_num;
	private String board_name;
	private String board_pass;
	private String board_subject;
	private String board_content;
	private String board_file;
	private int board_re_ref;
	private int board_re_lev;
	private int board_re_seq;
	private int board_readcount;
	private Timestamp board_date;
	
	public int getBoard_num() {
		return board_num;
	}
	public String getBoard_name() {
		return board_name;
	}
	public String getBoard_pass() {
		return board_pass;
	}
	public String getBoard_subject() {
		return board_subject;
	}
	public String getBoard_content() {
		return board_content;
	}
	public String getBoard_file() {
		return board_file;
	}
	public int getBoard_re_ref() {
		return board_re_ref;
	}
	public int getBoard_re_lev() {
		return board_re_lev;
	}
	public int getBoard_re_seq() {
		return board_re_seq;
	}
	public int getBoard_readcount() {
		return board_readcount;
	}
	public Timestamp getBoard_date() {
		return board_date;
	}
	public void setBoard_num(int board_num) {
		this.board_num = board_num;
	}
	public void setBoard_name(String board_name) {
		this.board_name = board_name;
	}
	public void setBoard_pass(String board_pass) {
		this.board_pass = board_pass;
	}
	public void setBoard_subject(String board_subject) {
		this.board_subject = board_subject;
	}
	public void setBoard_content(String board_content) {
		this.board_content = board_content;
	}
	public void setBoard_file(String board_file) {
		this.board_file = board_file;
	}
	public void setBoard_re_ref(int board_re_ref) {
		this.board_re_ref = board_re_ref;
	}
	public void setBoard_re_lev(int board_re_lev) {
		this.board_re_lev = board_re_lev;
	}
	public void setBoard_re_seq(int board_re_seq) {
		this.board_re_seq = board_re_seq;
	}
	public void setBoard_readcount(int board_readcount) {
		this.board_readcount = board_readcount;
	}
	public void setBoard_date(Timestamp board_date) {
		this.board_date = board_date;
	}
	
}

7. Create a BoardDAO Class in src-dao and create a Singleton and Connection instance. 

//DAO(Data Access Object)

package dao;

import java.sql.Connection;

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

public class BoardDAO {
	
	// Singleton
	private static BoardDAO instance = new BoardDAO();
	
	public static BoardDAO getInstance() {		// Static method
		return instance;
	}
	
	// Connection from Connection Pool
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}
}

8. Create BoardFrontController class in src-controller. The controller class has to be made as a Java Servlet Class.

.do is the general extension of actions using Apache Struts.

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;

/**
 * Servlet implementation class BoardFrontController
 */
@WebServlet("*.do")	// Do extension 
public class BoardFrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		
		System.out.println("requestURI: "+requestURI);
		System.out.println("contextPath: "+contextPath);
		System.out.println("command: "+command);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("get");
		
		doProcess(request, response);	// To call doProcess method
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("post");
		
		doProcess(request, response);	// To call doProcess method
	}

}

9. Create an Action interface in src-service.

package service;

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

public interface Action {

	// Abstract method
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception; 
}

10. Create an ActionForward Class in src-service.

package service;

public class ActionForward {
	private boolean redirect;		// To set the forwarding method
	private String path; 			// To save the file name to forward
	
	public boolean isRedirect() {
		return redirect;
	}
	public String getPath() {
		return path;
	}
	public void setRedirect(boolean redirect) {
		this.redirect = redirect;
	}
	public void setPath(String path) {
		this.path = path;
	}
	
}

11. Add action and forward part in the controller class.

Action action = null;
		ActionForward forward = null;
		
		// Writng a content
		if(command.equals("/BoardAddAction.do")) {
			try {
				action = new BoardAddAction();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		// Forwarding process
		if(forward != null) {
			if(forward.isRedirect()) {	//true -> Redirect method
				response.sendRedirect(forward.getPath());
			}else {						//not true -> Dispatcher method 
				RequestDispatcher dispatcher = 
						request.getRequestDispatcher(forward.getPath());
						dispatcher.forward(request, response);
			}
		}
	}

12. Create a BoardAddAction Class in src-service. This class is for file upload/download.

 

13. Create a qna_board_write.jsp.

Here,  enctype="multipart/form-data" is essential for the file attachment function.

<%@ page language="java" contentType="text/html; charset=utf-8"%>

<html>
<head>
	<title>MVC Bulletin Board</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="<%=request.getContextPath() %>/board/script.js"></script>
	<style>
@import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap');
</style>
</head>
<body>

<form action="<%=request.getContextPath() %>/BoardAddAction.do" method="post" 
	  enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" align=center border=1>
	<tr align="center" valign="middle">
		<td style="font-family: 'Abril Fatface', cursive;" colspan="5">MVC Bulletin Board</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Writer</div>
		</td>
		<td>
			<input name="board_name" id="board_name" type="text" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Password</div>
		</td>
		<td>
			<input name="board_pass" id="board_pass" type="password" size="10" maxlength="10" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12" height="16">
			<div align="center">Title</div>
		</td>
		<td>
			<input name="board_subject" id="board_subject" type="text" size="50" maxlength="100" 
				value=""/>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12">
			<div align="center">Content</div>
		</td>
		<td>
			<textarea name="board_content" id="board_content" cols="67" rows="15"></textarea>
		</td>
	</tr>
	<tr>
		<td style="font-family: 'Abril Fatface', cursive; font-size:12">
			<div align="center">Attach File</div>
		</td>
		<td>
			<input name="board_file" type="file"/>
		</td>
	</tr>
	<tr bgcolor="cccccc">
		<td colspan="2" style="height:1px;">
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr align="center" valign="middle">
		<td colspan="5">			
			<input type=submit value="Post">
			<input type=reset value="Cancel">
		</td>
	</tr>
</table>
</form>

</body>
</html>

14. In the DAO class, add the insert method. 

// Insert method : Post
	public int insert(BoardBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;

		try {
			con = getConnection();

			String sql = "insert into model2 values(model2_seq.nextval,?,?,?,?,?,";
			sql += " model2_seq.nextval,?,?,?,sysdate)";

			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getBoard_name());
			pstmt.setString(2, board.getBoard_pass());
			pstmt.setString(3, board.getBoard_subject());
			pstmt.setString(4, board.getBoard_content());
			pstmt.setString(5, board.getBoard_file());
			pstmt.setInt(6, 0); // board_re_lev
			pstmt.setInt(7, 0); // board_re_seq
			pstmt.setInt(8, 0); // board_readcount
			result = pstmt.executeUpdate(); // To execute SQL

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}

		return result;
	}

When you upload the file, you will check the file by copying and pasting the path from the console.

15. Create BoardListAction.java in src-service.

package service;

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

import dao.BoardDAO;

public class BoardListAction implements Action{

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("BoardListAction");
		
		int page = 1;			// Current Page
		int limit = 10;			// How many pages will be printed? 10
		
		if(request.getParameter("page") != null) {
			 page = Integer.parseInt(request.getParameter("page"));
		}
		
		// ex) page = 1 : startRow = 1, endRow : 10
		int startRow = (page -1) * limit + 1;
		int endRow = page * limit;
		
		BoardDAO dao = BoardDAO.getInstance();
		int listcount = dao.getCount();	// Total data volume
		System.out.println("listcount: "+listcount);
		
			ActionForward forward = new ActionForward();
			forward.setRedirect(false);  // Dispatcher method 
			forward.setPath("./board/qna_board_list.jsp");
		
		return forward;
	}
	
}

16. In the Controller class, add the Post list part.

// Posts list
		}else if(command.equals("/BoardListAction.do")){
			try {
				action = new BoardListAction();
				forward = action.execute(request, response);
		}catch(Exception e){
			e.printStackTrace();
		}

17. In the DAO class, add the total data volume part.

	// Total data volum
	public int getCount() {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select count(*) from model2";
			
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
//				result = rs.getInt(1);
				result = rs.getInt("count(*)");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		return result;
	}

18. Add the get list method in BoardListAction.java and DAO class.

BoardListAction.java

//To get List 
		List<BoardBean> boardlist = dao.getList(startRow, endRow);
		System.out.println("boardlist: "+boardlist);
        
//Total pages number
		int pageCount = listcount / limit + (( listcount%limit == 0 )? 0 : 1); //if the result of listcount%limit is 0, increase 0, otherwise increase 1.
		
		int startPage = ((page-1)/ 10) * limit + 1; // 1, 11, 22...
		int endPage = startPage + 10 - 1; 	// 10, 20, 30...
		
		if(endPage > pageCount) endPage = pageCount;
		
		request.setAttribute("page", page);
		request.setAttribute("listcount", listcount);
		request.setAttribute("boardlist", boardlist);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("startPage", startPage);
		request.setAttribute("endPage", endPage);

BoardDAO.java

	// Posts List ( 10 data)
	public List<BoardBean> getList(int start, int end){
		List<BoardBean> list = new ArrayList<BoardBean>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
	String sql="select * from (select rownum rnum, board.* from ";
		   sql+=" (select * from model2 order by board_re_ref desc, ";
		   sql+=" board_re_seq asc) board ) ";
		   sql+=" where rnum >= ? and rnum <= ?";
		   
		   pstmt = con.prepareStatement(sql);
		   pstmt.setInt(1, start);
		   pstmt.setInt(2, end);
		   rs = pstmt.executeQuery();  	//SQL
		   
		   while(rs.next()) {
			   BoardBean board = new BoardBean();
			   board.setBoard_num(rs.getInt("board_num"));
			   board.setBoard_name(rs.getString("board_name"));
			   board.setBoard_pass(rs.getString("board_pass"));
			   board.setBoard_subject(rs.getString("board_subject"));
			   board.setBoard_content(rs.getString("board_content"));
			   board.setBoard_file(rs.getString("board_file"));
			   board.setBoard_re_ref(rs.getInt("board_re_ref"));
			   board.setBoard_re_lev(rs.getInt("board_re_lev"));
			   board.setBoard_re_seq(rs.getInt("board_re_seq"));
			   board.setBoard_readcount(rs.getInt("board_readcount"));
			   board.setBoard_date(rs.getTimestamp("board_date"));
			   
			   list.add(board);
		   }
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		
		return list;
	}

19. Create qna_board_list.jsp and print out the posts list.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<a href="./BoardForm.do">Write my post</a>
<br>
Posts : ${listcount}
<br>
<%
	int count = ((Integer) request.getAttribute("listcount")).intValue();
%>

Total posts :<%=count%>
<br>
<table border=1 width=700 align=center>
	<caption>Posts List</caption>
	<tr>
		<th>No.</th>
		<th>Title</th>
		<th>Writer</th>
		<th>Date</th>
		<th>View</th>
	</tr>
	<c:set var="num" value="${listcount - (page-1) * 10}" />
	<c:forEach var="b" items="${boardlist}">
		<tr>
			<td>${num}<c:set var="num" value="${num-1}" />
			</td>
			<td>
				<!-- Space before reply --> 
				<c:if test="${b.board_re_lev > 0}">
					<c:forEach var="i" begin="0" end="${b.board_re_lev}">
					&nbsp;
				</c:forEach>

				</c:if> 
				<a href="./BoardDetailAction.do?board_num=${b.board_num}&page=${page}">
				${b.board_subject}</a>
			</td>
			<td>${b.board_name}</td>
			<td><fmt:formatDate value="${b.board_date}"
					pattern="dd.MM.yyyy HH:mm:ss EEEE" /></td>
			<td>${b.board_readcount }</td>
		</tr>
	</c:forEach>
</table>

When you run the index.jsp, you will see the posts list.

We will keep putting more functions into this project in the following posts. 

Maven is an Apache Software Foundation build tool for project management that automates Java projects

There is Gradle, which is similar to Maven, but the uses are a little bit different. 

Maven is for spring projects, while Gradle is for android projects. However, both deal with the springboot projects.

 

Let us make our first Maven project together. It will be useful for your better understanding.

Creating a new maven project is very similar to other projects like dynamic web projects we have done so far. 

There is a small different part: you need to choose an Internal Catalog and the last Artifact Id. 

maven-archetype-webapp is for web development, so for our next project, we are choosing this. Depending on the artifact id, you will see the different structures.

Next, you must write the domain reversely, and the artifact id will be your project's name. 


If there is an error that you can see(the red X sign), you can erase that by adding
Apache Tomcat v9.0.

Then, it's solved! 

 

As you can see, the project's structure is different from the dynamic web project.

This maven project is similar to the spring projects we will discuss next time. Let's take a deep look at the maven project.

The Java Resources contain controller, service, DTO, and DAO classes. In the webapp folder in the Deployed Resources folder, there are view pages. 

pom.xml is the configuration file of Maven. 

In this file, we will save the dependencies. 

Let's add cos library in it.

1. Maven Repository: Search/Browse/Explore (mvnrepository.com) Click the link.

2. Search cos and click the second one. 

3.Click 05 Nov 2002.

4. Copy the maven dependency tags and paste into the pom.xml file. 

5. When you save the file, it will download the library to the local repository.

To check your local repository, click window-Preferences- Maven - User Settings.

Now, we will add the Oracle repository

As it is better for fewer issues, we will first add <repository> tag which is an unofficial code. If you encounter any issue with downloading Oracle, try to download this repository. 

<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>

And, we will add Oracle JDBC Library in the <dependencies> tag. 

<!-- Oracle JDBC Library -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

To add MySQL repository, follow this : 

1. Maven Repository: Search/Browse/Explore (mvnrepository.com) enter MVN repository

2. Download the MySQL Connector/J (J means Java).

3. Download the same version of what you have on your system.

Since I have the 8.0.28 version, I will download this. 

4. Copy and paste the tags in the pom.xml file. 

To add MyBatis or other repositories, you will do the same. 

This is how you manage libraries.

 

To export and import the maven projects is also different from how we did before. Exporting and importing it as a WAR file will be saved as a dynamic web project. To export the Maven project, you will copy the whole project and paste it to the place you want. This is different from exporting the dynamic web project, but it is easier because you don't need any skills to do this. To import, click Existing Projects into Workspace in the General menu.

 

Main Funtions

1. Connection Pool

2. request, session object

3. Controller Class : Java Servlet

4. Model = Service + DAO

    Service, DTO, DAO Class

5. View: EL, JSTL 

 

In Model2, we need to separate the files into each package by function.

Here is how I planned to structure the program based on the MVC Architecture.

Controller Class : controller - MemberController.java

DTO Class: model - MemberDTO.java

DAO Class : dao - MemberDAO.java

Action Interface: service - Action.java

ActionForward Class: service - ActionForward.java

Service Class: service - MemberInsert.java

                                      - IdCheck.java(Id Validation check)

                                      - Login.java

                                      - Logout.java

                                      - UpdateMember.java

                                      - Update.java

                                      - DeleteMember.java

                                      - Delete.java

 

As this is my first time creating a Model2 project, so, I will write how I did it in detail. 

1. Create a Dynamic Web Project named model2member.

2. In the WebContent folder, create index.jsp.

3. In the lib folder, save three libraries: cos.jar, jstl-1.2jar, and ojdbc.jar.

4. In the WebContent folder, create member folder.

5. In the META-INF, create context.html for configuration.

<Context> 
  <Resource name="jdbc/orcl" 
   auth="Container"
   type="javax.sql.DataSource" 
   username="totoro" 
   password="totoro123"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
   url="jdbc:oracle:thin:@localhost:1521:xe"
   maxActive="500"  
   maxIdle="100"/>  
</Context>

6. Test with dbcpAPITest.jsp in WebContent - member folder.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
 	Connection conn = null; 
	
	try {
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		conn = ds.getConnection();
  		
  		out.println("<h3>Connected.</h3>");
	}catch(Exception e){
		out.println("<h3>Failed to connect.</h3>");
		e.printStackTrace();
 	}
%>

7. Create member.sql in WebContent - member - sql - member.sql and connect totoro account. 

8. Create a table named member2, block + Alt + X to create.

-- Model2 Customer Management Program

select * from tab;
select * from member2;

create table member2(
		id varchar2(20) primary key,
		passwd varchar2(20) not null,
		name varchar2(20) not null,
		jumin1 varchar2(6) not null,
		jumin2 varchar2(7) not null,
		mailid varchar2(30), 
		domain varchar2(30), 
		tel1 varchar2(5),
		tel2 varchar2(5),
		tel3 varchar2(5),
		phone1 varchar2(5),
		phone2 varchar2(5),
		phone3 varchar2(5),
		post varchar2(10),
		address varchar2(200),
		gender varchar2(20),
		hobby varchar2(50),
		intro varchar2(2000),
		register timestamp );

9. In the src folder, create a package named model, inside, create DTO Class namedMemberDTO.java.

10. Refer to the member table on sql, create properties. 

11. Mouse right click - Source - Generate Getters and Setters to create the getters and setters.

// DTO(Data Transfer Object)

package model;

import java.sql.Timestamp;

public class MemberDTO {
	private String id;		// Properties
	private String passwd;
	private String name;
	private String jumin1;
	private String jumin2;
	private String mailid;
	private String domain;
	private String tel1;
	private String tel2;
	private String tel3;
	private String phone1;
	private String phone2;
	private String phone3; 
	private String post; 
	private String address; 
	private String gender; 
	private String hobby; 
	private String intro; 
	private Timestamp register;
	public String getId() {
		return id;
	}
	public String getPasswd() {
		return passwd;
	}
	public String getName() {
		return name;
	}
	public String getJumin1() {
		return jumin1;
	}
	public String getJumin2() {
		return jumin2;
	}
	public String getMailid() {
		return mailid;
	}
	public String getDomain() {
		return domain;
	}
	public String getTel1() {
		return tel1;
	}
	public String getTel2() {
		return tel2;
	}
	public String getTel3() {
		return tel3;
	}
	public String getPhone1() {
		return phone1;
	}
	public String getPhone2() {
		return phone2;
	}
	public String getPhone3() {
		return phone3;
	}
	public String getPost() {
		return post;
	}
	public String getAddress() {
		return address;
	}
	public String getGender() {
		return gender;
	}
	public String getHobby() {
		return hobby;
	}
	public String getIntro() {
		return intro;
	}
	public Timestamp getRegister() {
		return register;
	}
	public void setId(String id) {
		this.id = id;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setJumin1(String jumin1) {
		this.jumin1 = jumin1;
	}
	public void setJumin2(String jumin2) {
		this.jumin2 = jumin2;
	}
	public void setMailid(String mailid) {
		this.mailid = mailid;
	}
	public void setDomain(String domain) {
		this.domain = domain;
	}
	public void setTel1(String tel1) {
		this.tel1 = tel1;
	}
	public void setTel2(String tel2) {
		this.tel2 = tel2;
	}
	public void setTel3(String tel3) {
		this.tel3 = tel3;
	}
	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}
	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}
	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}
	public void setPost(String post) {
		this.post = post;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	public void setRegister(Timestamp register) {
		this.register = register;
	}

}

12. In the src folder,create package named dao, inside, create DAO ClassnamedMemberDAO.java.

// DAO(Data Access Object)
package dao;

import java.sql.Connection;

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

public class MemberDAO {
	// Singleton : a design pattern that ensures that a class can only have one
	// object.
	private static MemberDAO instance = new MemberDAO();

	public static MemberDAO getInstance() { // static method
		return instance;
	}

	// Connection Pool
	private Connection getConnection() throws Exception {
		Context init = new InitialContext();
		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
		return ds.getConnection();
	}
	
	
}

13. Create a Servlet named controller, class name MemberController.

Since we don't need constructors, tick out the Contructors from superclass box.

14. In MemberController, change the WebServlet annotation to this : 

@WebServlet("*.do")
package controller; // 중간에 흐름을 제어하는 역할 

import java.io.IOException;

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 service.Action;
import service.ActionForward;
import service.MemberInsert;

/**
 * Servlet implementation class MemberController
 */
@WebServlet("*.do")
public class MemberController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// For processing common works of doGet() and doPost()
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String command = requestURI.substring(contextPath.length());
		
		System.out.println("requestURI:" + requestURI);      // /model2member/Login.do
		System.out.println("contextPath:" + contextPath);	 // /model2member
		System.out.println("command:" + command); 			// /Login.do 
		
		Action action = null;
		ActionForward forward = null;
		
		// Sign up 
		if(command.equals("/MemberInsert.do")) {
			try {
				action = new MemberInsert();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
		
		// Forward process
		if(forward != null) {
			if(forward != null) {	// redirect method
				response.sendRedirect(forward.getPath());
			}else {					// dispatcher method
				RequestDispatcher dispatcher = 
					request.getRequestDispatcher(forward.getPath());
				dispatcher.forward(request, response);
			}
		}
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("get");
		
		doProcess(request, response);		// call doProcess() method
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("post");
		
		doProcess(request, response);
	}
	
	

}

15. Create Action.java interface and ActionForward.java class in service package - src folder.

16. Go to MemberController, and update the forward process.

17. Create memberform.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://dmaps.daum.net/map_js_init/postcode.v2.js"></script>
<script>
	function openDaumPostcode() {
		new daum.Postcode({
			oncomplete : function(data) {
				document.getElementById('post').value = data.zonecode;
				document.getElementById('address').value = data.address;
				
			}
		}).open();
	}
</script>

<script src="<%=request.getContextPath() %>/member/member.js"></script>

</head>
<body>

<form method="post" action="<%=request.getContextPath() %>/memberInsert.do"> 
<table border=1 width=450 align="center">
	<caption>Sign Up</caption>
	<tr><td>ID</td>
		<td><input type=text autofocus="autofocus" id="id" name="id">
			<input type=button value="IDcheck" id="idcheck">
		</td>
	</tr>
	<tr><td>Password</td>
		<td><input type=password id="passwd" name="passwd">
		</td>
	</tr>
	<tr><td>Name</td>
		<td><input type=text id="name" name="name"></td>
	</tr>
	<tr><td>Resident Registration Number</td>
		<td><input type=text size=6 maxlength=6 id="jumin1" name="jumin1">-
			<input type=text size=7 maxlength=7 id="jumin2" name="jumin2">
		</td>
	</tr>
	<tr><td>E-Mail</td>
		<td><input type=text size=10 id="mailid" name="mailid">@
			<input type=text size=10 id="domain" name="domain">
			<select id="email">
				<option value="">Other</option>
				<option value="gmail.com">gmail</option>
				<option value="naver.com">Naver</option>
			</select>	
		</td>
	</tr>
	<tr><td>Office/Home Phone</td>
		<td><input type=text size=4 maxlength=4 id="tel1" name="tel1">-
		    <input type=text size=4 maxlength=4 id="tel2" name="tel2">-
		    <input type=text size=4 maxlength=4 id="tel3" name="tel3">-
		</td>
	</tr>
	<tr><td>Mobile</td>
		<td><select id="phone1" name="phone1">
				<option value="">Select Number</option>
				<option value="010">010</option>
				<option value="011">011</option>
				<option value="016">016</option>
				<option value="018">018</option>
				<option value="019">019</option>
			</select>-
			<input type=text size=4 maxlength=4 id="phone2" name="phone2">-
		    <input type=text size=4 maxlength=4 id="phone3" name="phone3">		
		</td>	
	</tr>
	<tr><td>Post Code</td>
		<td><input type=text size=5 maxlength=5 id="post" name="post">
			<input type=button value="Search" onClick="openDaumPostcode()">
		</td>
	</tr>
	<tr><td>Address</td>
		<td><input type=text size=45 id="address" name="address"></td>
	</tr>
	<tr><td>Sex</td>
		<td><input type=radio id="male" name="gender" value="Male">Male
			<input type=radio id="female" name="gender" value="Female">Female
			<input type=radio id="Prefer not to say" name="gender" value="Prefer Not to say">Prefer Not to say
		</td>
	</tr>
	<tr><td>Hobby</td>
		<td><input type=checkbox id="h1" name="hobby" value="Studying">Studying
			<input type=checkbox id="h2" name="hobby" value="Programming">Programming
			<input type=checkbox id="h3" name="hobby" value="Hiking">Hiking
			<input type=checkbox id="h4" name="hobby" value="Reading">Reading
			<input type=checkbox id="h5" name="hobby" value="Cooking">Cooking
		</td>
	</tr>
	<tr><td>About Me</td>
		<td><textarea rows=5 cols=50 id="intro" name="intro"
		     placeholder="Please write about you in up to 100 words."></textarea>		
		</td>
	</tr>
	<tr><td colspan=2 align=center>
			<input type=submit value="Sign Up">
			<input type=reset value="Cancel">
		</td>
	</tr>		
</table>
</form>

</body>
</html>

 

18. Create member.js for validation check.

$(document).ready(function(){	
	
	// ID Check
	$("#idcheck").click(function(){
		if($("#id").val()==""){
			alert("Insert ID.");
			$("#id").focus();
			return false;
		}else{
			
			var id = $("#id").val();	
			
			$.ajax({
				type:"post",
				url:"/model2member/Idcheck.do",
				data:{"id":id},
				datatype:"text",
				success:function(data){
//					alert(data);
					
					if(data==1){	
						$("#myid").text("Unavailable ID");
						$("#id").val("").focus();
					}else{			
						$("#myid").text("Available ID");
						$("#passwd").focus();
					}					
				}
			});			
		}		
	});
	
	// Move mouse cursor
	$("#jumin1").keyup(function(){
		
		if($("#jumin1").val().length == 6)
			$("#jumin2").focus();
	});
	
	
	// Domain
	$("#email").change(function(){
		if($("#email").val() == ""){	
			$("#domain").removeAttr("readonly");
			$("#domain").val("").focus();			
		}else{							
			$("#domain").val($("#email").val());
		    $("#domain").attr("readonly","readonly");
		}
	});
	
	// Validation Check
	$("form").submit(function(){
		
		if($("#id").val() == ""){
			alert("Insert ID.");
			$("#id").focus();
			return false;
		}		
		if($("#passwd").val()==""){
			alert("Insert Password.");
			$("#passwd").focus();
			return false;
		}		
		if($("#name").val()==""){
			alert("Insert Name.");
			$("#name").focus();
			return false;
		}
		if($("#jumin1").val()==""){
			alert("Insert Resident Registration Number1");
			$("#jumin1").focus();
			return false;
		}
		if($("#jumin1").val().length != 6){
			alert("Resident Registration Number1 has to be 6 digits.");
			$("#jumin1").val("").focus();
			return false;
		}
		if(isNaN($("#jumin1").val())){
			alert("Resident Registration Number has to be numbers only.");
			$("#jumin1").val("").focus();
			return false;
		}
		if($("#jumin2").val()==""){
			alert("Insert Resident Registration Number2.");
			$("#jumin2").focus();
			return false;
		}
		if($("#jumin2").val().length != 7){
			alert("Resident Registration Number2 has to be 7 digits.");
			$("#jumin2").val("").focus();
			return false;
		}
		if(isNaN($("#jumin2").val())){
			alert("Resident Registration Number has to be numbers only.");
			$("#jumin2").val("").focus();
			return false;
		}
		if($("#mailid").val()==""){
			alert("Insert Mailid.");
			$("#mailid").focus();
			return false;
		}
		if($("#domain").val()==""){
			alert("Insert Domain.");
			$("#domain").focus();
			return false;
		}
		if($("#tel1").val()==""){
			alert("Insert Office/Home Phone1.");
			$("#tel1").focus();
			return false;
		}
		if(isNaN($("#tel1").val())){
			alert("Office/Home Phone1 has to be numbers only.");
			$("#tel1").val("").focus();
			return false;
		}
		if($("#tel2").val()==""){
			alert("Insert Office/Home Phone2.");
			$("#tel2").focus();
			return false;
		}
		if(isNaN($("#tel2").val())){
			alert("Office/Home Phone2 has to be numbers only.");
			$("#tel2").val("").focus();
			return false;
		}
		if($("#tel3").val()==""){
			alert("Insert Office/Home Phone3.");
			$("#tel3").focus();
			return false;
		}
		if(isNaN($("#tel3").val())){
			alert("Office/Home Phone3 has to be numbers only.");
			$("#tel3").val("").focus();
			return false;
		}
		if($("#phone1").val()==""){
			alert("Select Mobile1.");			
			return false;
		}
		if($("#phone2").val()==""){
			alert("Insert Mobile2.");
			$("#phone2").focus();
			return false;
		}
		if(isNaN($("#phone2").val())){
			alert("Mobile2 has to be numbers only.");
			$("#phone2").val("").focus();
			return false;
		}
		if($("#phone3").val()==""){
			alert("Insert Mobile3.");
			$("#phone3").focus();
			return false;
		}
		if(isNaN($("#phone3").val())){
			alert("Mobile3 has to be numbers only.");
			$("#phone3").val("").focus();
			return false;
		}
		if($("#post").val()==""){
			alert("Insert post code.");
			$("#post").focus();
			return false;
		}
		if($("#address").val()==""){
			alert("Insert Address.");
			$("#address").focus();
			return false;
		}
		if($("#male").is(":checked")==false &&
		   $("#female").is(":checked")==false && 
		   $("#Prefer not to say").is(":checked")==false){
			alert("Select your sex.");
			return false;
		}
		
		if($("input:checkbox[name='hobby']:checked").length < 2){
			alert("Select at least 2 hobbies.");
			return false;
		}

		if($("#intro").val()==""){
			alert("Write About Me.");
			$("#intro").focus();
			return false;
		}
		if($("#intro").val().length > 100){
			alert("About Me has to be in up to 100 words.");
			$("#intro").focus();
			return false;
		}		
		
	}); // submit() end		
	
});  // ready() end

19. Create MemberInsert.java class in service package - service folder.

We need to override the method, click the "x" and add unimplemented methods.

package service;

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

import dao.MemberDAO;
import model.MemberDTO;

public class MemberInsert implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("MemberInsert");
		
		request.setCharacterEncoding("utf-8");
		
		MemberDTO member = new MemberDTO();
		member.setId(request.getParameter("id"));
		member.setPasswd(request.getParameter("passwd"));
		member.setName(request.getParameter("name"));
		member.setJumin1(request.getParameter("jumin1"));
		member.setJumin2(request.getParameter("jumin2"));
		member.setMailid(request.getParameter("mailid"));
		member.setDomain(request.getParameter("domain"));
		member.setTel1(request.getParameter("Tel1"));
		member.setTel2(request.getParameter("Tel2"));
		member.setTel3(request.getParameter("Tel3"));
		member.setPhone1(request.getParameter("Phone1"));
		member.setPhone2(request.getParameter("Phone2"));
		member.setPhone3(request.getParameter("Phone3"));
		member.setPost(request.getParameter("Post"));
		member.setAddress(request.getParameter("address"));
		member.setGender(request.getParameter("gender"));
		
		String[] hobby = request.getParameterValues("hobby");
		String h = "";
		for(String h1 : hobby) {
			h += h1 + "=";
		}
		member.setHobby(h);
		member.setIntro(request.getParameter("intro"));
		
		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.insert(member);	// Sign up
		if(result == 1) System.out.println("Successfully signed up. Welcome!");
		
		ActionForward forward = new ActionForward();
		forward.setRedirect(false);					// dispatcher method
		forward.setPath("./member/loginform.jsp"); // page forward
		
		
		ActionForward forward = new ActionForward();
		
		return forward;
	}

}

20. Add Insert method in MemberDAO.java.

	// Sign up 
	public int insert(MemberDTO member) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="insert into member2 ";
				   sql+="values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, member.getId());
			pstmt.setString(2, member.getPasswd());
			pstmt.setString(3, member.getName());
			pstmt.setString(4, member.getJumin1());
			pstmt.setString(5, member.getJumin2());
			pstmt.setString(6, member.getMailid());
			pstmt.setString(7, member.getDomain());
			pstmt.setString(8, member.getTel1());
			pstmt.setString(9, member.getTel2());
			pstmt.setString(10, member.getTel3());
			pstmt.setString(11, member.getPhone1());
			pstmt.setString(12, member.getPhone2());
			pstmt.setString(13, member.getPhone3());
			pstmt.setString(14, member.getPost());
			pstmt.setString(15, member.getAddress());
			pstmt.setString(16, member.getGender());
			pstmt.setString(17, member.getHobby());
			pstmt.setString(18, member.getIntro());
			
			result = pstmt.executeUpdate();
			
		}catch(Exception e){
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

 

21. For ID check, create Idcheck.java in service - src.

22. Add IDcheck part(ajax) in MemberController.java class. 

//ID check(ajax)
		}else if(command.equals("/Idcheck.do")) {
			try {
				action = new IdCheck();
				forward = action.execute(request, response);
			}catch(Exception e) {
				e.printStackTrace();
			}
// Sign up
		} else if (command.equals("/MemberForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("./member/memberform.jsp");

If you click the sign up button, it will load to the sign up form again and the code below"//Sign up" make it possible.

To check if the ID check works, check the console in Eclipse.

 

23. Add lines related to ID check in MemberDAO.java.

// ID check(ajax)
	public int idcheck(String id) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member2 where id=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery(); 			// SQL statement
			
			if(rs.next()) {
				result = 1;
			}else {
				result = -1;
			}
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {			
			if(rs != null) try { rs.close();} catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

24. Create loginform.jsp.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
	<!DOCTYPE html>
	<html>
	<head>
	<meta charset="UTF-8">
	<title>Log In</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>

	<script src="<%=request.getContextPath() %>/member/login.js"></script>
	
	</head>
	<body>
	
	<form method="post" action="<%=request.getContextPath() %>/Login.do">
	<table border=1 width=350 align=center>
		<caption>Log In</caption>
		<tr>
			<td>ID</td>	
			<td><input type=text size=30 id="id" name="id" autofocus="autofocus"></td>	
		</tr>
		<tr>
			<td>Password</td>
			<td><input type="password" size=30 id="passwd" name="passwd"></td>
		</tr>
		<tr>
			<td colspan=2 align=center>
				<input type="button" value="Sign Up" 
				       onClick="location.href='<%=request.getContextPath()%>/MemberForm.do' ">
				<input type="submit" value="Log In">
				<input type="reset" value="Cancel">
			</td>
		</tr>
		
	</table>
	</form>
	
	
	</body>
	</html>

25. Create Login.java class in service- src and override the method.

package service;

import java.io.PrintWriter;

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

import dao.MemberDAO;

public class Login implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Login");

		request.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();

		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");

		MemberDAO dao = MemberDAO.getInstance();
		int result = dao.memberAuth(id, passwd);
		if (result == 1)
			System.out.println("You are successfully logged in.");

		if (result == 1) { // Successful
			session.setAttribute("id", id); // Share with session
		} else { // Failed
			out.println("<script>");
			out.println("alert('Failed to log in.');");
			out.println("history.go(-1);");
			out.println("</script>");
			out.close();

			return null;
		}
		ActionForward forward = new ActionForward();
		forward.setRedirect(false); // Forward with dispatcher method
		forward.setPath("./member/main.jsp"); // To set the file name to forward

		return forward;
	}

}

26. Add memberAuth method in the DAO class.

// Login(Verification)
	public int memberAuth(String id, String passwd) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from member2 where id=? and passwd=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, passwd);
			rs = pstmt.executeQuery();		//To execute SQL
			
			if(rs.next()) {		//Verification Success
				result = 1;
			}else {			  //Verification Fail
				result = -1;
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally{
			if(rs != null) try { rs.close();} catch(Exception e) {}
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();}catch(Exception e) {}
		}
		
		return result;
	}

27. Connect this loginform to the controller class.

// Log in (Verification)
		} else if (command.equals("/Login.do")) {
			try {
				action = new Login();
				forward = action.execute(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

28. Create main.jsp file in member folder.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- When there is a session -->
<%-- <c:if test="${sessionScope.id != null }"> --%>
<c:if test="${!empty sessionScope.id}">    <!-- Empty operator -->
	${sessionScope.id }, Welcome! <br><br>
	
	Edit my profile<br>
	Log out<br>
	Delete my account<br>
</c:if>


<!-- When there is no session -->
<%-- <c:if test="${sessionScope.id == null }"> --%>
<c:if test="${empty sessionScope.id}">
	<a href="<%=request.getContextPath() %>/MemberForm.do">Sign up</a><br>
	<a href="<%=request.getContextPath() %>/LoginForm.do">Log in</a><br>
</c:if>

29. Add another else if for login form toMemberController.java.

// Login form
		} else if (command.equals("/LoginForm.do")) {
			forward = new ActionForward();
			forward.setRedirect(false);
			forward.setPath("./member/loginform.jsp");
		}

So far, we have made the sign-up form, log-in form, and main form connected to the database with MemberDAO class and MemberController class. In the next post, I will demonstrate the log-out form, account update form, and account deletion form.

 

Main funtions 

1. Connection Pool

2.  Action tags : <jsp:useBean...> / <jsp:setProperty...>

3. DTO, DAO class 

4. Paging ( inline view)

5. Uploading files ( using cos.jar library)

 

dbcpAPITest.jsp 

To check the connection

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
 	Connection conn = null; 
	
	try {
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		conn = ds.getConnection();
  		
  		out.println("<h3>Connected.</h3>");
	}catch(Exception e){
		out.println("<h3>Failed to connect.</h3>");
		e.printStackTrace();
 	}
%>

Create a SQL file and create a table and sequence. 

BoardDatabean.java(DTO)

package upload;

import java.sql.Timestamp;

public class BoardDatabean {
	private int num;
	private String writer;
	private String email;
	private String subject;
	private String passwd;
	private Timestamp reg_date;
	private int readcount;
	private String content;
	private String ip;
	private String upload;
	public int getNum() {
		return num;
	}
	public String getWriter() {
		return writer;
	}
	public String getEmail() {
		return email;
	}
	public String getSubject() {
		return subject;
	}
	public String getPasswd() {
		return passwd;
	}
	public Timestamp getReg_date() {
		return reg_date;
	}
	public int getReadcount() {
		return readcount;
	}
	public String getContent() {
		return content;
	}
	public String getIp() {
		return ip;
	}
	public String getUpload() {
		return upload;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public void setReg_date(Timestamp reg_date) {
		this.reg_date = reg_date;
	}
	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public void setUpload(String upload) {
		this.upload = upload;
	}	
}

BoardDBBean.java(DAO)

This is the basics of DAO class, and we will keep adding more codes. 

package upload;

import java.sql.Connection;

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

public class BoardDBBean {
	// Singleton
	private static BoardDBBean instance = new BoardDBBean(); 
	public static BoardDBBean getInstance(){ // static field
	return instance;
	}

	// Method that gets connection from the Connection Pool
	private Connection getConnection() throws Exception{
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		return ds.getConnection();
	}
}

writeForm.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Your Post</b>
<br>
<form method="post" name="writeform" action="writePro.jsp"
	  enctype="multipart/form-data">  

<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp"> Posts</a> 
   </td>
   </tr>
   <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Name</td>
    <td  width="330">
       <input autofocus type="text" size="10" maxlength="10" id="writer" name="writer"></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Title</td>
    <td  width="330">    
       <input type="text" size="40" maxlength="50" id="subject" name="subject"></td>	
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Email</td>
    <td  width="330">
       <input type="text" size="40" maxlength="30" id="email" name="email" ></td>
  </tr>
  <tr>
    <td  width="70"  bgcolor="<%=value_c%>" align="center">Attach File</td>
    <td  width="330">
       <input type="file" size="40"  name="upload" ></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Content</td>
    <td  width="330" >
     <textarea id="content" name="content" rows="13" cols="40"></textarea> </td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Post" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp'">
</td></tr></table>    
   
</form>      
</body>
</html>

 

writePro.jsp

<%@page import="upload.BoardDBBean"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	// Location of Directory
String path = request.getRealPath("upload");
System.out.println("path: " + path);

// Size of the files : 1MB
int size = 1024 * 1024;

// To upload files -> MultipartRequest object
MultipartRequest multi = new MultipartRequest(request, 
		path, // Location of Directory 
		size, // Size 
		"utf-8", // Encoding type
		new DefaultFileRenamePolicy()); // Overlapped files

String writer = multi.getParameter("writer");
String subject = multi.getParameter("subject");
String email = multi.getParameter("email");
String content = multi.getParameter("content");
String passwd = multi.getParameter("passwd");

// Original file name: file name uploaded by the client
String upload0 = multi.getOriginalFileName("upload");

// Save file name 
String upload = multi.getFilesystemName("upload");

BoardDataBean board = new BoardDataBean();
board.setWriter(writer);
board.setEmail(email);
board.setSubject(subject);
board.setContent(content);
board.setPasswd(passwd);
board.setIp(request.getRemoteAddr()); // Client's IP address
board.setUpload(upload); // Saved file's name

BoardDBBean dao = BoardDBBean.getInstance();
int result = dao.insert(board);

if (result == 1) {
%>

<script>
	alert("Posted successfully.");
	location.href = "list.jsp";
</script>
<%
	} else {
%>
<script>
	alert("Failed to post.");
	history.go(-1);
</script>

<%
	}
%>

list.jsp

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

	int page_size = 10;

	String pageNum = request.getParameter("page");
	if(pageNum == null){
		pageNum = "1";		
	}
	
	int currentPage = Integer.parseInt(pageNum);
	
	int startRow = (currentPage - 1) * page_size + 1;
	int endRow = currentPage * page_size;
	
    // Total data 
	int count = 0;
	
	BoardDBBean dao = BoardDBBean.getInstance();
	count = dao.getCount();
	System.out.println("count:"+count);
	
	List<BoardDataBean> list = null;
	if(count > 0){
		list = dao.getList(startRow, endRow);
	}
	System.out.println("list:"+list);
%>      
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	if(count == 0){
%>
		No posts yet.
<%	}else{ %>
	
		<a href="writeForm.jsp">Write</a> Total posts : <%=count %>
		<table border=1 width=700 align=center>
			<caption>List</caption>
			<tr>
				<th>No.</th>
				<th>Title</th>
				<th>Writer</th>
				<th>Date</th>
				<th>View</th>
				<th>IP Address</th>
			</tr>
<%
			// start number
			int number = count - (currentPage-1) * page_size;

			SimpleDateFormat sd = 
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			for(int i=0; i<list.size(); i++){
				BoardDataBean board = list.get(i);
%>				
			<tr>
				<td><%=number-- %></td>
				<td>
				
<a href="content.jsp?num=<%=board.getNum()%>&page=<%=currentPage%>">				
				<%=board.getSubject() %>
</a>	
			
				</td>
				<td><%=board.getWriter() %></td>
				<td><%=sd.format(board.getReg_date()) %></td>
				<td><%=board.getReadcount() %></td>
				<td><%=board.getIp() %></td>
			</tr>			
				
<%			} // for end
%>
			
		</table>	
		
<%	} // else end
%>

<!-- Page Link -->
<center>
<%
if(count > 0){
	
	int pageCount=count/page_size + ((count%page_size==0) ? 0:1);
	System.out.println("pageCount:"+pageCount);

	// startRow & endRow
	// 1 page : startRow=1,  endRow=10
	// 2 page : startRow=11, endRow=20
	// 3 page : startRow=21, endRow=30
	int startPage = ((currentPage-1)/10) * 10 + 1;
	int block = 10;	
	int endPage = startPage + block - 1;
	
	if(endPage > pageCount){
		endPage = pageCount;
	}
%>	
	<!-- Move to page 1 -->
	<a href="list.jsp?page=1" style="text-decoration:none"> << </a>

<%
	// Previous block
	if(startPage > 10){
%>	
		<a href="list.jsp?page=<%=startPage-10%>">[Prev]</a>	
<%	}	


	for(int i=startPage; i<=endPage; i++){
		if(i==currentPage){ 		 %>
				[<%=i%>]
<% 		}else{ %>
				<a href="list.jsp?page=<%=i%>">[<%=i%>]</a>
<% 		}	
	} // for end

	// Next block
	if(endPage < pageCount){ %>
			<a href="list.jsp?page=<%=startPage+10%>">[Next]</a>		
<%	}  %>
	
	<!-- Move to the last page -->
		<a href="list.jsp?page=<%=pageCount%>"
			style="text-decoration:none"> >> </a>			
<%	
}
%>
</center>

</body>
</html>

content.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	int num = Integer.parseInt(request.getParameter("num"));
String nowpage = request.getParameter("page");

BoardDBBean dao = BoardDBBean.getInstance();

// view count +1 & get detail 
BoardDataBean board = dao.updateContent(num);

SimpleDateFormat sd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

String content = board.getContent().replace("\n", "<br>");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Detail</title>
</head>
<body>
	<table border=1 width=500 align=center>
		<caption>Detail</caption>
		<tr>
			<td>No.</td>
			<td><%=board.getNum()%></td>
			<td>View</td>
			<td><%=board.getReadcount()%></td>
		</tr>
		<tr>
			<td>Writer</td>
			<td><%=board.getWriter()%></td>
			<td>Date</td>
			<td><%=sd.format(board.getReg_date())%></td>
		</tr>
		<tr>
			<td>Title</td>
			<td colspan=3><%=board.getSubject()%></td>
		</tr>
		<tr>
			<td>Content</td>
			<td colspan=3><%=board.getContent()%> <%=content%></td>
		</tr>
		<tr>
			<td>Attached File</td>
			<td colspan=3>
				<!-- If there is files to attach --> <%
 	if (board.getUpload() != null) {
 %> <a href="file_down.jsp?file_name=<%=board.getUpload()%>"> <%=board.getUpload()%>
			</a> <%
 	}
 %>
			</td>
		</tr>
		<tr>
			<td colspan=4 align=center><input type="button" value="Edit"
				onClick="location.href='updateForm.jsp?num=<%=num%>&page=<%=nowpage%>'">
				<input type="button" value="Delete"
				onClick="location.href='deleteForm.jsp?num=<%=num%>&page=<%=nowpage%>'">
				<input type="button" value="Go back to List"
				onClick="location.href='list.jsp?page=<%=nowpage%>'"></td>
		</tr>
	</table>

</body>
</html>

updateForm.jsp

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<%
	int num = Integer.parseInt(request.getParameter("num"));
	String nowpage = request.getParameter("page");
	
	BoardDBBean dao = BoardDBBean.getInstance();
	
	// To get detail 
	BoardDataBean board = dao.getContent(num);
%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Your Post</b>
<br>
<form method="post" name="writeform" action="updatePro.jsp"
	  enctype="multipart/form-data">  
<input type="hidden" name="num" value="<%=num %>">
<input type="hidden" name="page" value="<%=nowpage %>">


<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp?page=<%=nowpage%>"> Posts</a> 
   </td>
   </tr>
   <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Name</td>
    <td  width="330">
       <input autofocus type="text" size="10" maxlength="10" id="writer" name="writer" 
       value="<%=board.getWriter()%>"></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Title</td>
    <td  width="330">    
       <input type="text" size="40" maxlength="50" id="subject" name="subject" value="<%=board.getSubject()%>"></td>	
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Email</td>
    <td  width="330">
       <input type="text" size="40" maxlength="30" id="email" name="email" value="<%=board.getEmail()%>" ></td>
  </tr>
  <tr>
    <td  width="70"  bgcolor="<%=value_c%>" align="center">Attach File</td>
    <td  width="330">
       <input type="file" size="40"  name="upload" ><%=board.getUpload() %></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Content</td>
    <td  width="330" >
     <textarea id="content" name="content" rows="13" cols="40"><%=board.getContent() %></textarea> </td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Post" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp?page=<%=nowpage%>'">
</td></tr></table>    
   
</form>      
</body>
</html>

updatePro.jsp

<%@page import="upload.BoardDBBean"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	// Location of Directory
String path = request.getRealPath("upload");
System.out.println("path: " + path);

// Size of the files : 1MB
int size = 1024 * 1024;

// To upload files -> MultipartRequest object
MultipartRequest multi = new MultipartRequest(request, 
		path, // Location of Directory 
		size, // Size 
		"utf-8", // Encoding type
		new DefaultFileRenamePolicy()); // Overlapped files
		
int num = Integer.parseInt(multi.getParameter("num"));
String nowpage = multi.getParameter("page");

String writer = multi.getParameter("writer");
String subject = multi.getParameter("subject");
String email = multi.getParameter("email");
String content = multi.getParameter("content");
String passwd = multi.getParameter("passwd");

// Original file name: file name uploaded by the client
String upload0 = multi.getOriginalFileName("upload");

// Save file name 
String upload = multi.getFilesystemName("upload");

BoardDataBean board = new BoardDataBean();
board.setNum(num);
board.setWriter(writer);
board.setEmail(email);
board.setSubject(subject);
board.setContent(content);
board.setPasswd(passwd);
board.setIp(request.getRemoteAddr()); // Client's IP address
// board.setUpload(upload); // Saved file's name

BoardDBBean dao = BoardDBBean.getInstance();
BoardDataBean old = dao.getContent(num);

if(upload != null){ //If the attached file is edited
	board.setUpload(upload);
}else{					// If the attached file is not edited
	board.setUpload(old.getUpload());
}

System.out.println(old.getPasswd());
System.out.println(passwd);

// To compare passwords
if(old.getPasswd().equals(passwd)) {
	int result = dao.update(board);
	
	if(result ==1){
	%>
<script>
	alert("Posted successfully.");
	location.href="list.jsp?page=<%=nowpage%>";
</script>

<% } 
	}else{ // Incorrect Password %>
<script>
	alert("Incorrect password.");
	history.go(-1);
</script>

<%
	}
%>

deleteForm.jsp

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<%
	int num = Integer.parseInt(request.getParameter("num"));
	String nowpage = request.getParameter("page");
%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Please enter your password to delete your post.</b>
<br>
<form method="post" name="writeform" action="deletePro.jsp"> 
<input type="hidden" name="num" value="<%=num %>">
<input type="hidden" name="page" value="<%=nowpage %>">


<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp?page=<%=nowpage%>"> Posts</a> 
   </td>
   </tr>

  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Delete" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp?page=<%=nowpage%>'">
</td></tr></table>    
   
</form>      
</body>
</html>

deletePro.jsp

When it comes to deletion, the attached files have to be deleted along with the posts that are being deleted.

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="board" class="upload.BoardDataBean"/>
<jsp:setProperty property="*" name="board"/>

<%
	String nowpage = request.getParameter("page");

	String path = request.getRealPath("upload");
	System.out.println("Path: "+ path);
	
	BoardDBBean dao = BoardDBBean.getInstance();
	BoardDataBean old = dao.getContent(board.getNum());
	
	// To compare the passwords
	if(old.getPasswd().equals(board.getPasswd())){ 	// Correct password
		int result = dao.delete(old, path);
	if(result == 1) {
%>	
		<script>
			alert("Successfully deleted.");
			location.href="list.jsp?page=<%=nowpage%>";
		</script>
		<% } %>
<% 	}else { %> 							// Incorrect password
	<script>
		alert("Incorrect password.");
		history.go(-1);
	</script>
<% } %>

 

Please refer to my last post about deleting the attached file : 

2022.09.14 - [Java] - Deleting attached files

BoardDBBean.java

// DAO(Data Access Object)
package upload;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

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


public class BoardDBBean {
	// Singleton
	private static BoardDBBean instance = new BoardDBBean(); 
	public static BoardDBBean getInstance(){ // static field
	return instance;
	}

	// Method that gets connection from the Connection Pool
	private Connection getConnection() throws Exception{
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		return ds.getConnection();
	}
	
	// insert method 
	public int insert(BoardDataBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			String sql="insert into upload values(upload_seq.nextval,?,?,?,?,";
				   sql+="sysdate,?,?,?,?)";
				   
				   pstmt = con.prepareStatement(sql);
				   pstmt.setString(1, board.getWriter());
				   pstmt.setString(2, board.getEmail());
				   pstmt.setString(3, board.getSubject());
				   pstmt.setString(4, board.getPasswd());
				   pstmt.setInt(5, board.getReadcount());    // view count
				   pstmt.setString(6, board.getContent());
				   pstmt.setString(7, board.getIp());
				   pstmt.setString(8, board.getUpload());
				   
				   result = pstmt.executeUpdate();  		// To execute the SQL 
				   
				   
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		return result;
	}
	
	// getCount Method
	public int getCount() {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select count(*) from upload";
			
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				result = rs.getInt(1);
				result = rs.getInt("count(*)");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	// List : Extract 10 data
	public List<BoardDataBean> getList(int start, int end){
		List<BoardDataBean> list = new ArrayList<BoardDataBean>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from (select rownum rnum, upload.* from ";
				   sql+=" (select * from upload order by num desc) upload) ";
				   sql+=" where rnum >=? and rnum <=?";
				   
				   pstmt = con.prepareStatement(sql);
				   pstmt.setInt(1, start);
				   pstmt.setInt(2, end);
				   rs = pstmt.executeQuery();
				   
				   while(rs.next()) {
					   BoardDataBean board = new BoardDataBean();
					   
					   board.setNum(rs.getInt("num"));
					   board.setWriter(rs.getString("writer"));
					   board.setEmail(rs.getString("email"));
					   board.setSubject(rs.getString("subject"));
					   board.setSubject(rs.getString("subject"));
					   board.setPasswd(rs.getString("passwd"));
					   board.setReg_date(rs.getTimestamp("reg_date"));
					   board.setReadcount(rs.getInt("readcount"));
					   board.setContent(rs.getString("content"));
					   board.setIp(rs.getString("ip"));
					   board.setUpload(rs.getString("upload"));
					   
					   list.add(board);
				   }
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		return list;
	}
	
	// Detail page : view count +1 & detail information
	public BoardDataBean updateContent(int num) {
		BoardDataBean board = new BoardDataBean();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set readcount = readcount + 1 ";
				   sql+=" where num = ?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();	//To execute SQL
			
			sql="select * from upload where num = ?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				   board.setNum(rs.getInt("num"));
				   board.setWriter(rs.getString("writer"));
				   board.setEmail(rs.getString("email"));
				   board.setSubject(rs.getString("subject"));
				   board.setSubject(rs.getString("subject"));
				   board.setPasswd(rs.getString("passwd"));
				   board.setReg_date(rs.getTimestamp("reg_date"));
				   board.setReadcount(rs.getInt("readcount"));
				   board.setContent(rs.getString("content"));
				   board.setIp(rs.getString("ip"));
				   board.setUpload(rs.getString("upload"));
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}

		return board;
	}
	// Update : to get detail
	public BoardDataBean getContent(int num) {
		BoardDataBean board = new BoardDataBean();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set readcount = readcount + 1 ";
				   sql+=" where num = ?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();	//To execute SQL
			
			sql="select * from upload where num = ?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				   board.setNum(rs.getInt("num"));
				   board.setWriter(rs.getString("writer"));
				   board.setEmail(rs.getString("email"));
				   board.setSubject(rs.getString("subject"));
				   board.setSubject(rs.getString("subject"));
				   board.setPasswd(rs.getString("passwd"));
				   board.setReg_date(rs.getTimestamp("reg_date"));
				   board.setReadcount(rs.getInt("readcount"));
				   board.setContent(rs.getString("content"));
				   board.setIp(rs.getString("ip"));
				   board.setUpload(rs.getString("upload"));
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}

		return board;
	}
	
	// Update method
	public int update(BoardDataBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set writer=?,email=?,subject=?,";
				   sql+="content=?,ip=?,upload=? where num=?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getWriter());
			pstmt.setString(2, board.getEmail());
			pstmt.setString(3, board.getSubject());
			pstmt.setString(4, board.getContent());
			pstmt.setString(5, board.getIp());
			pstmt.setString(6, board.getUpload());
			pstmt.setInt(7, board.getNum());
			
			result = pstmt.executeUpdate();   // To execute SQL 
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	// Delete the post & attached file
	public int delete(BoardDataBean board, String path) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="delete from upload where num=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, board.getNum());
			result = pstmt.executeUpdate();			// To execute SQL 
			
			if(board.getUpload() != null) { // if there is any file attached
				
				File file = new File(path);
				
				// To read all files in the upload directory
				File[] f = file.listFiles();
				
				for(int i=0; i<f.length; i++) {
					
					if(f[i].getName().equals(board.getUpload())) {
						f[i].delete(); 		// To delete the attached file
					}
				}
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	
}

index.jsp

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

	<script>
		location.href = "upload1/list.jsp";
	</script>

</body>
</html>

Function tags

Function tags provide many functions we can use to perform common operations, most of which are for String manipulation, such as String COncatenation, Split String, etc. 

Here are some tags that you can refer to before looking at examples. 

 

Tag Description
fn:contains() It is used to test if an input string containing the specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case insensitive way.
fn:endsWith() It tests whether an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of the first occurrence of a specified substring.
fn:trim() It removes the blank spaces from both ends of a string.
fn:startsWith() It is used to check whether the given string starts with a particular string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lowercase.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:substringAfter() It returns the subset of the string after a specific substring.
fn:substringBefore() It returns the subset of the string before a specific substring.
fn:length() It returns the number of characters inside a string or items in a collection.
fn:replace() It replaces all the occurrences of a string with another string sequence.

Example

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<style>
@import url('https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap');
</style>

<html>
<head><title>Function Tag</title></head>
<body style="font-family: 'Josefin Sans', sans-serif;">
<c:set var="str1" value="Happy days!"/>
<c:set var="str2" value="app" />
<c:set var="tokens" value="1,2,3,4,5,6,7,8,9,10" />

length(str1) = ${fn:length(str1)} <br>
toUpperCase(str1) = "${fn:toUpperCase(str1)}" <br>
toLowerCase(str1) = "${fn:toLowerCase(str1)}" <br>
substring(str1, 3, 6) = "${fn:substring(str1, 3, 6)}" <br>
substringAfter(str1, str2) = "${fn:substringAfter(str1, str2)}" <br>
substringBefore(str1, str2) = "${fn:substringBefore(str1, str2)}" <br>
trim(str1) = "${fn:trim(str1)}" <br>
replace(str1, src, dest) = "${fn:replace(str1, " ", "-")}" <br>
indexOf(str1, str2) = "${fn:indexOf(str1, str2)}" <br>
startsWith(str1, str2) = "${fn:startsWith(str1, 'Fun')}" <br>
endsWith(str1, str2) = "${fn:endsWith("Using", str1)}" <br>
contains(str1, str2) = "${fn:contains(str1, str2)}" <br>
containsIgnoreCase(str1, str2) = "${fn:containsIgnoreCase(str1, str2)}" <br>

<c:set var="array" value="${fn:split(tokens, ',')}" />

join(array, "-") = "${fn:join(array, "-")}" <br>
escapeXml(str1) = "${fn:escapeXml(str1)}" <br>

</body>
</html>

SQL tags

SQL tags support interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags, we can run database queries. We first need to create a table with the totoro account to demonstrate. 

create table test(
	num number,
	name varchar2(10),
	primary key(num) );

In the code, first, we insert the data and print out the data with the select SQL.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<html>
<head>
<title>JSTL sql Tags</title>
</head>
<body>

	<sql:setDataSource var="conn" driver="oracle.jdbc.driver.OracleDriver"
		url="jdbc:oracle:thin:@localhost:1521:xe" user="totoro"
		password="totoro123" />

	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (1, 'Meadow')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (2, 'Dodo')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (3, 'Forest')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (4, 'Jenny')
</sql:update>

	<sql:query var="rs" dataSource="${conn}">
	SELECT * FROM test WHERE name=?
	<sql:param>Meadow</sql:param>
	</sql:query>

	<c:forEach var="data" items="${rs.rows}">
		<c:out value="${data['num']}" />
		<c:out value="${data['name']}" />
		<br>
	</c:forEach>

</body>
</html>

Search the table with select * from test; , you will see the inserted data.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

Internationalization tags are the second most used tags in JSTL. The most used tags are core tags, as you can refer to in my last post.

2022.09.17 - [JSP] - JSP) JSTL (JSP Standard Tag Library) - Core tags

 

Internationalization tags are related to numbers, dates, and timezone. The example tag with the URI is like this : 

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

The prefix value is "fmt" and the URI ends with "fmt" which refers to the internationalization tag. 

For your better understanding, let us look through some simple examples. 

 

numberFormat Tag

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head><title>numberFormat Tag</title></head>
<body>

<c:set var="now" value="<%= new java.util.Date() %>" />
${now }<br>
<c:out value="${now }"/><br>

<fmt:formatDate value="${now}" type="date" dateStyle="full" /> <br> <!-- in detail -->
<fmt:formatDate value="${now}" type="date" dateStyle="short" /> <br> <!-- simple -->
<fmt:formatDate value="${now}" type="time" /> <br>
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" /> <br>
<fmt:formatDate value="${now}" pattern="z a h:mm" /> <br><br> <!-- z: timezone a: am/pm -->
<fmt:formatDate value="${now}" pattern="MM/dd/yy EEEE h:mm a z"/><br>
</body>
</html>

timeZone tag

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head><title>timeZone Tag</title></head>
<body>

<c:set var="now" value="<%= new java.util.Date() %>" />


<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />

<br>
<fmt:timeZone value="Hongkong">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>

<fmt:timeZone value="America/New_York">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>

<fmt:timeZone value="Asia/Seoul">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>


</body>
</html>

formatNumber Tag

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<title>formatNumber Tag</title>
</head>
<body>

	<c:set var="price" value="10000" />
	<fmt:formatNumber value="${price}" type="number" var="numberType" />
	Number: ${numberType}  <!-- Variable name -->
	<br> KRW:
	<fmt:formatNumber value="${price}" type="currency" currencySymbol="\\" />
	<br> USD:
	<fmt:formatNumber value="${price}" type="currency" currencySymbol="$" />
	<br> Percentage:
	<fmt:formatNumber value="${price}" type="percent" groupingUsed="true" />
	<br> Percentage:
	<fmt:formatNumber value="${price}" type="percent" groupingUsed="false" />
	<br> Pattern:
	<fmt:formatNumber value="${price}" pattern="00000000.00" />

</body>
</html>

 

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Function tags / SQL tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

As we discussed, Model 2 consists of Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library). In this post, we will learn about JSTL. 

JSLT, itself stands for JSP Standard Tag Library. So what do we need to do first? 

To download the library!

 

First, go to apache taglibs.

https://tomcat.apache.org/taglibs/standard/

And click the download. 

That's actually it for the configuration!

 

These are the five types of tags in JSTL. Among then, we use mostly the core and Internationalization library.

Tags Description Example
Core Provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc. <%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
Internationalization  For formatting of Numbers, Dates and i18n support through locales and resource bundles. <%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
SQL Provide support for interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags we can run database queries. <%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
XML
Used to work with XML documents such as parsing XML, transforming XML data, and evaluating XPath expressions. <%@ taglib uri="https://java.sun.com/jsp/jstl/xml" prefix="x" %>
Functions 
Provide many functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc.  <%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Here are some most used JSTL Core Tags and examples of them.

Tags Description
c:set Sets the result of an expression under evaluation in a 'scope' variable.
c:if Conditional tag used for testing the condition and display the body content only if the expression evaluates is true.
c:choose Simple conditional tag that includes its body content if the evaluated condition is true.
c:forEach Repeats the nested body content for fixed number of times or over collection.
c:import Retrieves relative or an absolute URL and display the contents to either a String in 'var',a Reader in 'varReader' or the page.
c:out Displays the result of an expression, similar to the way <%=...%> tag work.

 

Set tag / Remove tag

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="num1" value="${20}" />
<c:set var="num2">
10.5
</c:set>
<c:set var="today" value="<%= new java.util.Date() %>" />

<html>
	<head>
		<title>set Tag & remove Tag</title>
	</head>

	<body>
		Variable num1 = ${num1} <br>
		Variable num2 = ${num2} <br>
		num1 + num2 = ${num1 + num2} <br>
		Today is ${today}.

		<c:remove var="num1" scope="page" />

		<p>
		num1 after deletion = ${num1} <br>
		num1 + num2 after deletion = ${num1 + num2}
	</body>
</html>

As you can see above, EL is used to print out in JSTL, which means you can use EL by itself, but JSTL has to collaborate with EL. 

You need to use the request object to use the EL tag.

	<%
		String str = "JSP Variable";
		request.setAttribute("st", str); 
	%>
		Variable1: str1 = <%=str %> <br>	<!-- Printed -->
		Variable2: str2 = ${str} <br> 		<!-- Not printed -->
		Variable3: str3 = ${st} <br> 		<!-- Printed -->

if tag

if tag is to process a single condition.

ifTagForm.jsp

<%@ page contentType = "text/html; charset=utf-8" %>

<html>	
	<body>
	<form method=post action=ifTag.jsp>
	Name <input type=text name=name><br>
	Age <input type=text name=age><br>
	<input type=submit value="Submit">
	</form>
	</body>
</html>

ifTag.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<c:if test="true">
If the test value is "true", it always runs. <br>
</c:if>

<c:if test="${param.name == 'Meadow' }">
 Hello ${param.name }, welcome! <br>
</c:if>

<c:if test="${param.age >= 18 }">
You are an adult! haha!<br>
</c:if>

choose tag 

choose ~ when ~ otherwise tag is used when we process multiple conditions.

It is the same as switch ~ case ~ default in java.

If there is a condition that the value meets, it will execute the tag and stop execution. 

ifTagFrom.jsp

<%@ page contentType = "text/html; charset=utf-8" %>

<html>	
	<body>
	<form method=post action=chooseTag.jsp>
	Name <input type=text name=name><br>
	Bloodtype <input type=text name=bloodtype><br>
	<input type=submit value="Submit">
	</form>
	</body>
</html>

chooseTag.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<ul>
		<c:choose>
			<c:when test="${param.name == 'Meadow' }">
				<li>Your name is ${param.name }.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'O' }">
				<li>Your bloodtype is O! People with type O blood less
					susceptible to malaria.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'A' }">
				<li>Your bloodtype is A! People with type A blood are more
					likely to develop stomach cancer.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'AB' }">
				<li>Your bloodtype is AB! People with type AB blood are much
					more likely to develop cognitive issues.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'B' }">
				<li>Your bloodtype is B! About 9% of the population have B
					positive blood.</li>
			</c:when>
			<c:otherwise>
				<li>Your name is not Meadow, and there is no such bloodtype. 
				</li>
			</c:otherwise>
		</c:choose>
	</ul>

</body>
</html

If I enter the name "Meadow", it will stop executing at the first condition since it meets the condition. 

 

If I enter the other name and the blood type(O,A,AB, or B), it will execute that condition.

catch tag / out tag

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>JSTL core Library Example 1</title>
</head>
<body>
	<c:set var="test" value="Hello JSTL!" />
	<h3>
		Using &lt;c:set&gt; :
		<c:out value="${test}" />
	</h3>
	<c:remove var="test" />
	<h3>
		Using &lt;c:remove&gt; :
		<c:out value="${test}" />
	</h3>

	<c:catch var="err">
		<%=10 / 0%>
	</c:catch>
	<h3>
		An error caught by &lt;c:catch&gt;:
		<c:out value="${err}" />
	</h3>

	<c:if test="${5<10}">
		<h3>5 is lesser than 10.</h3>
	</c:if>
	<c:if test="${6+3==9}">
		<h3>6 + 3 equals 9.</h3>
	</c:if>

	<c:choose>
		<c:when test="${5+10==50}">
			<h3>5+10 equals 50.</h3>
		</c:when>

		<c:otherwise>
			<h3>5+10 not equal 50.</h3>
		</c:otherwise>
	</c:choose>
</body>
</html>

forEach tag

It is like a loop in java, while the format is different from it. 

There are two big types in this forEach tag. Type 1 is more used than the other. Let us look at the example codes.

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	java.util.HashMap mapData = new java.util.HashMap();
	mapData.put("name", "Meadow");
	mapData.put("today", new java.util.Date());
%>
<c:set var="intArray" value="<%=new int[] { 1, 2, 3, 4, 5 }%>" />
<c:set var="map" value="<%=mapData%>" />
<html>
<head>
<title>forEach Tag</title>
</head>
<body>
	<h4>Sum of odd integers from 1 to 100.</h4>
	<c:set var="sum" value="0" />
	<c:forEach var="i" begin="1" end="100" step="2">
		<c:set var="sum" value="${sum + i}" />
	</c:forEach>
	Result = ${sum}

	<h4>4 Times table</h4>
	<ul>
		<c:forEach var="i" begin="1" end="9">
			<li>4 * ${i} = ${4 * i}
		</c:forEach>
	</ul>

	<h4>Array - Datatype int</h4>

	<c:forEach var="i" items="${intArray}" begin="2" end="4">
    [${i}]
</c:forEach>

	<h4>Map</h4>

	<c:forEach var="i" items="${map}">
    ${i.key} = ${i.value}<br>
	</c:forEach>
	<br>
	<br>

	<%
		List list = new ArrayList();
	list.add("Toronto");
	list.add("Halifax");
	list.add("Vancouver");
	list.add("Calgary");
	list.add("Airdrie");
	list.add("Winnipeg");
	list.add("Yellowknife");

	request.setAttribute("slist", list);
	%>
	<!-- Type 1 -->
	<c:forEach var="s" items="${slist}">
		${s} <br>
	</c:forEach>
	<br>
	<br>

	<%
		// Origianl code
	List li = (List) request.getAttribute("slist");
	for (int i = 0; i < li.size(); i++) {
		String str = (String) li.get(i);
		out.println(str + "<br>");
	}
	%><br><br>
	
	<!-- Type 2 -->
	<c:set var="s1" value="<%=list %>"/>
	<c:forEach var="s2" items="${s1}">
		${s2} <br>
	</c:forEach>
</body>
</html>

Other tags(not used a lot)

forTokens tag

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head><title>forTokens tag</title></head>
<body>

delims= ",." :<br>
<c:forTokens var="token" 
             items="Red,Orange.Yellow.Green,Blue,Navy.Purple"
             delims=",.">
${token} 
</c:forTokens>

</body>
</html>

forEach tag / forTokens tag

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>JSTL core Library Example</title>
</head>
<body>
	<c:forEach var="test" begin="1" end="10" step="2">
		<b>${test}</b>&nbsp;
</c:forEach>
	<br>
	<c:forTokens var="alphabet" items="a,b,c,d,e,f,g,h,i,j,k,l,m,n"
		delims=",">
		<b>${alphabet}</b>&nbsp;
</c:forTokens>
	<br>
	<c:set var="data" value="Banana,Orange,Melon" />
	<c:forTokens var="varData" items="${data}" delims=",">
		<b>${varData}</b>&nbsp;
</c:forTokens>
</body>
</html>

So far, we have learned about Core tags, which are the most used, in the next post, we will see the second most used ones, internationalization tags.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Function tags / SQL tags  (0) 2022.09.19
JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

To develop with the Model2 MVC patterns, we need to know Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library), and we already covered the Java Servlet class in the last posts. If you want to go check out, please click the link below.

2022.09.15 - [JSP] - JSP) Model2 - Java Servlet 1

2022.09.16 - [Codes & Projects] - JSP) Model2 - Java Servlet 2

 

 

In this post, we will discuss Expression Language, which we use instead of Expression tags in the model2, we use Expression language. It looks different from the expression tags we have been using, but once we get used to it, it will be easier and simpler.

 

For example, param is used as${param.name} and sessionScope is used as${sessionScope.id}

 

For a better understanding, let us look through the examples.

 

Example 1

Arithmetic Operators

To print out the EL on the browser, you must use "\". 

  <TR>
    <TD>\${2 + 5}</TD>
    <TD>${2 + 5}</TD>
  </TR>

To divide, you can use either "/" or "div" and the result will be the same. "mod" is to get the remainder.

  <TR>
    <TD>\${4/5}</TD>
    <TD>${4/5}</TD>
  </TR>
  <TR>
    <TD>\${5 div 6}</TD>
    <TD>${5 div 6}</TD>
  </TR>
  <TR>
    <TD>\${5 mod 7}</TD>
    <TD>${5 mod 7}</TD>
  </TR>

Comparison Operators

"<" is same as "gt"(greater) and ">" is same as "le"(less).

  <TR>
    <TD>\${2 < 3}</TD>
    <TD>${2 < 3}</TD>
  </TR>
  <TR>
    <TD>\${2 gt 3}</TD>
    <TD>${2 gt 3}</TD>
  </TR>
  <TR>
    <TD>\${3.1 le 3.2}</TD>
    <TD>${3.1 le 3.2}</TD>
  </TR>

Conditional Operators

<TR>
    <TD>\${(5 > 3) ? 5 : 3}</TD>
    <TD>${(5 > 3) ? 5 : 3}</TD>
  </TR>

Implicit Objects

  <TR>
    <TD>\${header["host"]}</TD>
    <TD>${header["host"]}</TD>
  </TR>
  <TR>
    <TD>\${header["user-agent"]}</TD>
    <TD>${header["user-agent"]}</TD>
  </TR>

Example 2

Processing parameter value

<%@ page contentType="text/html;charset=utf-8"%>
<% request.setCharacterEncoding("utf-8");%>

<HTML>
<HEAD>
<TITLE>EL Example2</TITLE>
</HEAD>

<BODY>

<H3>Processing parameter value</H3>
<P>
<FORM action="eLEx2.jsp" method="post">
   Name : <input type="text" name="name" value="${param['name']}">
          <input type="submit" value="Submit">
</FORM>

<P>
Hello <%=request.getParameter("name") %>, how are you today? <br>
Would you like to have a cup of tea, ${param.name}?

</BODY>
</HTML>

The followings bring the same result, but as you can see, EL is simpler than JSP expression tag. 

You can also use ${param['name']}.

Hello <%=request.getParameter("name") %>, how are you today? <br>
Would you like to have a cup of tea, ${param.name}?
${param['name']}

There are several ELs that you can use simpler way.

Object EL JSP expression tag
param ${param.name} <%=request.getParameter("name"%>
sessionScope ${sessionScope.id} <%=session.getAttribute("id")%>
requestScope ${requestScope.page} <%=request.getAttribute("page")%>

 

Example 3

Product.java

package jspbook;

public class Product {

	// Products (Array)
	private String[] productList = {"item1","item2","item3","item4","item5"};
	
	// Variables
	private int num1 = 10;
	private int num2 = 20;
	
	public int getNum1() {
		return num1;
	}

	public int getNum2() {
		return num2;
	}

	public String[] getProductList() {
		return productList;
	}
}

productList.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
%>

<html>

	<head>
		
<meta charset="utf-8">

		<title>EL Example 3</title>

	</head>

	<body>

	<center>
		<H2>Product list</H2>
		<HR>
	<form method="post" action="productSel.jsp">
		<jsp:useBean id="product" class="jspbook.Product" scope="session"/>
		<select name="sel">
			<%
			for(String item : product.getProductList()) {
				out.println("<option>"+item+"</option>");
			}
			%>
		</select>
		<input type="submit" value="Select"/>
	</form>
	</center>
</body>

</html>

productSel.jsp

<%@page import="jspbook.Product"%>
<%@ page language="java" contentType="text/html; charset=utf-8"%>

<html>
	<head>		
		<meta charset="utf-8">
		<title>EL Example 3</title>
	</head>
	<body>
		<center>
		<H2>Selected product</H2>
		<HR>
		1. (EL) You selected : ${param.sel} <br> 
		1. (Expression tag) You selected : <%=request.getParameter("sel") %><br>
		
		2. num1 + num2 = ${product.num1+product.num2} <br>
<%
	Product pro = (Product) session.getAttribute("product");
%>
		2.(Expression tag) num1 + num2 = <%=pro.getNum1() + pro.getNum2()%>
		</center>
	</body>
</html>

As you explored in this post, Expression Language is often simpler, so as we learn, we will use it more often than the expression tags of the JSP.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31

+ Recent posts