728x90
728x90
회원가입 및 로그인 구현 작업 순서
1. 테이블 생성
2. 우편번호 입력
3. 빈즈 생성 : MemberaBean.java(hobby는 배열로 선언), ZipcodeBean.java
라이브러리
데이터
table.sql
Mysql과 HeidiSQL 프로그램을 이용해서 테이블을 만들고 데이터를 입력한다.
DROP TABLE IF EXISTS tblMember;
CREATE TABLE `tblMember` (
`id` char(20) NOT NULL,
`pwd` char(20) NOT NULL,
`name` char(20) NOT NULL,
`gender` char(1) NOT NULL,
`birthday` char(6) NOT NULL,
`email` char(30) NOT NULL,
`zipcode` char(5) NOT NULL,
`address` char(50) NOT NULL,
`hobby` char(5) NOT NULL,
`job` char(20) NOT NULL,
PRIMARY KEY (`id`)
)COLLATE='euckr_korean_ci';
DROP TABLE IF EXISTS tblZipcode;
CREATE TABLE `tblZipcode` (
`zipcode` char(5) NOT NULL,
`area1` char(10) DEFAULT NULL,
`area2` char(20) DEFAULT NULL,
`area3` char(30) DEFAULT NULL
)COLLATE='euckr_korean_ci';
주소검색기능을 테스트하기 위해 서울시의 우편번호 데이터만 가져온 파일
myapp > WebContent > WEB-INF > lib 위치에 넣어야 할 jar 파일
CSS, Javascript 파일
style.css
BODY {
FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TD {
FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
SELECT {
FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
DIV {
FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
FORM {
FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TEXTAREA {
BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999 ; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; BACKGROUND-COLOR: white
}
INPUT {
BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; HEIGHT: 19px; BACKGROUND-COLOR: white
}
A:link {text-decoration:none;color:#696969}
A:hover{text-decoration:yes;color:#66CCFF}
A:visited {text-decoration:none;color:#330066}
script.js
function inputCheck(){
if(document.regFrm.id.value==""){
alert("아이디를 입력해 주세요.");
document.regFrm.id.focus();
return;
}
if(document.regFrm.pwd.value==""){
alert("비밀번호를 입력해 주세요.");
document.regFrm.pwd.focus();
return;
}
if(document.regFrm.repwd.value==""){
alert("비밀번호를 확인해 주세요");
document.regFrm.repwd.focus();
return;
}
if(document.regFrm.pwd.value != document.regFrm.repwd.value){
alert("비밀번호가 일치하지 않습니다.");
document.regFrm.repwd.value="";
document.regFrm.repwd.focus();
return;
}
if(document.regFrm.name.value==""){
alert("이름을 입력해 주세요.");
document.regFrm.name.focus();
return;
}
if(document.regFrm.birthday.value==""){
alert("생년월일을 입력해 주세요.");
document.regFrm.birthday.focus();
return;
}
if(document.regFrm.email.value==""){
alert("이메일을 입력해 주세요.");
document.regFrm.email.focus();
return;
}
var str=document.regFrm.email.value;
var atPos = str.indexOf('@');
var atLastPos = str.lastIndexOf('@');
var dotPos = str.indexOf('.');
var spacePos = str.indexOf(' ');
var commaPos = str.indexOf(',');
var eMailSize = str.length;
if (atPos > 1 && atPos == atLastPos &&
dotPos > 3 && spacePos == -1 && commaPos == -1
&& atPos + 1 < dotPos && dotPos + 1 < eMailSize);
else {
alert('E-mail주소 형식이 잘못되었습니다.\n\r다시 입력해 주세요!');
document.regFrm.email.focus();
return;
}
if(document.regFrm.zipcode.value==""){
alert("우편번호를 검색해 주세요.");
return;
}
if(document.regFrm.job.value=="0"){
alert("직업을 선택해 주세요.");
document.regFrm.job.focus();
return;
}
document.regFrm.submit();
}
function win_close(){
self.close();
}
Java 파일들
* member 패키지에 MemberBean.java, ZipcodeBean.java 그리고 MemberBean.java 순으로 클래스를 만든다.
MemberBean.Java
package member;
public class MemberBean {
private String id;
private String pwd;
private String name;
private String gender;
private String birthday;
private String email;
private String zipcode;
private String address;
private String hobby[];
private String job;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
ZipcodeBean.java
package member;
public class ZipcodeBean {
private String zipcode;
private String area1;
private String area2;
private String area3;
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getArea1() {
return area1;
}
public void setArea1(String area1) {
this.area1 = area1;
}
public String getArea2() {
return area2;
}
public void setArea2(String area2) {
this.area2 = area2;
}
public String getArea3() {
return area3;
}
public void setArea3(String area3) {
this.area3 = area3;
}
}
다음 나올 파일 MemberMgr.Java에서 import받은
DBConnectionMgr.java 파일
package ch07;
import java.sql.*;
import java.util.Properties;
import java.util.Vector;
public class DBConnectionMgr {
private Vector connections = new Vector(10);
private String _driver = "org.gjt.mm.mysql.Driver",
_url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=EUC_KR",
_user = "root", //본인이 설정해 놓은 mysql의 ID
_password = "1234"; //본인이 설정해 놓은 mysql의 password
private boolean _traceOn = false;
private boolean initialized = false;
private int _openConnections = 50;
private static DBConnectionMgr instance = null;
public DBConnectionMgr() {
}
/** Use this method to set the maximum number of open connections before
unused connections are closed.
*/
public static DBConnectionMgr getInstance() {
if (instance == null) {
synchronized (DBConnectionMgr.class) {
if (instance == null) {
instance = new DBConnectionMgr();
}
}
}
return instance;
}
public void setOpenConnectionCount(int count) {
_openConnections = count;
}
public void setEnableTrace(boolean enable) {
_traceOn = enable;
}
/** Returns a Vector of java.sql.Connection objects */
public Vector getConnectionList() {
return connections;
}
/** Opens specified "count" of connections and adds them to the existing pool */
public synchronized void setInitOpenConnections(int count)
throws SQLException {
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < count; i++) {
c = createConnection();
co = new ConnectionObject(c, false);
connections.addElement(co);
trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
}
}
/** Returns a count of open connections */
public int getConnectionCount() {
return connections.size();
}
/** Returns an unused existing or new connection. */
public synchronized Connection getConnection()
throws Exception {
if (!initialized) {
Class c = Class.forName(_driver);
DriverManager.registerDriver((Driver) c.newInstance());
initialized = true;
}
Connection c = null;
ConnectionObject co = null;
boolean badConnection = false;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
// If connection is not in use, test to ensure it's still valid!
if (!co.inUse) {
try {
badConnection = co.connection.isClosed();
if (!badConnection)
badConnection = (co.connection.getWarnings() != null);
} catch (Exception e) {
badConnection = true;
e.printStackTrace();
}
// Connection is bad, remove from pool
if (badConnection) {
connections.removeElementAt(i);
trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
continue;
}
c = co.connection;
co.inUse = true;
trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
break;
}
}
if (c == null) {
c = createConnection();
co = new ConnectionObject(c, true);
connections.addElement(co);
trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
}
return c;
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void freeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (c == co.connection) {
co.inUse = false;
break;
}
}
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if ((i + 1) > _openConnections && !co.inUse)
removeConnection(co.connection);
}
}
public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
try {
if (r != null) r.close();
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s, ResultSet r) {
try {
if (r != null) r.close();
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, PreparedStatement p) {
try {
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s) {
try {
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void removeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (c == co.connection) {
try {
c.close();
connections.removeElementAt(i);
trace("Removed " + c.toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
private Connection createConnection()
throws SQLException {
Connection con = null;
try {
if (_user == null)
_user = "";
if (_password == null)
_password = "";
Properties props = new Properties();
props.put("user", _user);
props.put("password", _password);
con = DriverManager.getConnection(_url, props);
} catch (Throwable t) {
throw new SQLException(t.getMessage());
}
return con;
}
/** Closes all connections and clears out the connection pool */
public void releaseFreeConnections() {
trace("ConnectionPoolManager.releaseFreeConnections()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
if (!co.inUse)
removeConnection(co.connection);
}
}
/** Closes all connections and clears out the connection pool */
public void finalize() {
trace("ConnectionPoolManager.finalize()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.elementAt(i);
try {
co.connection.close();
} catch (Exception e) {
e.printStackTrace();
}
co = null;
}
connections.removeAllElements();
}
private void trace(String s) {
if (_traceOn)
System.err.println(s);
}
}
class ConnectionObject {
public java.sql.Connection connection = null;
public boolean inUse = false;
public ConnectionObject(Connection c, boolean useFlag) {
connection = c;
inUse = useFlag;
}
}
MemberMgr.Java
package member;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import ch07.DBConnectionMgr;
public class MemberMgr {
private DBConnectionMgr pool;
public MemberMgr() {
pool= DBConnectionMgr.getInstance();
}
//ID중복확인 - true 중복 (존재)
public boolean checkId(String id) {
Connection con = null; //java.sql import
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
boolean flag = false; //초기화
try {
con = pool.getConnection();
sql = "select id from tblMember where id=?"; //아이티 포커스
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
flag = rs.next();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return flag; //id중복확인
}
//우편번호검색 (select)
//select * from tblZipcode where area3 like '%강 남 대 로%' (가운데 있는 것 : %)
public Vector<ZipcodeBean> zipcodeRead (String area3) { //도로명 부분
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
Vector<ZipcodeBean> vlist = new Vector<ZipcodeBean>(); // 벡터 선언
try {
con = pool.getConnection();
sql = " select * from tblZipcode where area3 like ? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "%"+area3+"%"); // %
rs = pstmt.executeQuery();
while(rs.next()) {
ZipcodeBean bean = new ZipcodeBean();
bean.setZipcode(rs.getString(1)); // 뒤에 숫자 주의
bean.setArea1(rs.getString(2));
bean.setArea2(rs.getString(3));
bean.setArea3(rs.getString(4));
vlist.addElement(bean); // 빠뜨리지 않도록 주의
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vlist;
}
//회원가입 : 배열로 들어오는 값 처리
public boolean insertMember(MemberBean bean) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
boolean flag = false;
try {
con = pool.getConnection();
sql = "insert tblMember(id,pwd,name,gender,birthday,email,zipcode,address,hobby,job)"
+ "values(?,?,?,?,?,?,?,?,?,?)" ;
pstmt = con.prepareStatement(sql);
///////////////////////////////////////////////////////////////////////
pstmt.setString(1, bean.getId());
pstmt.setString(2, bean.getPwd());
pstmt.setString(3, bean.getName());
pstmt.setString(4, bean.getGender());
pstmt.setString(5, bean.getBirthday());
pstmt.setString(6, bean.getEmail());
pstmt.setString(7, bean.getZipcode());
pstmt.setString(8, bean.getAddress());
////////////////////////////////////////////////////////////////////////
// {"인터넷", "여행", "영화"} : 순서대로 배열 0,1,2로 들어온다.
String hobby[] = bean.getHobby();
char hb[] = {'0','0','0','0','0'};
String lists[] = {"인터넷", "여행", "게임", "영화", "운동"};
// 배열2개 = 2중 for문
for (int i = 0; i < hobby.length; i++) { //for문 자동완성은 가장 근처의 변수로 만들어준다. 선택된 것(3)
for (int j = 0; j < lists.length; j++) { //5번
if(hobby[i].equals(lists[j])) {
hb[j]='1';
break;
}//if
}//for2
}//for1
pstmt.setString(9, new String(hb)); // "11010"이라는 문자열로 저장
////////////////////////////////////////////////////////////////////////
pstmt.setString(10, bean.getJob());
///////////////////////////////////////////////////////////////////////
// int cnt = pstmt.executeUpdate(); // insert: int형으로 execute됨. 입력성공 1 실패 0.
if(pstmt.executeUpdate()==1) flag=true;
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
//로그인
public boolean loginMember(String id, String pwd) { //한 개 이상 (프라이머리키가 있어서 t/f값으로 체크 가능하다.)
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
boolean flag = false;
try {
con = pool.getConnection();
sql = " select id from tblMember where id=? and pwd=? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id); //세팅. 순서중요
pstmt.setString(2, pwd);
rs = pstmt.executeQuery(); //실행
flag = rs.next(); //true면 로그인 성공. 없으면(false) 로그인 실패
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return flag;
}
//회원정보가져오기
public MemberBean getMember(String id) { //레코드 타입으로 가져옴
//id pk, db1
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
// 객체 불변의 법칙 : new로 만들어진 객체는 절대 타입이 변하지 않는다.
MemberBean bean = new MemberBean(); //bean : reference 변수
Object obj = bean;
try {
con = pool.getConnection();
sql = " select * from tblMember where id=? ";
// select * from 빈칸을 없애면 쿼리는 먹지만 구 자바에서는 인식을 못한다.
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
bean.setId(rs.getString("id"));
bean.setPwd(rs.getString("pwd"));
bean.setName(rs.getString("name"));
bean.setGender(rs.getString("gender"));
bean.setBirthday(rs.getString("birthday"));
bean.setEmail(rs.getString("email"));
bean.setZipcode(rs.getString("zipcode"));
bean.setAddress(rs.getString("address"));
//hobby => 10101 (table) ==> {"1","0","1","0","1"} 문자열배열로 변형해서 저장
String hobby = rs.getString("hobby");
String hobbys[] = new String[5];
//배열 아래는 for
for (int i = 0; i < hobbys.length; i++) {
hobbys[i] = hobby.substring(i, i+1); // 문자열을 배열로 만들어
}
bean.setHobby(hobbys);
bean.setJob(rs.getString("job"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return bean;
}
//회원정보수정 : 입력(회원가입)과 거의 비슷함.
public boolean updateMember(MemberBean bean) { //db2
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
boolean flag = false;
try {
con = pool.getConnection();
sql = "update tblMember set pwd=?, name=?, gender=?, birthday=?, email=?, zipcode=?, address=?, hobby=?, job=? where id=?";
pstmt = con.prepareStatement(sql);
///////////////////////////////////////////////////////////////////////
pstmt.setString(1, bean.getPwd());
pstmt.setString(2, bean.getName());
pstmt.setString(3, bean.getGender());
pstmt.setString(4, bean.getBirthday());
pstmt.setString(5, bean.getEmail());
pstmt.setString(6, bean.getZipcode());
pstmt.setString(7, bean.getAddress());
////////////////////////////////////////////////////////////////////////
// {"인터넷", "여행", "영화"} : 순서대로 배열 0,1,2로 들어온다.
String hobby[] = bean.getHobby();
char hb[] = {'0','0','0','0','0'};
String lists[] = {"인터넷", "여행", "게임", "영화", "운동"};
// 배열2개 = 2중 for문
for (int i = 0; i < hobby.length; i++) { //for문 자동완성은 가장 근처의 변수로 만들어준다. 선택된 것(3)
for (int j = 0; j < lists.length; j++) { //5번
if(hobby[i].equals(lists[j])) {
hb[j]='1';
break;
}//if
}//for2
}//for1
pstmt.setString(8, new String(hb)); // "11010"이라는 문자열로 저장
////////////////////////////////////////////////////////////////////////
pstmt.setString(9, bean.getJob());
pstmt.setString(10, bean.getId());
///////////////////////////////////////////////////////////////////////
// int cnt = pstmt.executeUpdate(); // insert: int형으로 execute됨. 입력성공 1 실패 0.
if(pstmt.executeUpdate()==1) flag=true;
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
}
Jsp 파일들
* Webcontent 폴더 안에 member 폴더에 만든다.
member.jsp
<%@ page contentType="text/html; charset=EUC-KR" %>
<html>
<head>
<title>회원가입</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function idCheck(id){
if(id==""){
alert("아이디를 입력하세요"); //null값은 서버에 부하걸리므로 가기전에 잡아준다
document.regFrm.id.focus();
return; // function를 벗어난다.
}
url = "idCheck.jsp?id="+id;
window.open(url, "IDCheck", "width=300, height=150");
}
function zipSearch(){
url = "zipSearch.jsp?search=n"; // n : 창만 띄우고 메소드는 호출하지 않는 것
window.open(url, "ZipcodeSearch", "width=500, height=300");
}
</script>
</head>
<body bgcolor="#FFFFCC" onLoad="regFrm.id.focus()"> <!-- 정적 -->
<div align="center">
<br /><br />
<form name="regFrm" method="post" action="memberProc.jsp">
<table cellpadding="5">
<tr>
<td bgcolor="#FFFFCC">
<table border="1" cellspacing="0" cellpadding="2" width="600">
<tr bgcolor="#996600">
<td colspan="3"><font color="#FFFFFF"><b>회원 가입</b></font></td>
</tr>
<tr>
<td width="20%">아이디</td>
<td width="50%">
<input name="id" size="15">
<input type="button" value="ID중복확인" onClick="idCheck(this.form.id.value)"><!-- 유동적 -->
</td>
<td width="30%">아이디를 적어 주세요.</td>
</tr>
<tr>
<td>패스워드</td>
<td><input type="password" name="pwd" size="15"></td>
<td>패스워드를 적어주세요.</td>
</tr>
<tr>
<td>패스워드 확인</td>
<td><input type="password" name="repwd" size="15"></td>
<td>패스워드를 확인합니다.</td>
</tr>
<tr>
<td>이름</td>
<td><input name="name" size="15">
</td>
<td>이름을 적어주세요.</td>
</tr>
<tr>
<td>성별</td>
<td>
남<input type="radio" name="gender" value="1" checked>
여<input type="radio" name="gender" value="2">
</td>
<td>성별을 선택 하세요.</td>
</tr>
<tr>
<td>생년월일</td>
<td><input name="birthday" size="6">
ex)830815</td>
<td>생년월일를 적어 주세요.</td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" size="30">
</td>
<td>이메일를 적어 주세요.</td>
</tr>
<tr>
<td>우편번호</td>
<td><input name="zipcode" size="5" readonly>
<input type="button" value="우편번호찾기" onClick="zipSearch()">
</td>
<td>우편번호를 검색하세요.</td>
</tr>
<tr>
<td>주소</td>
<td><input name="address" size="45"></td>
<td>주소를 적어 주세요.</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="영화"> 운동<input
type="checkbox" name="hobby" value="운동">
</td>
<td>취미를 선택 하세요.</td>
</tr>
<tr>
<td>직업</td>
<td><select name=job>
<option value="0" selected>선택하세요.
<option value="회사원">회사원
<option value="연구전문직">연구전문직
<option value="교수학생">교수학생
<option value="일반자영업">일반자영업
<option value="공무원">공무원
<option value="의료인">의료인
<option value="법조인">법조인
<option value="종교,언론,에술인">종교.언론/예술인
<option value="농,축,수산,광업인">농/축/수산/광업인
<option value="주부">주부
<option value="무직">무직
<option value="기타">기타
</select></td>
<td>직업을 선택 하세요.</td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="button" value="회원가입" onclick="inputCheck()">
<input type="reset" value="다시쓰기">
<input type="button" value="로그인" onClick="javascript:location.href='login.jsp'">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
arrayTest.jsp / arrayTest2.jsp
<!-- arrayTest.jsp -->
<%@page contentType="text/html; charset=EUC-KR" %>
<%
request.setCharacterEncoding("EUC-KR");
%>
<form action="arrayTest2.jsp">
취미 : 인터넷<input type="checkbox" name="hobby" value="인터넷">
여행<input type="checkbox" name="hobby" value="여행">
게임<input type="checkbox" name="hobby" value="게임">
영화<input type="checkbox" name="hobby" value="영화">
운동<input type="checkbox" name="hobby" value="운동">
<input type="submit">
</form>
<!-- arrayTest2.jsp -->
<%@page contentType="text/html; charset=EUC-KR" %>
<%
request.setCharacterEncoding("EUC-KR");
//arrayTest2.jsp?hobby=인터넷&hobby=여행
String hobby[] = request.getParameterValues("hobby");
//배열, 벡터 밑에는 무조건 for
for(int i=0; i<hobby.length; i++){
out.println(hobby[i]+" ");
}
%>
<form action="arrayTest2.jsp">
취미 : 인터넷<input type="checkbox" name="hobby" value="인터넷">
여행<input type="checkbox" name="hobby" value="여행">
게임<input type="checkbox" name="hobby" value="게임">
영화<input type="checkbox" name="hobby" value="영화">
운동<input type="checkbox" name="hobby" value="운동">
<input type="submit">
</form>
idCheck.jsp
<%@page contentType="text/html; charset=EUC-KR" %>
<jsp:useBean id="mgr" class="member.MemberMgr" />
<html>
<head>
<title>ID 중복체크</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
<div align="center">
<%
String id = request.getParameter("id");
boolean result = mgr.checkId(id);
%>
<b><%=id%></b>
<%
if(result) {
out.println("는 이미 존재하는 ID입니다.");
}else {
out.println("는 사용 가능한 ID입니다.");
}
%>
<br><br>
<a href="#" onclick="self.close()">닫기</a>
</div>
</body>
</html>
zipsearch.jsp
<%@page import="member.ZipcodeBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR" %>
<jsp:useBean id="mgr" class="member.MemberMgr" />
<%
request.setCharacterEncoding("EUC-KR");
String search = request.getParameter("search");
String area3 = null;
Vector<ZipcodeBean> vlist = null;
if(search.equals("y")){ // 검색버튼을 클릭시
area3 = request.getParameter("area3");
vlist = mgr.zipcodeRead(area3);
//out.print(vlist.size());
}
%>
<html>
<head>
<title>우편번호 검색</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function loadSearch() {
frm = document.zipFrm;
if(frm.area3.value==""){
alert("도로명을 입력하세요.");
return;
}
frm.action = "zipSearch.jsp";
frm.submit();
}
function sendAdd(zipcode, adds){
opener.document.regFrm.zipcode.value = zipcode;
opener.document.regFrm.address.value = adds;
self.close();
}
</script>
</head>
<body bgcolor="#FFFFCC">
<div align="center">
<br />
<form name="zipFrm" method="post">
<table>
<tr>
<td>
<br/>도로명 입력 : <input name="area3">
<input type="button" value="검색"
onclick="loadSearch()">
</td>
</tr>
<!-- 검색결과시작 -->
<%
if (search.equals("y")){
if(vlist.isEmpty()){
%>
<tr>
<td align="center"><br/>검색된 결과가 없습니다.</td>
</tr>
<%
}else{
%>
<tr>
<td align="center"><br/>
※ 검색 후 아래 우편번호를 클릭하면 자동으로 입력됩니다.
</td>
</tr>
<%
for(int i=0; i<vlist.size(); i++){
ZipcodeBean bean = vlist.get(i);
String rZipcode = bean.getZipcode();
String rArea1 = bean.getArea1();
String rArea2 = bean.getArea2();
String rArea3 = bean.getArea3();
String adds = rArea1 + " " + rArea2 + " " + rArea3 + " " ;
%>
<tr>
<td>
<a href="#" onclick="javascript:sendAdd('<%=rZipcode%>','<%=adds%>')">
<%=rZipcode+" "+adds%>
</a>
</td>
</tr>
<%
}//for
}
}
%>
<!-- 검색결과끝 -->
<tr>
<td align="center"><br/>
<a href="#" onClick="self.close()">닫기</a></td>
</tr>
</table>
<input type="hidden" name="search" value="y">
</form>
</div>
</body>
</html>
memberUpdate.jsp
<%@page import="member.MemberBean"%>
<%@ page contentType="text/html;charset=EUC-KR" %>
<jsp:useBean id="mgr" class="member.MemberMgr" />
<%
String id = (String) session.getAttribute("idKey");
MemberBean bean = mgr.getMember(id);
%>
<html>
<head>
<title>회원수정</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function zipCheck() {
url = "zipSearch.jsp?search=n";
window.open(url, "ZipCodeSearch","width=500,height=300,scrollbars=yes");
}
</script>
</head>
<body bgcolor="#FFFFCC" onLoad="regFrm.id.focus()">
<div align="center">
<br /> <br />
<form name="regFrm" method="post" action="memberUpdateProc.jsp">
<table align="center" cellpadding="5" >
<tr>
<td align="center" valign="middle" bgcolor="#FFFFCC">
<table border="1" cellpadding="2" align="center" width="600">
<tr align="center" bgcolor="#996600">
<td colspan="3"><font color="#FFFFFF"><b>회원 수정</b></font></td>
</tr>
<tr>
<td width="20%">아이디</td>
<td width="80%"><input name="id" size="15"
value="<%=bean.getId()%>" readonly></td>
<!-- readonly : 수정대상이 아님
******************차이 다시 정리
varchar :
char :
where절에 들어오는 것은 pk, 인덱스가 되기 때문에 퍼포먼스가 좋다.
-->
</tr>
<tr>
<td>패스워드</td>
<td><input type="password" name="pwd" size="15"
value="<%=bean.getPwd()%>"></td>
</tr>
<tr>
<td>이름</td>
<td><input name="name" size="15"
value="<%=bean.getName()%>"></td>
</tr>
<tr>
<td>성별</td>
<td>남<input type="radio" name="gender" value="1"
<%=bean.getGender().equals("1")?"checked":""%>>
여<input type="radio" name="gender" value="2"
<%=bean.getGender().equals("2")?"checked":""%>>
</td>
</tr>
<tr>
<td>생년월일</td>
<td><input name="birthday" size="6"
value="<%=bean.getBirthday()%>">ex)920814</td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" size="30"
value="<%=bean.getEmail()%>"></td>
</tr>
<tr>
<td>우편번호</td>
<td><input name="zipcode" size="5"
value="" readonly> <input
type="button" value="우편번호찾기" onClick="zipCheck()"></td>
</tr>
<tr>
<td>주소</td>
<td><input name="address" size="45" value="<%=bean.getAddress()%>"></td>
</tr>
<tr>
<td>취미</td>
<td>
<%
String lists[] = {"인터넷", "여행", "게임", "영화", "운동"};
String hobby[] = bean.getHobby(); //10101
for(int i=0; i<lists.length; i++){
out.print(lists[i]);
%>
<input type="checkbox" name="hobby" value="<%=lists[i]%>"
<%=hobby[i].equals("1")?"checked":""%>></input>
<%
}
%>
</td>
</tr>
<tr>
<td>직업</td>
<td><select name=job>
<option value="0">선택하세요.
<option value="회사원">회사원
<option value="연구전문직">연구전문직
<option value="교수,학생">교수 / 학생
<option value="일반자영업">일반자영업
<option value="공무원">공무원
<option value="의료인">의료인
<option value="법조인">법조인
<option value="종교,언론,에술인">종교.언론/예술인
<option value="농,축,수산,광업인">농/축/수산/광업인
<option value="주부">주부
<option value="무직">무직
<option value="기타">기타
</select>
<script>document.regFrm.job.value="<%=bean.getJob()%>"</script>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="submit" value="수정완료">
<input type="reset" value="다시쓰기"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
memberUpdateProc.jsp
<%@page contentType="text/html; charset=EUC-KR" %>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="member.MemberMgr" />
<jsp:useBean id="bean" class="member.MemberBean" />
<jsp:setProperty property="*" name="bean"/>
<%
boolean result = mgr.updateMember(bean);
if(result){
%>
<script>
alert("회원정보를 수정 하였습니다.");
location.href = "login.jsp";
</script>
<%
}
else
{
%>
<script>
alert("회원정보를 수정에 실패 하였습니다.");
history.back();
</script>
<%}%>
로그인, 로그아웃
login.jsp
<!-- login.jsp -->
<%@ page contentType="text/html; charset=EUC-KR"%>
<%
request.setCharacterEncoding("EUC-KR");
String id = (String) session.getAttribute("idKey"); //세션에서 idkey를 가져온다
%>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function loginCheck() {
if (document.loginFrm.id.value == "") {
alert("아이디를 입력해 주세요.");
document.loginFrm.id.focus();
return;
}
if (document.loginFrm.pwd.value == "") {
alert("비밀번호를 입력해 주세요.");
document.loginFrm.pwd.focus();
return;
}
document.loginFrm.submit();
}
</script>
<body bgcolor="#FFFFCC">
<div align="center">
<br />
<br />
<%
if (id != null) {
%>
<b><%=id%></b>님 환영합니다.<br /> 제한된 기능을 사용 할 수가 있습니다.<br /> <a
href="logout.jsp">로그아웃</a> <a href="memberUpdate.jsp">회원수정</a>
<%
} else {
//id = request.getParameter("id");
%>
<form name="loginFrm" method="post" action="loginProc.jsp">
<!-- 일반적 select는 get방식이 일반적이나 단점은 넘어가는 값이 노출됨으로 로그인 시 보안에 문제가 생겨서 post를 쓴다. -->
<table>
<tr>
<td align="center" colspan="2"><h4>로그인</h4></td>
</tr>
<tr>
<td>아 이 디</td>
<td><input name="id" value="aaa"></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" name="pwd" value="1234"></td>
</tr>
<tr>
<td colspan="2">
<div align="right">
<input type="button" value="로그인" onclick="loginCheck()">
<input type="button" value="회원가입"
onClick="javascript:location.href='member.jsp'">
</div>
</td>
</tr>
</table>
</form>
<%
}
%>
</div>
</body>
loginProc.jsp
<!-- login Process.jsp -->
<%@page contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<jsp:useBean id="mgr" class="member.MemberMgr" />
<% request.setCharacterEncoding("EUC-KR");
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
boolean result = mgr.loginMember(id, pwd);
String msg = "로그인에 실패하였습니다.";
if(result) {
msg = "로그인에 성공하였습니다.";
session.setAttribute("idKey", id); //id를 세션 안에 넣어 두겠음
}
%>
<script>
alert("<%=msg%>");
location.href="login.jsp";
</script>
logout.jsp
<!-- logout.jsp -->
<%@ page contentType="text/html; charset=EUC-KR"%>
<%
//세션에 저장된 idKey를 제거
session.removeAttribute("idKey");
//현재 세션을 서버에서 제거
session.invalidate();
response.sendRedirect("login.jsp"); //로그아웃 후 로그인 폼으로 돌아가기
%>
728x90
728x90
'Java Friends > JSP' 카테고리의 다른 글
jsp로 투표 프로그램 만들기 (0) | 2019.07.22 |
---|---|
JSP 파일업로드 기능 구현 (0) | 2019.07.16 |
JSP 방명록 구현하기 (0) | 2019.07.15 |