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.

 

+ Recent posts