[jQuery]会員登録
120904 ワード
Main_jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="kr">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="../js/jquery.serializejson.min.js"></script>
<script src="../js/regcheck.js"></script>
<style type="text/css">
.ziptr:hover{
background: lime;
}
</style>
<script type="text/javascript">
$(function(){
/* 아이디 중복검사 */
$('#idbtn').on('click', function(){
idvalue = $('#id').val().trim();
if(idvalue.length < 1){
alert("id를 입력하세요");
return false;
}
if(idvalue.length<4 || idvalue.length > 12){
alert("id는 4~12자리 사이 ");
return false;
}
// 정규식 체크 - idcheck()호출
if(!idcheck()) return false;
// 서버로 전송하기
$.ajax({
url : '/jqpro/CheckId.do',
data: {"id": idvalue}, // data : "id= "+ idvalue
type: 'get',
success : function(res){ /* res는 서블릿 -> 서비스 -> 다오 -> 매퍼 다녀온 결과값 */
$('#spanid').html(res.sw).css('color','red');
},
error: function(xhr){
alert("상태: " + xhr.status); // 404(url이름), 500(콘솔), 200(json형태-jsp)
},
dataType : 'json'
})
})
$('#zipbtn').on('click', function(){
window.open("zipsearch.jsp","", "width=500 height=400");
})
// 우편번호 검색-modal. modal창에서 검색버튼 클릭하면
$('#but').on('click', function(){
dongvalue = $('#dong').val().trim();
if(dongvalue.length <1){
alert("입력하세요");
return false;
}
// 서버로 전송하기
$.ajax({
/* jqpro는 contextpath와 동일 */
url : "<%= request.getContextPath()%>/ZipSearch.do",
data: {"dong" : dongvalue},
type : 'post',
success : function(res){
str ="<table>"
str += "<tr><td>우편번호</td>";
str += "<td>주소</td><td>번지</td></tr>"
$.each(res, function(i, v){
str += "<tr class = 'ziptr'><td>"+res[i].zipcode+"</td>";
str += "<td>"+v.addr+"</td><td>"+v.bunji+"</td></tr>"
})
str+="</table>";
$('#result').html(str);
},
error : function(xhr){
alert("상태: "+ xhr.status)
},
dataType : 'json'
})
})
$(document).on('click','.ziptr', function(){
zip = $('td:eq(0)', this).text();
addr = $('td:eq(1)', this).text();
// 부모의 input창의 넣는다,,
$('#zip').val(zip);
$('#add1').val(addr);
// 실행결과 지우기
/* $('#dong').val("");
$('#result').empty(); */
$('#myModal').modal('hide');
})
// 모달닫는 이벤트 - 실행결과 지우기
$("#myModal").on('hide.bs.modal', function(){
$('#dong').val("");
$('#result').empty();
});
/* 가입-저장하기 */
$('form').on('submit', function(){
/* alert("submit"); */
//입력한 모든 값 가져오기 - 정규식
console.log($('form').serialize());
console.log($('form').serializeArray());
console.log($('form').serializeJSON());
if(!regcheck()) return false;
// 각 항목에 대한 정규식이 통과되면 서버로 전송
$.ajax({
url : '/jqpro/Insert.do',
data: $('form').serializeArray(),
type : 'post',
success : function(res){
},
error : function(xhr){
alert("상태: "+ xhr.status);
},
dataType : 'json'
})
})
})
</script>
</head>
<body>
<div class="container">
<h2>Horizontal form</h2>
<form class="form-horizontal" onsubmit = "return false;">
<div class="form-group">
<label class="control-label col-sm-2" for="id">아이디</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="id" placeholder="Enter id" name="mem_id">
</div>
<!-- 버튼옆에 결과 뿌릴꺼라 onclick="/jqpro/CheckIDServlet.do" 불필요 -->
<button id="idbtn" type="button" class="btn">중복검사</button>
<span id ="spanid"></span> <!-- 중복검사버튼옆공간생성 -->
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="name">이름</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="name" placeholder="Enter name" name="mem_name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="bir">생년월일</label>
<div class="col-sm-2">
<input type="date" class="form-control" id="bir" placeholder="Enter bir" name="mem_bir">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">비밀번호</label>
<div class="col-sm-2">
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="mem_pass">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">이메일</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="email" placeholder="Enter email" name="mem_mail">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="hp">휴대폰번호</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="hp" placeholder="Enter hp" name="mem_hp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="zip">우편번호</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="zip" placeholder="Enter zip" name="mem_zip">
</div>
<button id="zipbtn" type="button" class="btn">번호검색window</button>
<button type="button" class="btn" data-toggle="modal" data-target="#myModal">번호검색modal</button>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="add1">주소</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="add1" placeholder="Enter add1" name="mem_add1">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="add2">상세주소</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="add2" placeholder="Enter add2" name="mem_add2">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">제출</button>
</div>
</div>
</form>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog"> <!-- modal-lg -->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<h3>찾는 동이름을 입력하세요</h3>
<input type= "text" name="dong" id="dong">
<button type = "button" id ="but">검색</button>
<br><br>
<div id = "result">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
zipcode_jsp
<%@page import="kr.or.ddit.join.vo.ZipVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 서블릿에서 수행된 결과 공유하여 json Object의 배열을 생성
List<ZipVO> list = (List<ZipVO>)request.getAttribute("listd");
%>
[
<%
for(int i=0; i<list.size(); i++){
ZipVO vo = list.get(i);
if(i>0) out.print(",");
String bunji = vo.getBunji();
if(bunji==null) bunji="";
%>
{
"zipcode" : "<%= vo.getZipcode() %>",
"addr" :"<%= vo.getSido() %> <%= vo.getGugun() %> <%= vo.getDong() %>",
"bunji" : "<%= bunji %>"
}
<%
}
%>
]
zipsearch_jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="../js/jquery-3.6.0.min.js"></script>
<style type="text/css">
.ziptr:hover{
background: pink;
}
</style>
<script type="text/javascript">
$(function(){
$('#but').on('click', function(){
dongvalue = $('#dong').val().trim();
console.log(dongvalue);
if(dongvalue.length <1){
alert("입력하세요");
return false;
}
// 서버로 전송하기
$.ajax({
/* jqpro는 contextpath와 동일 */
url : "<%= request.getContextPath()%>/ZipSearch.do",
data: {"dong" : dongvalue},
type : 'post',
success : function(res){
str ="<table>"
str += "<tr><td>우편번호</td>";
str += "<td>주소</td><td>번지</td></tr>"
$.each(res, function(i, v){
str += "<tr class = 'ziptr'><td>"+res[i].zipcode+"</td>";
str += "<td>"+v.addr+"</td><td>"+v.bunji+"</td></tr>"
})
str+="</table>";
$('#result').html(str);
},
error : function(xhr){
alert("상태: "+ xhr.status)
},
dataType : 'json'
})
})
// ziptr은 bind로하면안되고 delegate로해야한다.........
// bind 방식은 $('.ziptr').on('click', function(){})
$(document).on('click','.ziptr', function(){
zip = $('td:eq(0)', this).text();
addr = $('td:eq(1)', this).text();
// 부모의 input창의 넣는다,,
$('#zip', opener.document).val(zip);
$('#add1', opener.document).val(addr);
window.close(); // 오픈한 창을 닫는다.
})
})
</script>
</head>
<body>
<h3>찾는 동이름을 입력하세요</h3>
<input type= "text" name="dong" id="dong">
<button type = "button" id ="but">검색</button>
<br><br>
<div id = "result">
</div>
</body>
</html>
checkId_jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 서블릿에서 결과값 공유하기
String id = (String)request.getAttribute("cid");
if(id==null){
%>
{
"sw" : "사용가능한 id입니다."
}
<% }else{ %>
{
"sw": "사용불가능한 id입니다."
}
<%}
%>
mapper - xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace = "join">
<!-- 중복검사 -->
<select id="checkId" resultClass="String" parameterClass="String">
select mem_id from member where mem_id = #data#
</select>
<!-- 우편번호 -->
<select id="selectByDong" resultClass="zipVo" parameterClass="String">
select * from ziptb where dong like #data#||'%'
</select>
<!-- 가입하기 -->
<insert id="insertMember" parameterClass="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#)
<selectKey resultClass="string" keyProperty="mem_id">
select mem_id from member where mem_id = #mem_id#
</selectKey>
</insert>
</sqlMap>
config
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- DB와 연결하는 정보를 properties파일에 설정해 놓고 이 properties파일의 내용을 읽어올 수 있도록 설정한다. -->
<properties resource="kr/or/ddit/ibatis/config/dbinfo.properties"/>
<!-- SQL문이 저장된 xml문서에서 실행할 쿼리문을 찾을때 xml문서의 네임스페이스와 SQL문이 작성된 태그의 id 속성값을 연결해서 찾도록 설정한다. -->
<settings useStatementNamespaces="true"/>
<!--
쿼리문에 사용할 VO객체는 패키지 이름을 포함한 전체 이름을 사용해야 하는데 그렇게 되면 문장이 너무 길어질 수 있기 때문에
전체이름을 대신할 alias를 설정할 수 있다.
형식) <typeAlias alias = "alias명" type="클래스의 풀네임"/>
-->
<typeAlias alias="memberVo" type="kr.or.ddit.member.vo.MemberVO"/>
<typeAlias alias="lprodVo" type="kr.or.ddit.lprod.vo.LprodVO"/>
<typeAlias alias="BuyerVo" type="kr.or.ddit.buyer.vo.BuyerVO"/>
<typeAlias alias="ProdVo" type="kr.or.ddit.prod.vo.ProdVO"/>
<typeAlias alias="memVo" type="kr.or.ddit.join.vo.MemVO"/>
<typeAlias alias="zipVo" type="kr.or.ddit.join.vo.ZipVO"/>
<!-- <typeAlias alias="lprodVo" type="lprodVo"/> -->
<!-- DB와의 연결을 처리하는 부분-->
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${user}"/>
<property name="JDBC.Password" value="${pass}"/>
</dataSource>
</transactionManager>
<!-- 실행할 SQL문을 등록 -->
<!-- 실행할 SQL문은 xml문서로 따로 만든 후 그 xml문서를 아래와 같이 등록하면 된다.
형식) <sqlMap resource = "경로명/파일명.xml"/>
-->
<sqlMap resource ="kr/or/ddit/ibatis/mapper/memberTest.xml"/>
<sqlMap resource ="kr/or/ddit/ibatis/mapper/lprod.xml"/>
<sqlMap resource ="kr/or/ddit/ibatis/mapper/buyer.xml"/>
<sqlMap resource ="kr/or/ddit/ibatis/mapper/lprod_prod.xml"/>
<sqlMap resource ="kr/or/ddit/ibatis/mapper/member.xml"/>
</sqlMapConfig>
CheckId Servlet
package kr.or.ddit.join.controller;
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 kr.or.ddit.join.service.IJoinService;
import kr.or.ddit.join.service.JoinServiceImpl;
@WebServlet("/CheckId.do")
public class CheckId extends HttpServlet {
private static final long serialVersionUID = 1L;
public CheckId() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0. 클라이언트 요청시 전송데이터 받기 - jsp의 id
String userId = request.getParameter("id");
// 1. service객체 얻기
IJoinService service = JoinServiceImpl.getJoinService();
// 2. service 메서드 호출 - 결과값 받기
// 결과값을 이용해서 json을 생성하거나 출력한다. -> jsp응답페이지로 forward시켜서 위임한다.
String checkId = service.checkId(userId);
// 3. 결과값을 request에 저장
request.setAttribute("cid", checkId);
// 4. jsp로 forward시킨다.
request.getRequestDispatcher("1204/checkId.jsp").forward(request, response);
}
}
zipSearchテンプレート
package kr.or.ddit.join.controller;
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 kr.or.ddit.join.service.IJoinService;
import kr.or.ddit.join.service.JoinServiceImpl;
import kr.or.ddit.join.vo.ZipVO;
@WebServlet("/ZipSearch.do")
public class ZipSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ZipSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 0. 클라이언트 요청시 전송데이터 받기 - jsp의 dong
String dong = request.getParameter("dong");
// 1. service객체 얻기
IJoinService service = JoinServiceImpl.getJoinService();
// 2. service 메서드 호출 - 결과값 받기
// 결과값을 이용해서 json을 생성하거나 출력한다. -> jsp응답페이지로 forward시켜서 위임한다.
List<ZipVO> list = service.selectByDong(dong);
// 3. 결과값을 request에 저장
request.setAttribute("listd", list);
// 4. jsp로 forward시킨다.
request.getRequestDispatcher("1204/zipcode.jsp").forward(request, response);
}
}
dao
package kr.or.ddit.join.dao;
import java.sql.SQLException;
import java.util.List;
import kr.or.ddit.join.vo.MemVO;
import kr.or.ddit.join.vo.ZipVO;
import kr.or.ddit.member.vo.MemberVO;
public interface IJoinDao {
public String checkId(String id) throws SQLException;
public List<ZipVO> selectByDong(String dong)throws SQLException;
public String insertMember(MemVO vo)throws SQLException;
}
package kr.or.ddit.join.dao;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.sqlmap.client.SqlMapClient;
import kr.or.ddit.ibatis.config.SqlMapClientFactory;
import kr.or.ddit.join.vo.MemVO;
import kr.or.ddit.join.vo.ZipVO;
import kr.or.ddit.lprod.dao.ILprodDao;
import kr.or.ddit.lprod.dao.LprodDaoImpl;
public class JoinDaoImpl implements IJoinDao{
private SqlMapClient smc;
private static JoinDaoImpl dao;
private JoinDaoImpl() {
smc = SqlMapClientFactory.getSqlMapClient();
}
public static IJoinDao getJoinDao(){
if(dao==null) dao = new JoinDaoImpl(); // 인터페이스로받은 클래스로받든 객체 생성은 클래스로
return dao;
}
@Override
public String checkId(String id) throws SQLException {
// String memId = null;
// memId = (String)smc.queryForObject("join.checkId", id);
// return memId;
return (String)smc.queryForObject("join.checkId", id);
}
@Override
public List<ZipVO> selectByDong(String dong) throws SQLException {
// TODO Auto-generated method stub
List<ZipVO> list = smc.queryForList("join.selectByDong", dong);
return list;
}
@Override
public String insertMember(MemVO vo) throws SQLException {
String memId = (String)smc.insert("join.insertMember", vo);
return memId;
}
}
service
package kr.or.ddit.join.service;
import java.util.List;
import kr.or.ddit.join.vo.MemVO;
import kr.or.ddit.join.vo.ZipVO;
import kr.or.ddit.member.vo.MemberVO;
public interface IJoinService {
public String checkId(String id);
public List<ZipVO> selectByDong(String dong);
public String insertMember(MemVO vo);
}
package kr.or.ddit.join.service;
import java.sql.SQLException;
import java.util.List;
import kr.or.ddit.join.dao.IJoinDao;
import kr.or.ddit.join.dao.JoinDaoImpl;
import kr.or.ddit.join.vo.MemVO;
import kr.or.ddit.join.vo.ZipVO;
import kr.or.ddit.lprod.service.ILprodService;
import kr.or.ddit.lprod.service.LprodServiceImpl;
public class JoinServiceImpl implements IJoinService{
private IJoinDao dao;
private static IJoinService service;
private JoinServiceImpl() {
dao = JoinDaoImpl.getJoinDao();
}
public static IJoinService getJoinService(){
if(service==null) service = new JoinServiceImpl();
return service;
}
@Override
public String checkId(String id) {
String st = null;
try {
st = dao.checkId(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
}
@Override
public List<ZipVO> selectByDong(String dong) {
List<ZipVO> list = null;
try {
list = dao.selectByDong(dong);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public String insertMember(MemVO vo) {
String st2 = null;
try {
st2 = dao.insertMember(vo);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st2;
}
}
vo
package kr.or.ddit.join.vo;
public class MemVO {
private String mem_id;
private String mem_name;
private String mem_pass;
private String mem_hp;
private String mem_add1;
private String mem_add2;
private String mem_mail;
private String mem_zip;
private String mem_bir;
public MemVO() {
// TODO Auto-generated constructor stub
}
public MemVO(String mem_id, String mem_name, String mem_pass,
String mem_hp, String mem_add1, String mem_add2, String mem_mail,
String mem_zip, String mem_bir) {
super();
this.mem_id = mem_id;
this.mem_name = mem_name;
this.mem_pass = mem_pass;
this.mem_hp = mem_hp;
this.mem_add1 = mem_add1;
this.mem_add2 = mem_add2;
this.mem_mail = mem_mail;
this.mem_zip = mem_zip;
this.mem_bir = mem_bir;
}
public String getMem_id() {
return mem_id;
}
public void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
public String getMem_name() {
return mem_name;
}
public void setMem_name(String mem_name) {
this.mem_name = mem_name;
}
public String getMem_pass() {
return mem_pass;
}
public void setMem_pass(String mem_pass) {
this.mem_pass = mem_pass;
}
public String getMem_hp() {
return mem_hp;
}
public void setMem_hp(String mem_hp) {
this.mem_hp = mem_hp;
}
public String getMem_add1() {
return mem_add1;
}
public void setMem_add1(String mem_add1) {
this.mem_add1 = mem_add1;
}
public String getMem_add2() {
return mem_add2;
}
public void setMem_add2(String mem_add2) {
this.mem_add2 = mem_add2;
}
public String getMem_mail() {
return mem_mail;
}
public void setMem_mail(String mem_mail) {
this.mem_mail = mem_mail;
}
public String getMem_zip() {
return mem_zip;
}
public void setMem_zip(String mem_zip) {
this.mem_zip = mem_zip;
}
public String getMem_bir() {
return mem_bir;
}
public void setMem_bir(String mem_bir) {
this.mem_bir = mem_bir;
}
}
package kr.or.ddit.join.vo;
public class ZipVO {
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String bunji;
public ZipVO() {
// TODO Auto-generated constructor stub
}
public ZipVO(String zipcode, String sido, String gugun, String dong,
String bunji) {
super();
this.zipcode = zipcode;
this.sido = sido;
this.gugun = gugun;
this.dong = dong;
this.bunji = bunji;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getSido() {
return sido;
}
public void setSido(String sido) {
this.sido = sido;
}
public String getGugun() {
return gugun;
}
public void setGugun(String gugun) {
this.gugun = gugun;
}
public String getDong() {
return dong;
}
public void setDong(String dong) {
this.dong = dong;
}
public String getBunji() {
return bunji;
}
public void setBunji(String bunji) {
this.bunji = bunji;
}
}
Reference
この問題について([jQuery]会員登録), 我々は、より多くの情報をここで見つけました https://velog.io/@vgo_dongv/jQuery-회원가입テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol