1. 메인 페이지 index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/login/register_form.html">회원등록하기</a>
<a href="/login/login_form.jsp">로그인하기</a>
</body>
</html>
* 회원등록하기를 누르면 register_form.html로 이동하고 로그인하기를 누르면 login_form.jsp로 이동하여 로그인을 한다.
2. register_form.html 만들기
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>회원등록</title>
</head>
<body>
<h2>회원등록하기</h2><p>
<form action="/login/register_servlet" method="post">
<table border="1">
<tr>
<td align="center">아이디</td><td><input type="text" name="id" size="10" maxlength="10"></td>
</tr>
<tr>
<td align="center">패스워드</td><td><input type="password" name="password" size="4" maxlength="4"></td>
</tr>
<tr>
<td align="center">이름</td><td><input type="text" name="name" size="10" maxlength="10"></td>
</tr>
<tr>
<td align="center">주민번호</td><td><input type="text" name="registerNo1" size="6" maxlength="6">-<input type="text" name="registerNo2" size="7" maxlength="7"></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="회원등록"><input type="reset" value="초기화"></td>
</tr>
</table>
</form>
</body>
</html>
* 위의 값들을 입력하고 회원등록을 클릭하면 RegisterMemberServlet으로 이동
package member.servlet;
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.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.dto.MemberDTO;
public class RegisterMemberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterMemberServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 파라미터 값 받아오기
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String password = request.getParameter("password");
String name = request.getParameter("name");
String registerNo1 = request.getParameter("registerNo1");
String registerNo2 = request.getParameter("registerNo2");
String registerNo = registerNo1+registerNo2;
int mileage = 1000;
response.setContentType("text/html;utf-8");
//2. db연결하기
ServletContext servletContext = getServletContext();
String url = servletContext.getInitParameter("url");
String user = servletContext.getInitParameter("user");
String dbPwd = servletContext.getInitParameter("password");
String sql = "insert into member values(?,?,?,?,?)";
Connection connection = null;
PreparedStatement preparedStatement = null;
String resUrl = null;
try {
connection = DriverManager.getConnection(url, user, dbPwd);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, id);
preparedStatement.setString(2, password);
preparedStatement.setString(3, name);
preparedStatement.setString(4, registerNo);
preparedStatement.setInt(5, mileage);
int cnt = preparedStatement.executeUpdate();
System.out.println(cnt+"개의 행이 삽입되었습니다. ");
//3. 디비로 삽입한 값을 request scope를 이용하여 register_success로 옮기기
MemberDTO memberDTO = new MemberDTO(id, password, name, registerNo, mileage);
request.setAttribute("member_info", memberDTO);
resUrl = "/res/register_success.jsp";
} catch (SQLException e) {
request.setAttribute("error_message", e.getMessage());
resUrl = "/res/error.jsp";
} finally{
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// request scope방식으로 화면 전환하기
RequestDispatcher requestDispatcher = request.getRequestDispatcher(resUrl);
requestDispatcher.forward(request, response);
}
}
* 정상적으로 회원가입이 되면 /res/register_success.jsp로 이동을 하여 아래와 같은 화면을 뿌려주고
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%
MemberDTO memberDTO = (MemberDTO)request.getAttribute("member_info");
%>
<body>
<h2>회원가입을 축하드입니다.</h2><p>
아이디 : <%=memberDTO.getId() %><br>
이름 : <%=memberDTO.getName() %><br>
주민번호 : <%=memberDTO.getRegisterNumber() %><br>
마일리지 : <%=memberDTO.getMileage() %><br>
<a href = "/login/login_form.jsp">로그인</a>
<a href = "/login/index.html">처음으로 이동</a>
</body>
</html>
* 기존에 있는 아이디를 입력하게 되면 아래와 같이 에러 문구와 함께 화면을 보여주게 됩니다. /res/error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
실행도중 에러가 발생하였습니다. <p>
<%String error_message = (String)request.getAttribute("error_message"); %>
<%= error_message%><br>
<a href="/login/index.html">메인페이지로 이동</a>
</body>
</html>
3. login하기 login_form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%
String error_message = (String)request.getAttribute("error_message");
if(error_message!=null){
%>
<font color="red" size="2"><%=error_message %></font>
<%} %>
<body>
<h2>로그인</h2><p>
<form action="/login/login_servlet" method="post">
<table border="1">
<tr>
<td>아이디</td><td><input type="text" name="id"></td>
</tr>
<tr>
<td>비밀번호</td><td><input type="password" name="password"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="로그인"><input type="reset" value="초기화"></td>
</tr>
</table>
</form>
</body>
</html>
* 로그인을 누르게 되면 LoginServlet으로 이동하여 아이디와 패스워드를 검사한다.
package member.servlet;
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.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.MemberDTO;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 파라미터 값 받아오기
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String password = request.getParameter("password");
//2.초기 파라미터 값 받아와서 DB와 연결
response.setContentType("text/html;utf-8");
ServletContext servletContext = getServletContext();
String url = servletContext.getInitParameter("url");
String user = servletContext.getInitParameter("user");
String dbPwd = servletContext.getInitParameter("password");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "select id ,password, name, registerNumber, mileage from member where id=?";
String resUrl = null;
try {
connection = DriverManager.getConnection(url, user, dbPwd);
preparedStatement = connection.prepareStatement(sql);
//3. DB에서 값 조회
preparedStatement.setString(1, id);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
//아이디가 맞고 비밀번호도 맞다면
if(resultSet.getString(2).equals(password)){
HttpSession httpSession = request.getSession();
MemberDTO memberDTO = new MemberDTO(id, password, resultSet.getString(3), resultSet.getString(4), resultSet.getInt(5));
httpSession.setAttribute("member_info", memberDTO);
response.sendRedirect("/login/res/login_success.jsp");
}else{
request.setAttribute("error_message", "비밀번호가 틀립니다. 비밀번호를 확인하세요");
resUrl = "/login_form.jsp";
}
}else{
request.setAttribute("error_message", id+"는 없는 아이디 입니다. 아이디를 확인하세요");
resUrl = "/login_form.jsp";
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
if(resUrl!=null){
RequestDispatcher requestDispatcher = request.getRequestDispatcher(resUrl);
requestDispatcher.forward(request, response);
}
}
}
* 로그인 성공 /res/login_succes.jsp 로 이동 아래와 같은 화면을 뿌려준다.
<%@page import="member.dto.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%
MemberDTO memberDTO = (MemberDTO)session.getAttribute("member_info");
%>
<body>
<h2><%=memberDTO.getId() %>님이 로그인 되었습니다.</h2><p>
<a href ="/login/index.html">메인페이지</a><br>
<a href ="/login/logoutServlet">logout</a>
</body>
</html>
* 로그인 실패 하면 /login_form.jsp로 이동 하여 아래와 같은 두 화면을 보여준다. (아이디가 틀릴 시, 비밀번호가 틀릴 시)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<%
String error_message = (String)request.getAttribute("error_message");
if(error_message!=null){
%>
<font color="red" size="2"><%=error_message %></font>
<%} %>
<body>
<h2>로그인</h2><p>
<form action="/login/login_servlet" method="post">
<table border="1">
<tr>
<td>아이디</td><td><input type="text" name="id"></td>
</tr>
<tr>
<td>비밀번호</td><td><input type="password" name="password"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="로그인"><input type="reset" value="초기화"></td>
</tr>
</table>
</form>
</body>
</html>
4. logout하기( logout을 클릭하면 logoutServlet으로 이동하여 로그아웃 처리를 한다. )
(로그인이 되어 있다면 로그아웃처리를 하고 그렇지 않다면 로그인 먼저 해달라는 메세지를 띄운다.)
package member.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import member.dto.MemberDTO;
public class logoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public logoutServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession httpSession = request.getSession();
String resUrl = null;
MemberDTO memberDTO = (MemberDTO) httpSession.getAttribute("member_info");
if(memberDTO==null){
request.setAttribute("error_message", "로그인 먼저해주세요.");
resUrl = "/login_form.jsp";
}else{
httpSession.invalidate();
resUrl = "/login_form.jsp";
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher(resUrl);
requestDispatcher.forward(request, response);
}
}
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-2 jsp를 활용한 회원정보 수정하기 (0) | 2012.05.02 |
---|---|
2012-5-2 로그인한 회원정보 조회하기 (0) | 2012.05.02 |
2012-4-30 로그인 & 로그아웃하기 (0) | 2012.04.30 |
2012-4-30 jsp를 활용한 회원등록하기 (0) | 2012.04.30 |
2012-4-30 servlet을 이용한 회원가입하기 (0) | 2012.04.30 |