[필기정리]Day76-1 - doGet, doPost, service, 회원가입 구현 예시 등

Web/JSP

2020. 10. 14. 12:11

# print vs println

ex)

- test1.java (println)

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/Test1")
public class Test1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test1() {
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

- test2.java (print)

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/Test2")
public class Test2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test2() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.print("<!DOCTYPE>");
		out.print("<html>");
		out.print("<head>");
		out.print("<title>out Test</title>");
		out.print("</head>");
		out.print("<body>");
		out.print("<p>안녕하세요.</p>");
		out.print("</body>");
		out.print("</html>");
	}
}

# Servlet - doGet, doPost, service

ex) 

- form.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="FormTest"> 
<input type="submit" value="get"> // doGet 호출
</form>
<form method="post" action="FormTest">
<input type="submit" value="post"> // doPost 호출
</form>
</body>
</html>

- FormTest.java

package com.superman.www;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FormTest")
public class FormTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FormTest() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("post");
	}
}

 

- form2.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="FormTest2">
<input type="submit" value="get"> // service 호출
</form>
<form method="post" action="FormTest2">
<input type="submit" value="post"> // service 호출
</form>
</body>
</html>

// get, post 방식 모두 service로 받을 수 있다!

 

- FormTest2.java (서비스만 만든 예시)

package com.superman.www;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FormTest2")
public class FormTest2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FormTest2() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("service");
	}

}

- form3.jsp 

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="FormTest3">
<input type="submit" value="get"> // service 호출
</form>
<form method="post" action="FormTest3">
<input type="submit" value="post"> // service 호출
</form>
</body>
</html>

// doGet과 doPost가 있더라도 service가 우선시 된다.

 

- FormTest3.java (doGet, doPost, service 모두 사용한 예시)

package com.superman.www;

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 FormTest3
 */
@WebServlet("/FormTest3")
public class FormTest3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public FormTest3() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("service");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("post");
	}
}

 

ex) 서블릿의 특성을 설명하는 예시로 실제 사용하는 방식은 아님

- test.java

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>service 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

- test2.java (doGet 메소드 사용)

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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 Test2
 */
@WebServlet("/Test2")
public class Test2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test2() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>get 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

- test3.java (doPost 메소드 사용, 실행되지 않는 예시)

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/Test3")
public class Test3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test3() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>post 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

- test4.java (service 메소드 사용)

package com.superman.www;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/Test4")
public class Test4 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Test4() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>service 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>get 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>out Test</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>post 안녕하세요.</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

 

# 회원가입 실습 1

- main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id");
	if(id==null)
	{
%>
		<form action="LoginOK" method="post">
			아이디 : <input type="text" name="id"><br />
			비밀번호 : <input type="password" name="password"><br />
			<input type="submit" value="로그인"> <a href="memberRegister.htm">회원가입</a><br>
		</form>
<% 
	}
	else
	{
%>
	<%=id %>님 환영합니다<br>
	<a href="Logout">로그아웃</a> <a href="memberModify.jsp">개인정보수정</a>
<%
	}
%>
</body>
</html>

- memberRegister.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>회원가입</h2>
<form name="member" method="post" action="MemberRegisterOK" onsubmit="return validateForm()">
<table>
<tr>
	<td>이름 </td>
    <td><input type="text" name="name" required></td>
</tr>
<tr>
	<td>아이디 </td>
    <td><input type="text" name="id" required></td>
</tr>
<tr>
	<td>비밀번호 </td>
    <td><input type="password" name="password" required></td>
</tr>
<tr>
	<td>비밀번호확인 </td>
    <td><input type="password" name="passwordChk" required></td>
</tr>
<tr>
	<td>성별 </td>
    <td>
    	<input type="radio" name="sex" value="male" checked>남 
    	<input type="radio" name="sex" value="female">여
    </td>
</tr>
<tr>
	<td>이메일</td>
    <td><input type="email" name="email" required></td>
</tr>
<tr>
	<td>취미</td>
	<td>
		<input type="checkbox" name="hobby" value="수영">수영 
		<input type="checkbox" name="hobby" value="야구">야구 
		<input type="checkbox" name="hobby" value="영화감상">영화감상 
		<input type="checkbox" name="hobby" value="음악감상">음악감상 
	</td>
</tr>
<tr>
	<td>핸드폰</td>
	<td><select name="mobilePhone1">
			<option value="010">010</option>
			<option value="011">011</option>
			<option value="016">016</option>
		</select>
		<input type="text" name="mobilePhone2" required>	
	</td>
</tr>
<tr>
	<td colspan="2">
    	<input type="submit" value="회원가입"> 
        <input type="reset" value="초기화">
    </td>
</tr>
</table>
</form>
<script>
function validateForm() {
    var password = document.forms["member"]["password"].value;
    var passwordChk = document.forms["member"]["passwordChk"].value;
    if(password != passwordChk){
        alert("비밀번호와 비밀번호확인이 서로 다릅니다.");
        return false;
    }
}
</script>
</body>
</html>

- memberRegisterOK.java

package com.superman.ex;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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;

@WebServlet("/MemberRegisterOK")
public class MemberRegisterOK extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String driver = "com.mysql.jdbc.Driver";
	private String mysqlUrl = "jdbc:mysql://localhost/project?useSSL=false&serverTimezone=UTC";	// mysql 기본포트 3306 생략가능
	private String mysqlUser = "root";
	private String mysqlPassword = "1234";
       
    public MemberRegisterOK() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Connection conn = null;
		PreparedStatement pstmt = null;
		int result = 0;
		String mobilePhone = null, hobby = "";
		String[] temp = null;
		String sql = 
				"INSERT INTO MEMBER (NAME, ID, PASSWORD, SEX, EMAIL, MOBILEPHONE, HOBBY) VALUES(?, ?, ?, ?, ?, ?, ?)";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, request.getParameter("name"));
			pstmt.setString(2, request.getParameter("id"));
			pstmt.setString(3, request.getParameter("password"));
			pstmt.setString(4, request.getParameter("sex"));
			pstmt.setString(5, request.getParameter("email"));
			mobilePhone = request.getParameter("mobilePhone1") + request.getParameter("mobilePhone2");
			pstmt.setString(6, mobilePhone);
			temp = request.getParameterValues("hobby"); //getParameterValues 사용 시 String 배열로 값을 가지고 옴
			for(int i=0;i<temp.length;i++) // hobby를 여러 개 체크한 경우를 위해 temp.length 사용
				hobby += temp[i] + " "; // 결과 ex)수영 야구  
			pstmt.setString(7, hobby);
			result = pstmt.executeUpdate(); // 쿼리 실행, executeUpdate는 insert, delete, update 시 사용하는 것으로 반환형은 resultSet임 
			if(result >= 1) response.sendRedirect("main.jsp");
			else 
			{
				request.setAttribute("errMSG", "데이터베이스 입력실패"); // errMSG = 에러메시지
				request.setAttribute("url", "error.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

-error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script>
	alert('<%=request.getAttribute("errMSG")%>');
	location.href = '<%=request.getAttribute("url")%>';
</script>
</head>
<body>
</body>
</html>

 

# 회원가입 실습 2

- main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id");
	if(id==null)
	{
%>
		<form action="LoginOK" method="post">
			아이디 : <input type="text" name="id"><br />
			비밀번호 : <input type="password" name="password"><br />
			<input type="submit" value="로그인"> <a href="memberRegister.htm">회원가입</a><br>
		</form>
<% 
	}
	else
	{
%>
	<%=id %>님 환영합니다<br>
	<a href="Logout">로그아웃</a> <a href="memberModify.jsp">개인정보수정</a>
<%
	}
%>
</body>
</html>

- memberRegister.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>회원가입</h2>
<form name="member" method="post" action="MemberRegisterOK" onsubmit="return validateForm()">
<table>
<tr>
	<td>이름 </td><td><input type="text" name="name" required></td>
</tr>
<tr>
	<td>아이디 </td><td><input type="text" name="id" required></td>
</tr>
<tr>
	<td>비밀번호 </td><td><input type="password" name="password" required></td>
</tr>
<tr>
	<td>비밀번호확인 </td><td><input type="password" name="passwordChk" required></td>
</tr>
<tr>
	<td>성별 </td><td><input type="radio" name="sex" value="male" checked>남 <input type="radio" name="sex" value="female">여</td>
</tr>
<tr>
	<td>이메일</td><td><input type="email" name="email" required></td>
</tr>
<tr>
	<td>취미</td>
	<td>
		<input type="checkbox" name="hobby" value="수영">수영 
		<input type="checkbox" name="hobby" value="야구">야구 
		<input type="checkbox" name="hobby" value="영화감상">영화감상 
		<input type="checkbox" name="hobby" value="음악감상">음악감상 
	</td>
</tr>
<tr>
	<td>핸드폰</td>
	<td><select name="mobilePhone1">
			<option value="010">010</option>
			<option value="011">011</option>
			<option value="016">016</option>
		</select>
		<input type="text" name="mobilePhone2" required>	
	</td>
</tr>
<tr>
	<td colspan="2"><input type="submit" value="회원가입"> <input type="reset" value="초기화"></td>
</tr>
</table>
</form>
<script>
function validateForm() {
    var password = document.forms["member"]["password"].value;
    var passwordChk = document.forms["member"]["passwordChk"].value;
    if(password != passwordChk){
        alert("비밀번호와 비밀번호확인이 서로 다릅니다.");
        return false;
    }
}
</script>
</body>
</html>

- memberModify.jsp

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String driver = "com.mysql.cj.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/project?useSSL=false&serverTimezone=UTC";
	String user = "root";
	String password = "1234";
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String name=null, id=null, sex=null, email=null, hobby=null, mobilePhone=null;
	
	try{
		Class.forName(driver);
		conn = DriverManager.getConnection(url, user, password);
		pstmt = conn.prepareStatement("SELECT * FROM MEMBER WHERE ID=?");
		pstmt.setString(1, (String)session.getAttribute("id") );
		rs = pstmt.executeQuery();
		
		if(rs.next()){
			name = rs.getString("name");
			id = rs.getString("id");
			sex = rs.getString("sex");
			email = rs.getString("email");
			hobby = rs.getString("hobby");
			mobilePhone = rs.getString("mobilePhone");
		}		
	} catch(ClassNotFoundException e){
		e.printStackTrace();
	} catch(SQLException e){
		e.printStackTrace();
	} finally{
		try{
			if(rs != null) rs.close();
			if(pstmt != null) pstmt.close();
			if(conn != null) conn.close();			
		} catch(SQLException e){
			e.printStackTrace();
		}
	}	
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<h2>회원정보수정</h2>
<form name="member" method="post" action="MemberModifyOK" onsubmit="return validateForm()">
<table>
<tr>
	<td>이름 </td><td><input type="text" name="name" value="<%=name %>" disabled></td>
</tr>
<tr>
	<td>아이디 </td><td><input type="text" name="id" value="<%=id %>"  readonly></td>
</tr>
<tr>
	<td>비밀번호 </td><td><input type="password" name="password" required></td>
</tr>
<tr>
	<td>비밀번호확인 </td><td><input type="password" name="passwordChk" required></td>
</tr>
<tr>
	<td>성별 </td>
	<td><input type="radio" name="sex" value="male" <%if(sex.equals("male")){ %>checked <%} %> >남 
		<input type="radio" name="sex" value="female" <%if(sex.equals("female")){ %>checked <%} %>>여
	</td>
</tr>
<tr>
	<td>이메일</td><td><input type="email" name="email" value="<%=email %>" required></td>
</tr>
<tr>
	<td>취미</td>
	<td>
		<input type="checkbox" name="hobby" value="수영" <%if(hobby.indexOf("수영")!=-1){ %>checked <%} %>>수영 
		<input type="checkbox" name="hobby" value="야구" <%if(hobby.indexOf("야구")!=-1){ %>checked <%} %>>야구 
		<input type="checkbox" name="hobby" value="영화감상" <%if(hobby.indexOf("영화감상")!=-1){ %>checked <%} %>>영화감상 
		<input type="checkbox" name="hobby" value="음악감상" <%if(hobby.indexOf("음악감상")!=-1){ %>checked <%} %>>음악감상 
	</td>
</tr>
<tr>
	<td>핸드폰</td>
	<td><select name="mobilePhone1">
			<option value="010" <%if( mobilePhone.substring(0,3).equals("010") ){ %> selected <%}%> >010</option>
			<option value="011" <%if( mobilePhone.substring(0,3).equals("011") ){ %> selected <%}%> >011</option>
			<option value="016" <%if( mobilePhone.substring(0,3).equals("016") ){ %> selected <%}%> >016</option>
		</select>
		<input type="text" name="mobilePhone2" value="<%=mobilePhone.substring(3) %>" required>	
	</td>
</tr>
<tr>
	<td colspan="2"><input type="submit" value="정보수정"> <input type="reset" value="초기화"></td>
</tr>
</table>
</form>
<script>
function validateForm() {
    var password = document.forms["member"]["password"].value;
    var passwordChk = document.forms["member"]["passwordChk"].value;
    if(password != passwordChk){
        alert("비밀번호와 비밀번호확인이 서로 다릅니다.");
        return false;
    }
}
</script>
</body>
</html>

- error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script>
	alert('<%=request.getAttribute("errMSG")%>');
	location.href = '<%=request.getAttribute("url")%>';
</script>
</head>
<body>
</body>
</html>

- LoginOK.java

package com.superman.ex;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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 javax.servlet.http.HttpSession;

@WebServlet("/LoginOK")
public class LoginOK extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public LoginOK() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String driver = "com.mysql.cj.jdbc.Driver";
		String mysqlUrl = "jdbc:mysql://localhost:3306/project?useSSL=false&serverTimezone=UTC";
		String mysqlUser = "root";
		String mysqlPassword = "1234";
		Connection conn = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String id = request.getParameter("id");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		
		try{
			Class.forName(driver); // 드라이버 로드
			conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
			pstmt = conn.prepareStatement("SELECT ID, PASSWORD FROM MEMBER WHERE ID=? AND PASSWORD=?");
			pstmt.setString(1,  id);
			pstmt.setString(2,  password);
			rs = pstmt.executeQuery();
			if(rs.next()){
				session.setAttribute("id", id);
				response.sendRedirect("main.jsp");
			} else{
				request.setAttribute("errMSG", "유효하지 않은 아이디와 비밀번호 입니다.");
				request.setAttribute("url", "main.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);				
			}
		} catch(ClassNotFoundException e){
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();				
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}
}

- Logout.java

package com.superman.ex;

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;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Logout
 */
@WebServlet("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Logout() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.invalidate();
		response.sendRedirect("main.jsp");
	}

}

- MemberRegisterOK.java

package com.superman.ex;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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;

@WebServlet("/MemberRegisterOK")
public class MemberRegisterOK extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String driver = "com.mysql.cj.jdbc.Driver";
	private String mysqlUrl = "jdbc:mysql://localhost/project?useSSL=false&serverTimezone=UTC";	// mysql 기본포트 3306 생략가능
	private String mysqlUser = "root";
	private String mysqlPassword = "1234";
       
    public MemberRegisterOK() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Connection conn = null;
		PreparedStatement pstmt = null;
		int result = 0;
		String mobilePhone = null, hobby = "";
		String[] temp = null;
		String sql = 
				"INSERT INTO MEMBER (NAME, ID, PASSWORD, SEX, EMAIL, MOBILEPHONE, HOBBY) VALUES(?, ?, ?, ?, ?, ?, ?)";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, request.getParameter("name"));
			pstmt.setString(2, request.getParameter("id"));
			pstmt.setString(3, request.getParameter("password"));
			pstmt.setString(4, request.getParameter("sex"));
			pstmt.setString(5, request.getParameter("email"));
			mobilePhone = request.getParameter("mobilePhone1") + request.getParameter("mobilePhone2");
			pstmt.setString(6, mobilePhone);
			temp = request.getParameterValues("hobby");
			for(int i=0;i<temp.length;i++)
				hobby += temp[i] + " ";
			pstmt.setString(7, hobby);
			result = pstmt.executeUpdate();
			if(result >= 1) response.sendRedirect("main.jsp");
			else 
			{
				request.setAttribute("errMSG", "데이터베이스 입력실패");
				request.setAttribute("url", "main.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try{
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();			
			} catch(SQLException e){
				e.printStackTrace();
			}			
		}
	}
}

- MemberModifyOK.java

package com.superman.ex;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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;

@WebServlet("/MemberModifyOK")
public class MemberModifyOK extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public MemberModifyOK() {
		super();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = null, password = null, sex = null, email = null, hobby = "", mobilePhone = null;
		String[] tmp = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		String driver = "com.mysql.cj.jdbc.Driver";
		String mysqlUrl = "jdbc:mysql://localhost:3306/project?useSSL=false&serverTimezone=UTC";
		String mysqlUser = "root";
		String mysqlPassword = "1234";
		int result = 0;
		request.setCharacterEncoding("UTF-8");

		id = request.getParameter("id");
		password = request.getParameter("password");
		sex = request.getParameter("sex");
		email = request.getParameter("email");
		tmp = request.getParameterValues("hobby");
		for(int i=0;i<tmp.length;i++)
			hobby += tmp[i]+" ";
		mobilePhone = request.getParameter("mobilePhone1") + request.getParameter("mobilePhone2");
		System.out.println(id + " " + password + " " + sex + " " + email + " " + mobilePhone);

		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
			pstmt = conn.prepareStatement("UPDATE MEMBER SET PASSWORD=?, SEX=?, EMAIL=?, HOBBY=?, MOBILEPHONE=? WHERE id=?");
			pstmt.setString(1, password);
			pstmt.setString(2, sex);
			pstmt.setString(3, email);
			pstmt.setString(4, hobby);
			pstmt.setString(5, mobilePhone);
			pstmt.setString(6, id);
			result = pstmt.executeUpdate();
			if(pstmt != null) pstmt.close();
			if(conn != null) conn.close();
			if(result > 0) response.sendRedirect("main.jsp");
			else 
			{
				request.setAttribute("errMSG", "데이터베이스 수정실패");
				request.setAttribute("url", "main.jsp");
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try{
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();			
			} catch(SQLException e){
				e.printStackTrace();
			}			
		}
	}
}

 

728x90