package member.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 RegisterMemberServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection = null;
private PreparedStatement preparedStatement = null;
public RegisterMemberServlet1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.요청파라미터 조회
//2. Business Logic 처리
//1. Connection
//2. PreparedStatement
//3. SQL 문 전송(insert)
//4. close
//3. 응답처리
// 클라이언트로 받은 가입정보를 출력한뒤 가입처리 성공 메세지 응답.
//1.요청 파라미터 조회
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String password = request.getParameter("pwd");
String name = request.getParameter("name");
String registerNo1 = request.getParameter("register_no1");
String registerNo2 = request.getParameter("register_no2");
String registerNo = registerNo1+registerNo2;
int mileage = 1000;
response.setContentType("text/html;charset=utf-8");
//Business Logic 처리
ServletContext ctx = getServletContext();
String url = ctx.getInitParameter("url");
String user = ctx.getInitParameter("user");
String dbPwd = ctx.getInitParameter("password");
String resUrl = null;
try {
connection = DriverManager.getConnection(url, user, dbPwd);
String sql = "insert into member values(?,?,?,?,?)";
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+"개의 행이 삽입되었습니다.");
//1. Business Logic처리
//2. 조회한 정보 request scope에 binding
MemberDTO memberDTO = new MemberDTO(id,password,name,registerNo,mileage);
//3. member_list.jsp로 수행이동
request.setAttribute("memberDTO", 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();
}
}
}
RequestDispatcher rdp = request.getRequestDispatcher(resUrl);
rdp.forward(request, response);
}
}
<!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>
<form action="/member_servlet/RegisterMemberServlet1" method="post">
<table border="1">
<tr>
<td align="center">id</td><td><input type="text" name="id" maxlength="10" size="10"></td>
</tr>
<tr>
<td align="center">pwd</td><td><input type="password" name="pwd" maxlength="4" size="4"></td>
</tr>
<tr>
<td align="center">이름 : </td><td><input type="text" name="name" maxlength="10" size="10"></td>
</tr>
<tr>
<td align="center">주민번호 : </td>
<td>
<input type="text" name="register_no1" maxlength="6" size="6">-
<input type="text" name="register_no2" maxlength="7" size="7">
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="가입">
<input type="reset" value="다시작성"></td>
</tr>
</table>
</form>
</body>
</html>
WebContent
folder : 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>
<%
String errMessage = (String)request.getAttribute("error_message");
%>
실행 도중 오류가 발생했습니다.<br>
오류 내용<%=errMessage %>
<a href='/member_servlet/index.html'>메인페이지로 이동</a>
</body>
</html>
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>
<body>
<%
MemberDTO memberDTO = (MemberDTO)request.getAttribute("memberDTO");
%>
<h2>가입 환영합니다.</h2>
<h3>가입 시 입력한 정보입니다. </h3>
ID : <%=memberDTO.getId() %>
Password : <%=memberDTO.getPassword() %>
이름 : <%=memberDTO.getName() %>
주민번호 : <%=memberDTO.getRegisterNumber().substring(0,6) %>-<%=memberDTO.getRegisterNumber().substring(6) %>
마일리지 : <%=memberDTO.getMileage() %><p>
<a href="/member_servlet/login_form.jsp">로그인</a>
<a href="/member_servlet/index.html">메인페이지</a>
</body>
</html>
package member.dto;
public class MemberDTO {
private String id;
private String password;
private String name;
private String registerNumber;
private int mileage;
public MemberDTO() {
super();
}
public MemberDTO(String id, String password, String name,
String registerNumber, int mileage) {
super();
this.id = id;
this.password = password;
this.name = name;
this.registerNumber = registerNumber;
this.mileage = mileage;
}
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegisterNumber() {
return registerNumber;
}
public void setRegisterNumber(String registerNumber) {
this.registerNumber = registerNumber;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
@Override
public String toString() {
return "MemberDTO [id=" + id + ", password=" + password + ", name="
+ name + ", registerNumber=" + registerNumber + ", mileage="
+ mileage + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + mileage;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
result = prime * result
+ ((registerNumber == null) ? 0 : registerNumber.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MemberDTO other = (MemberDTO) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (mileage != other.mileage)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (registerNumber == null) {
if (other.registerNumber != null)
return false;
} else if (!registerNumber.equals(other.registerNumber))
return false;
return true;
}
}
package member.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DriverLoadingListener implements ServletContextListener {
public DriverLoadingListener() {
}
public void contextInitialized(ServletContextEvent arg0) {
//web.xml에 있는 Context읽어오기(초기 파라미터)
ServletContext ctx = arg0.getServletContext();
//web.xml에 있는 driver class 읽어오기
String driverClass = ctx.getInitParameter("driver class");
try {
//어플리케이션이 시작할 때 driver class 로딩
Class.forName(driverClass);
System.out.println("-----Driver Loading 성공------");
} catch (Exception e) {
}
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
* request scope : 데이터가 사용하고 나면 더이상 필요 없어 질 경우에 리퀘스트 스코프를 활용하여 jsp쪽으로 값만 넘겨주고 데이터는 사라지도록 한다.
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-1 jsp를 이용한 회원등록하기 & 로그인, 로그아웃하기(session활용) (0) | 2012.05.02 |
---|---|
2012-4-30 로그인 & 로그아웃하기 (0) | 2012.04.30 |
2012-4-30 servlet을 이용한 회원가입하기 (0) | 2012.04.30 |
2012-4-27 eclipse와 DB연결해서 Driver Loading 시키기[실습] (0) | 2012.04.27 |
eclipse에서 DB연동하기 (0) | 2012.04.27 |