복습★
더보기
- 새로운 페이지 팝업으로 띄우기
window.open("띄울.html", "아무 이름", "스타일")
- 닫는법
window.close();
- 부모페이지에 데이터 전달하기
** 스크립트방식
window.opender.document.querySelector('#부모id').value
** jQuery방식
$('입력할부모데이터',opener.document).val(새로운값)
- 새로 생성한 테이블에 (동적)이벤트
$(document).on('click','클래스이름이나 id이름', function(){ })
문제
유효성검사
전에 배운 이론 링크
유효성검사
1. on이벤트에서 'keyup' 타입으로 생성
2. 제출 버튼 'click'이벤트에서 유효성검사
아이디 유효성 | /^[a-zA-Z][a-zA-Z0-9]{3,12}$/ (규칙 영문자로 시작해서 숫자와 조합해서 4~12글자의 아이디) |
이름 유효성 | /^[가-힣]{2,6}$/ (2~6) |
전화번호 유효성 | /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/ |
이메일 유효성 | /^[a-zA-Z0-9._%+\-]+@([a-zA-Z]+[0-9.\-]*[a-zA-Z]*)(\.[a-zA-Z]+){1,2}$/ |
더보기
<script>
// 입력 데이터 체크하기 - 입력과 동시에 - keyup() 이벤트
$('#id').on('keyup', function(){
// 입력한 값
idvalue = $(this).val();
// 규칙 영문자로 시작해서 숫자와 조합해서 4~12글자의 아이디
regid = /^[a-zA-Z][a-zA-Z0-9]{3,12}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regid.test(idvalue)){
$(this).css('border', '2px solid green');
$('#idBtn').prop('disabled',false); // 중복검사 안눌리게
}else{
$(this).css('border', '2px solid red');
$('#idBtn').prop('disabled',true);
}
})
$('#name').on('keyup', function(){
// 입력한 값
namevalue = $(this).val();
// 한글 2글자이상 6글자이상
regname = /^[가-힣]{2,6}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regname.test(namevalue)){
$(this).css('border', '2px solid green');
}else{
$(this).css('border', '2px solid red');
}
})
</script>
회원가입.html
<!DOCTYPE html>
<html lang="kr">
<head>
<title>회원가입</title>
<meta charset="utf-8">
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script src="http://localhost/Jqpro/js/jquery.serializejson.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<style>
</style>
<script>
$(function(){
$('#idBtn').on('click',function(){
let vid = $('#id').val().trim();
if(vid.length<1){
alert("아이디를 입력하세요");
return;
}
// fetch('/Jqpro/idChk.do',{
// method : "POST",
// headers : {
// "Content-type" : "application/x-www-form-urlencoded" // 직렬화X
// },
// body : "mem_id="+vid
// })
fetch('/Jqpro/idChk.do?mem_id='+vid)
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.text();
// return response.json();
})
.then(function(data){
//data는 결과를 text로 받은 변수
$('#chkid').html(data);
// $('#chkid').html(data.flag);
})
})
$('#zipBtn').on('click',function(){
window.open("./view/zip.html","주소","width=500 height=800 top=200 left=300");
})
// 입력 데이터 체크하기 - 입력과 동시에 - keyup() 이벤트
$('#id').on('keyup', function(){
// 입력한 값
idvalue = $(this).val();
// 규칙 영문자로 시작해서 숫자와 조합해서 4~12글자의 아이디
regid = /^[a-zA-Z][a-zA-Z0-9]{3,12}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regid.test(idvalue)){
$(this).css('border', '2px solid green');
$('#idBtn').prop('disabled',false);
}else{
$(this).css('border', '2px solid red');
$('#idBtn').prop('disabled',true);
}
})
$('#name').on('keyup', function(){
// 입력한 값
namevalue = $(this).val();
// 한글 2글자이상 6글자이상
regname = /^[가-힣]{2,6}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regname.test(namevalue)){
$(this).css('border', '2px solid green');
}else{
$(this).css('border', '2px solid red');
}
})
$('#hp').on('keyup',function(){
// 전화번호
hpvalue = $(this).val()
reghp = /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/;
if(reghp.test(hpvalue)){
$(this).css('border', '2px solid green');
}else{
$(this).css('border', '2px solid red');
}
})
// 저장하기 - 가입하기
$('#submit').on('click',function(){
// 입력데이터 가져오기 - 9개
// 라이브러리없이 사용가능
fdata1 = $('#ff').serialize();
fdata2 = $('#ff').serializeArray();
fdata3 = $('#ff').serializeJSON();
console.log(fdata1);
console.log(fdata2);
console.log(fdata3);
/*
// id체크
idvalue = fdata3.mem_id;
// 규칙 영문자로 시작해서 숫자와 조합해서 4~12글자의 아이디
regid = /^[a-zA-Z][a-zA-Z0-9]{3,12}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regid.test(idvalue)){
$('#id').css('border', '2px solid green');
$('#idBtn').prop('disabled',false);
}else{
$('#id').css('border', '2px solid red');
$('#idBtn').prop('disabled',true);
return false; // 끝나게
}
// name체크
namevalue = fdata3.mem_name;
// 한글 2글자이상 6글자이상
regname = /^[가-힣]{2,6}$/;
// 규칙에 입력값이 올바른지 비교 - test() - true/false 리턴
if(regname.test(namevalue)){
$('#name').css('border', '2px solid green');
}else{
$('#name').css('border', '2px solid red');
}
*/
if($('#chkOK').length==0){
alert('중복검사를 해주세요');
return;
}
//POST
fetch("/Jqpro/InsertM.do",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8" // json 직렬화
},
// body : JSON.stringify({mem_id : vid, mem_pass : vpw, mem_name : vname, mem_hp : vhp, mem_bir : vbir, mem_mail : vmail, mem_zip : vzip, mem_add1 : vadd1, mem_add2 : vadd2}) // json
body : JSON.stringify(fdata3)
})
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
// return response.text();
return response.json();
})
.then(function(data){
console.log(data);
// $('#res').html(data);
$('#res').html(data.flag);
})
})
// 저장하기 - 가입하기 - form id=ff button[type=submit]
$('#ff').on('submit',function(ev){
// 기존에 이미 정해져 있는 기능을 취소
ev.preventDefault()
// event.preventDefault()
})
})
</script>
<style>
.mb-3 input{
width: 300px;
}
.flex{
display: flex;
}
input{
margin-right: 20px;
}
</style>
</head>
<body>
<div class="container mt-3">
<h2>회원 가입</h2>
<br>
<form action="" id="ff">
<div class="mb-3">
<label for="id">아이디:</label>
<!-- db칼럼과 name일치 -->
<div class="flex">
<input type="text" class="form-control" id="id" name="mem_id">
<button class="btn btn-outline-primary btn-sm" type="button" id="idBtn">중복검사</button>
</div>
<span id="chkid"></span>
</div>
<div class="mb-3">
<label for="pwd">비밀번호:</label>
<input type="password" class="form-control" id="pass" name="mem_pass">
</div>
<div class="mb-3">
<label for="name">이름:</label>
<input type="text" class="form-control" id="name" name="mem_name"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="hp">전화번호:</label>
<input type="text" class="form-control" id="hp" name="mem_hp"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="bir">생일:</label>
<input type="date" class="form-control" id="bir" name="mem_bir"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="email">Email:</label>
<input type="email" class="form-control" id="mail" name="mem_mail"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="zip">우편번호:</label>
<div class="flex">
<input type="text" class="form-control" id="zip" name="mem_zip"> <!-- db칼럼과 name일치 -->
<button class="btn btn-outline-primary btn-sm" type="button" id="zipBtn">검색</button>
</div>
</div>
<div class="mb-4">
<label for="add1">주소:</label>
<input type="text" class="form-control" id="add1" name="mem_add1"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-4">
<label for="add2">상세주소:</label>
<input type="text" class="form-control" id="add2" name="mem_add2"> <!-- db칼럼과 name일치 -->
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<br>
<div id="res"></div>
</body>
</html>
serialize
-- 라이브러리 없이 사용 가능
fdata1 = $('#form아이디').serialize();
fdata2 = $('#form아이디').serializeArray();
-- 라이브러리 필요 ( jquery.serializejson.min.js )
fdata3 = $('#form아이디').serializeJSON()
출력결과
serialize적용한 html
fetch("/Jqpro/InsertM.do",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8"
},
body : JSON.stringify(fdata3) // fdata3 = $('#ff').serializeJSON();
})
<!DOCTYPE html>
<html lang="kr">
<head>
<title>회원가입</title>
<meta charset="utf-8">
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script src="http://localhost/Jqpro/js/jquery.serializejson.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<style>
</style>
<script>
$(function(){
$('#idBtn').on('click',function(){
let vid = $('#id').val().trim();
if(vid.length<1){
alert("아이디를 입력하세요");
return;
}
// fetch('/Jqpro/idChk.do',{
// method : "POST",
// headers : {
// "Content-type" : "application/x-www-form-urlencoded" // 직렬화X
// },
// body : "mem_id="+vid
// })
fetch('/Jqpro/idChk.do?mem_id='+vid)
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.text();
// return response.json();
})
.then(function(data){
//data는 결과를 text로 받은 변수
$('#chkid').html(data);
// $('#chkid').html(data.flag);
})
})
$('#zipBtn').on('click',function(){
window.open("./view/zip.html","주소","width=500 height=800 top=200 left=300");
})
// 저장하기 - 가입하기
$('#submit').on('click',function(){
// 입력데이터 가져오기 - 9개
// 라이브러리없이 사용가능
fdata1 = $('#ff').serialize();
fdata2 = $('#ff').serializeArray();
fdata3 = $('#ff').serializeJSON();
console.log(fdata1);
console.log(fdata2);
console.log(fdata3);
if($('#chkOK').length==0){
alert('중복검사를 해주세요');
return;
}
//POST
fetch("/Jqpro/InsertM.do",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8" // json 직렬화
},
// body : JSON.stringify({mem_id : vid, mem_pass : vpw, mem_name : vname, mem_hp : vhp, mem_bir : vbir, mem_mail : vmail, mem_zip : vzip, mem_add1 : vadd1, mem_add2 : vadd2}) // json
body : JSON.stringify(fdata3)
})
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
// return response.text();
return response.json();
})
.then(function(data){
console.log(data);
// $('#res').html(data);
$('#res').html(data.flag);
})
})
// 저장하기 - 가입하기 - form id=ff button[type=submit]
$('#ff').on('submit',function(ev){
// 기존에 이미 정해져 있는 기능을 취소
ev.preventDefault()
// event.preventDefault()
})
})
</script>
<style>
.mb-3 input{
width: 300px;
}
.flex{
display: flex;
}
input{
margin-right: 20px;
}
</style>
</head>
<body>
<div class="container mt-3">
<h2>회원 가입</h2>
<br>
<form action="" id="ff">
<div class="mb-3">
<label for="id">아이디:</label>
<!-- db칼럼과 name일치 -->
<div class="flex">
<input type="text" class="form-control" id="id" name="mem_id">
<button class="btn btn-outline-primary btn-sm" type="button" id="idBtn">중복검사</button>
</div>
<span id="chkid"></span>
</div>
<div class="mb-3">
<label for="pwd">비밀번호:</label>
<input type="password" class="form-control" id="pass" name="mem_pass">
</div>
<div class="mb-3">
<label for="name">이름:</label>
<input type="text" class="form-control" id="name" name="mem_name"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="hp">전화번호:</label>
<input type="text" class="form-control" id="hp" name="mem_hp"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="bir">생일:</label>
<input type="date" class="form-control" id="bir" name="mem_bir"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="email">Email:</label>
<input type="email" class="form-control" id="mail" name="mem_mail"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-3">
<label for="zip">우편번호:</label>
<div class="flex">
<input type="text" class="form-control" id="zip" name="mem_zip"> <!-- db칼럼과 name일치 -->
<button class="btn btn-outline-primary btn-sm" type="button" id="zipBtn">검색</button>
</div>
</div>
<div class="mb-4">
<label for="add1">주소:</label>
<input type="text" class="form-control" id="add1" name="mem_add1"> <!-- db칼럼과 name일치 -->
</div>
<div class="mb-4">
<label for="add2">상세주소:</label>
<input type="text" class="form-control" id="add2" name="mem_add2"> <!-- db칼럼과 name일치 -->
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<br>
<div id="res"></div>
</body>
</html>
우편번호.html
<!DOCTYPE html>
<html lang="kr">
<head>
<title>회원가입</title>
<meta charset="utf-8">
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function(){
$('#zipBtn').on('click',function(){
let vdong = $('#id').val().trim();
if(vdong.length<1){
alert("동을 입력하세요");
return;
}
console.log(vdong);
// fetch('/Jqpro/ZipSearch.do?dong='+vdong)
fetch("/Jqpro/ZipSearch.do",{
method : "POST",
headers : {
"Content-type" : "application/json;charset=utf-8" // json 직렬화
},
body : JSON.stringify({dong : vdong}) // json
})
.then(function(response){
console.log("response", response);
if(!response.ok){
throw new Error(`오류발생 : ${response.status}`);
}
return response.json();
})
.then(function(data){
let code = `<table border='1'><tr><th>우편번호</th><th>시</th><th>군</th><th>동</th></tr>`;
$.each(data, function(){
code+=`<tr class="zip">
<td id="code">
${this.zipcode}
</td>
<td id="sido">
${this.sido}
</td>
<td id="gugun">
${this.gugun}
</td>
<td id="dong">
${this.dong}
</td>
</tr>`;
})
code+=`</table>`;
$('#result').html(code);
})
})
$(document).on('click','.zip',function(){
let value = $("#code", this).text().trim();
let add = $("#sido", this).text().trim() + " " + $("#gugun", this).text().trim()
+ " " + $("#dong", this).text().trim();
console.log(value);
window.opener.document.querySelector('#zip').value = value;
window.opener.document.querySelector('#add1').value = add;
window.close();
})
})
</script>
<style>
.mb-3 input{
width: 300px;
}
.flex{
display: flex;
}
input{
margin-right: 20px;
}
</style>
</head>
<body>
<div class="container mt-3">
<h3>우편번호 검색</h2>
<br>
<form action="">
<div class="mb-3">
<label for="id">동 검색:</label>
<div class="flex">
<input type="text" class="form-control" id="id" name="dong">
<button class="btn btn-outline-primary btn-sm" type="button" id="zipBtn">주소검색</button>
</div>
</div>
</form>
<div id="result"></div>
</div>
</body>
</html>
우편번호 저장할 jsp
<%@page import="com.google.gson.Gson"%>
<%@page import="com.google.gson.GsonBuilder"%>
<%@page import="kr.or.ddit.member.vo.ZipVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
List<ZipVO> list = (List<ZipVO>)request.getAttribute("listvalue");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(list);
out.print(json);
out.flush();
%>
중복검사 (전달 출력시) jsp
더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
int count = (int)(request.getAttribute("cnt"));
if(count>0){
%>
{
"flag" : "사용불가능한 아이디"
}
<%
}else{
%>
{
"flag" : "사용가능한 아이디"
}
<%
}
%>
%>
servlet으로 전송하기 위한 데이터
더보기
Config
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org/DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- DB연결 정보가 있는 Properties파일 설정 -->
<properties resource="kr/or/ddit/mybatis/config/dbinfo.properties" />
<!-- MyBatis의 기본 설정값 세팅 -->
<settings>
<!-- 데이터가 null로 전달되었으면 빈칸으로 인지되지 않고 null로 인식하는 설정 -->
<!-- value값은 전부 대문자 -->
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<typeAliases>
<!-- MyBatis에서 사용되는 클래스들은 사용할 때 패키지명이 포함된
전체 이름을 사용해야되는데 이것을 대신해서 짧은 이름으로 사용하기 위한 별칭을 등록한다.
형식) <typeAlias type="패키지명을 포함한 전체이름" alias="별칭이름"/>
-->
<typeAlias type="kr.or.ddit.member.vo.MemberVO" alias="memVo"/>
<typeAlias type="kr.or.ddit.member.vo.ZipVO" alias="zipVo"/>
</typeAliases>
<!-- DB에 연결 할 정보 설정하기 -->
<environments default="oracleDB">
<!-- 다른 DB도 연결할 수 있으므로 env는 여러개 올 수 있다 / id는 구분하기 위한 이름 -->
<environment id="oracleDB">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/><!-- value값에 프로퍼티스의 키값 작성 -->
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${pass}"/>
</dataSource>
</environment>
</environments>
<!-- DB에서 사용되는 SQL문이 작성된 mapper파일을 등록하는 부분 -->
<mappers>
<!--
형식) <mapper resource="경로명/파일명.xml"/>
-->
<mapper resource="kr/or/ddit/mybatis/mappers/member-mapper.xml"/>
</mappers>
</configuration>
mapper
<?xml version="1.0" encoding="UTF-8"?>
<!-- 이 문서는 myBatis에서 처리할 SQL문을 작성하는 문서입니다 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- <mapper>태그의 namespace속성에 설정된 값은 Java소스에서 실행할 SQL문을 호출할 때
같이 사용되는 이름이다 -->
<mapper namespace="mem">
<select id="getAllMem" resultType="memVo">
select * from member
</select>
<select id="zip" parameterType="String" resultType="zipVo">
select * from ziptb where dong like '%'||#{dong}||'%'
</select>
<select id="idchk" parameterType="String" resultType="int">
select count(*) from member where mem_id=#{mem_id}
</select>
<insert id="insertMember" parameterType="memVo">
insert into member(mem_id, mem_pass, mem_name, mem_bir, mem_zip, mem_add1, mem_add2, mem_hp, mem_mail)
values(#{mem_id}, #{mem_pass}, #{mem_name}, #{mem_bir}, #{mem_zip}, #{mem_add1}, #{mem_add2}, #{mem_hp}, #{mem_mail})
</insert>
</mapper>
dao
package kr.or.ddit.member.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.member.vo.MemberVO;
import kr.or.ddit.member.vo.ZipVO;
import kr.or.ddit.util.MyBatisUtil;
public class MemberMybatisDaoImpl implements IMemberDao{
private static MemberMybatisDaoImpl dao;
// 생성자가 없으면 다른 클래스에서 객체를 생성할 수도 있기 때문에 private로 생성 못하게 막음
private MemberMybatisDaoImpl() {
// TODO Auto-generated constructor stub
}
public static MemberMybatisDaoImpl getInstance() {
if(dao==null) {
dao = new MemberMybatisDaoImpl();
}
return dao;
}
@Override
public List<MemberVO> getAllMember() {
List<MemberVO> list = null;
SqlSession session = null;
try {
session = MyBatisUtil.getSqlSession();
list = session.selectList("mem.getAllMem");
} catch (Exception e) {
// TODO: handle exception
} finally {
if(session!=null) try {session.close();}catch(Exception e){}
}
return list;
}
@Override
public int idChk(String mem_id) {
SqlSession session = null;
int cnt = 0;
try {
session = MyBatisUtil.getSqlSession();
cnt = session.selectOne("mem.idchk", mem_id);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if(session!=null) try {session.close();}catch(Exception e){}
}
return cnt;
}
@Override
public List<ZipVO> zipSearch(String dong) {
SqlSession session = null;
List<ZipVO> list = null;
try {
session = MyBatisUtil.getSqlSession();
list = session.selectList("mem.zip", dong);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if(session!=null) try {session.close();}catch(Exception e){}
}
return list;
}
@Override
public int insertMember(MemberVO vo) {
SqlSession session = null;
int cnt = 0;
try {
session = MyBatisUtil.getSqlSession();
cnt = session.insert("mem.insertMember", vo);
if(cnt>0) {
session.commit();
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if(session!=null) try {session.close();}catch(Exception e){}
}
return cnt;
}
}
중복검사 Servlet
package kr.or.ddit.member.controller;
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;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
/**
* Servlet implementation class IdChk
*/
@WebServlet("/idChk.do")
public class IdChk extends HttpServlet {
private static final long serialVersionUID = 1L;
// service 객체 얻기
private IMemberService service = MemberServiceImpl.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mem_id = request.getParameter("mem_id"); // id값
int cnt = service.idChk(mem_id);
String result = "<span id='chkOK' style='color:green'>사용가능한 아이디입니다</span>";
if(cnt>0) {
result = "<span style='color:red'>중복된 아이디입니다</span>";
}
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter(); out.println(result);
// request.setAttribute("cnt", cnt);
// request.getRequestDispatcher("/비동기fetch/view/idChk.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
우편번호 Servlet
package kr.or.ddit.member.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
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 com.google.gson.Gson;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.ZipVO;
/**
* Servlet implementation class ZipSearch
*/
@WebServlet("/ZipSearch.do")
public class ZipSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
private IMemberService service = MemberServiceImpl.getInstance();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
StringBuffer buf = new StringBuffer();
String line = null;
try {
BufferedReader br = request.getReader();
while((line = br.readLine())!=null) {
buf.append(line);
}
} catch (Exception e) {
// TODO: handle exception
}
String reqdata = buf.toString();
Gson gson = new Gson();
ZipVO vo = gson.fromJson(reqdata, ZipVO.class);
String dong = vo.getDong();
// String dong = request.getParameter("dong");
List<ZipVO> list = service.zipSearch(dong);
request.setAttribute("listvalue", list);
request.getRequestDispatcher("/비동기fetch/view/zip.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
회원추가insert Servlet
POST방식
package kr.or.ddit.member.controller;
import java.io.BufferedReader;
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;
import com.google.gson.Gson;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;
/**
* Servlet implementation class InsertM
*/
@WebServlet("/InsertM.do")
public class InsertM extends HttpServlet {
private static final long serialVersionUID = 1L;
private IMemberService service = MemberServiceImpl.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// POST방식
request.setCharacterEncoding("UTF-8");
StringBuffer buf = new StringBuffer();
String line = null;
try {
BufferedReader br = request.getReader();
while((line=br.readLine())!=null) {
buf.append(line);
}
} catch (Exception e) {
// TODO: handle exception
}
String reqdata = buf.toString();
Gson gson = new Gson();
MemberVO vo = gson.fromJson(reqdata, MemberVO.class);
int cnt = service.insertMember(vo);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
if(cnt>0) {
String html = "<html><head><meta charset='utf-8'><title>가입완료</title></head>"
+ "<body><h1>가입완료</h1><h3>"+vo.getMem_name()+"님 환영합니다</h3></body></html>";
out.println(html);
} else {
out.print(cnt+" 실패");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
GET방식
package kr.or.ddit.member.controller;
import java.io.BufferedReader;
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;
import com.google.gson.Gson;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;
/**
* Servlet implementation class InsertM
*/
@WebServlet("/InsertM.do")
public class InsertM extends HttpServlet {
private static final long serialVersionUID = 1L;
private IMemberService service = MemberServiceImpl.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// GET방식
String mem_id = request.getParameter("id");
String mem_pass = request.getParameter("pass");
String mem_name = request.getParameter("name");
String mem_hp = request.getParameter("hp");
String mem_bir = request.getParameter("bir");
String mem_mail = request.getParameter("mail");
String mem_zip = request.getParameter("zip");
String mem_add1 = request.getParameter("add1");
String mem_add2 = request.getParameter("add2");
MemberVO vo = new MemberVO();
vo.setMem_add1(mem_add1);
vo.setMem_add2(mem_add2);
vo.setMem_bir(mem_bir);
vo.setMem_hp(mem_hp);
vo.setMem_id(mem_id);
vo.setMem_mail(mem_mail);
vo.setMem_name(mem_name);
vo.setMem_pass(mem_pass);
vo.setMem_zip(mem_zip);
int cnt = service.insertMember(vo);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
if(cnt>0) {
String html = "<html><head><meta charset='utf-8'><title>가입완료</title></head>"
+ "<body><h1>가입완료</h1><h3>"+vo.getMem_name()+"님 환영합니다</h3></body></html>";
out.println(html);
} else {
out.print(cnt+" 실패");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
회원추가를 request - forward로 보내는 경우
package kr.or.ddit.member.controller;
import java.io.BufferedReader;
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;
import com.google.gson.Gson;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.member.vo.MemberVO;
/**
* Servlet implementation class InsertM
*/
@WebServlet("/InsertM.do")
public class InsertM extends HttpServlet {
private static final long serialVersionUID = 1L;
private IMemberService service = MemberServiceImpl.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// GET방식
// String mem_id = request.getParameter("id");
// String mem_pass = request.getParameter("pass");
// String mem_name = request.getParameter("name");
// String mem_hp = request.getParameter("hp");
// String mem_bir = request.getParameter("bir");
// String mem_mail = request.getParameter("mail");
// String mem_zip = request.getParameter("zip");
// String mem_add1 = request.getParameter("add1");
// String mem_add2 = request.getParameter("add2");
//
// MemberVO vo = new MemberVO();
//
// vo.setMem_add1(mem_add1);
// vo.setMem_add2(mem_add2);
// vo.setMem_bir(mem_bir);
// vo.setMem_hp(mem_hp);
// vo.setMem_id(mem_id);
// vo.setMem_mail(mem_mail);
// vo.setMem_name(mem_name);
// vo.setMem_pass(mem_pass);
// vo.setMem_zip(mem_zip);
// POST방식
request.setCharacterEncoding("UTF-8");
StringBuffer buf = new StringBuffer();
String line = null;
try {
BufferedReader br = request.getReader();
while((line=br.readLine())!=null) {
buf.append(line);
}
} catch (Exception e) {
// TODO: handle exception
}
String reqdata = buf.toString();
// 역직렬화 MemberVO로 변환
Gson gson = new Gson();
// 여기서 vo.setMem_id()식으로 실행되어서 모든 데이터로 채워진다
MemberVO vo = gson.fromJson(reqdata, MemberVO.class);
// 성공시 1, 실패 0
int cnt = service.insertMember(vo);
// request에 저장
request.setAttribute("cnt", cnt);
// view페이지로 이동 - forward
request.getRequestDispatcher("/비동기fetch/view/complete.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 저장한 데이터 꺼내기
int cnt = (int)request.getAttribute("cnt");
if(cnt>0){
%>
{
"flag" : "회원가입이 완료되었습니다."
}
<%
}else{
%>
{
"flag" : "회원가입에 실패했습니다."
}
<%
}
%>
'웹프로그래밍 > jQuery' 카테고리의 다른 글
[jQuery] 게시판 (2) | 2024.06.03 |
---|---|
[jQuery] 비동기 fetch, 직렬화 (0) | 2024.05.29 |
[jQuery] Servlet을 활용한 promise (0) | 2024.05.28 |
[jQuery] 비동기 AJAX (json) (0) | 2024.05.27 |
[jQurey] 비동기 AJAX (0) | 2024.05.24 |