이러한 화면을 만들고 등록을 하면 입력한 값에 대한 정보가 DB에 저장되고 조회를 누르면 해당 값에 대한 정보와 일치하는 목록을 출력하는 간단한 예제를 만들어 본다.
페이지는 <table>, <tr>, <td>를 적절히 이용하여 만들어준다.
<style>
table, tr, td{
height:26px;
border: 1px solid skyblue;
}
td p{
text-align:center;
width:140px;
margin:0px;
}
tr td:nth-child(2){
width:375px;
}
input[type="text"]{
border-color:skyblue;
}
h2{
text-align:center;
width:531px;
margin: 0px;
margin-bottom: 20px;
margin-top: 20px;
}
</style>
->이 페이지에서 사용한 css 부분이다. 별거 없다.
<body>
<h2>회원 등록</h2>
<form id="form" name="idtextf" method="post" action="userlist.jsp">
<table>
<tr>
<td><p>아이디</p></td>
<td>
<input type="text" name="idtext">
</td>
</tr>
<tr>
<td><p>비밀번호</p></td>
<td><input type="text" name="pwtext"></td>
</tr>
<tr>
<td><p>서명</p></td>
<td><input type="text" name="nmtext"></td>
</tr>
<tr>
<td><p>이메일</p></td>
<td><input type="text" name="emtext" style="width:250px"></td>
</tr>
<tr>
<td><p>연락처</p></td>
<td><input type="text" name="pntext"></td>
</tr>
<tr>
<td colspan="2"><button id="register" style="margin-right:5px" >등록</button><button id="listview" onclick="substr()">조회</button></td>
</tr>
</table>
</form>
</body>
<script>
$("#listview").click(function(){
$("#form").attr('action','userlist.jsp');
document.idtextf.submit();
});
$("#register").click(function(){
$("#form").attr('action','registerprocess.jsp');
document.idtextf.submit();
});
</script>
-> <body> 부분 안에 테이블의 요소가 들어가고
<form>태그로 submit 할 요소들을 감싼다. <imput>태그 안에 name을 주어 나중에 받을 값들을 분류한다. 처음에 <form>태그를 <tr>안에 어중간하게 넣어놨더니 오류가 발생한다. <form>태그는 위치도 중요하다.
그다음 jQuery를 이용해 한가지 폼에서 두가지 action을 취해서 등록 버튼은 등록페이지로 조회 버튼은 조회페이지로 가게 만들었다. 처음에 이 페이지에서 등록을 하려고 했으나 정보를 받는 과정에서 오류가 생겨 executeUptate()문에 문제가 생겼다. 너무 골치가 아파서 그만 두고 새로운 페이지 만들어서 거기서 등록 작업을 걸치고 다시 이 페이지로 돌아오게 만들었다. 그리고 가장 시간이 많이 걸린 것은 한글이 깨진다는 것이다.
request.setCharacterEncoding("UTF-8");
이를 추가해주면 post 받는 한글데이터는 깨지지 않지만 등록하는 데이터는 여전히 깨진다. 즉 등록부분을 또 찾아서 수정해줘야하는데 아직 못 해결했다. 추후 수정해야겠다. 이거 찾는 것도 오래 걸렸다. mysql은 url 부분에서 수정하면 금방 될 것 같던데.. oracle은 자료도 mysql에 비해 작을 뿐더러 jdbc 예제에 적용해도 되는지 아닌지 판단하는데 너무 오래걸렸다.(다 내가 생각하는게 오래 걸린다ㅎ..)
<%@ page language="java" import="java.sql.*" 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>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
Connection dbconn=DriverManager.getConnection(url,"edujh","1234");
Statement stmt=dbconn.createStatement();
request.setCharacterEncoding("UTF-8");
String pid=request.getParameter("idtext");
String ppw=request.getParameter("pwtext");
String cnm=request.getParameter("nmtext");
String cem=request.getParameter("emtext");
String ctl=request.getParameter("pntext");
stmt.executeUpdate("INSERT INTO USERLIST VALUES('"+pid+"', '"+ppw+"', '"+cnm+"', '"+cem+"', '"+ctl+"')");
stmt.close();
dbconn.close();
%>
<h1 ><button onclick="pagemoving()"><%-- <jsp:forward page="useregister.jsp"></jsp:forward> --%>돌아가기</button>등록 되었습니다.</h1>
</body>
<script>
$('h1 button').appendTo('<jsp:forward page="useregister.jsp"></jsp:forward>');
</script>
</html>
등록페이지 부분이다. 이부분은 따로 ui는 있는데 엄청 간단하다. 여기서 등록만 처리하고 다시 등록/조회 페이지로 돌아오려 했으나 forward()방식을 이용하는데 (이것도 찾아서 적용하는데 애먹었다), 이걸 jsp 형식으로 입력해 넣었더니 등록하자마자 바로 사이트가 넘어온다. 이부분을 jQuery로 해결하려 했으나 전혀 들지 않고 바로 페이지가 변경된다. 이 부분도 수정 해야한다.
<%@ page language="java" import="java.sql.*" import="java.lang.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
Connection conn=DriverManager.getConnection(url,"edujh","1234");
Statement psmt=null;
String sQuery="";
request.setCharacterEncoding("UTF-8");
String[] query=new String[4];
if(request.getParameter("idtext")!=""){
query[0]="P_ID like '%"+request.getParameter("idtext")+"%'";
}else{
query[0]=null;
}
if(request.getParameter("nmtext")!=""){
query[1]="C_NAME like '%"+request.getParameter("nmtext")+"%'";
}else{
query[1]=null;
}
if(request.getParameter("emtext")!=""){
query[2]="C_EMAIL like '%"+request.getParameter("emtext")+"%'";
}else{
query[2]=null;
}
if(request.getParameter("pntext")!=""){
query[3]="C_TEL like '%"+request.getParameter("pntext")+"%'";
}else{
query[3]=null;
}
for(int i=0; i<4; i++){
if(query[i]!=null){
sQuery+=" "+query[i]+" and";
}
}
if(sQuery.substring(sQuery.length()-3,sQuery.length()).equals("and")){
sQuery=sQuery.substring(0,sQuery.length()-3);
}
//submit로 받은 값이 없을 경우에 예외처리가 들어가야함.
psmt=conn.createStatement();
ResultSet rs=psmt.executeQuery("SELECT * FROM USERLIST WHERE "+sQuery+" ");
String pid=null;
String cnm=null;
String cem=null;
String cpm=null;
System.out.println(sQuery);
System.out.println(sQuery.substring(sQuery.length()-3,sQuery.length()));
%>
<!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>
<style>
table, tr, td{
height:26px;
border: 1px solid skyblue;
border-collapse:collapse;
}
tr td:nth-child(3){
width:360px;
}
tr td{
width:180px;
}
h1{
width:913px;
text-align:center;
border-bottom: 1px dotted red;
margin:none;
margin-top:20px;
margin-bottom:2px;
padding-bottom:18px;
}
h4{
width:913px;
text-align:center;
border-top: 1px dotted red;
margin:none;
margin-top:2px;
}
</style>
</head>
<body>
<h1>회 원 목 록 조 회</h1>
<table>
<tr>
<td>회원아이디</td>
<td>회원이름</td>
<td>이메일</td>
<td>연락처</td>
</tr>
<%
while(rs.next()){
pid=rs.getString("p_id");
cnm=rs.getString("C_NAME");
cem=rs.getString("C_EMAIL");
cpm=rs.getString("C_TEL");
%>
<tr>
<td><%=pid%></td>
<td><%=cnm%></td>
<td><%=cem%></td>
<td><%=cpm%></td>
</tr>
<% }
rs.close();
psmt.close();
conn.close();
%>
</table>
<h4>HRDKOREA Copyright@2015 All right reserved, Human Resourses Development Service of Korea</h4>
<h1><%=sQuery%></h1>
</body>
</html>
이 부분은 받은 값을 이용하여 조회하는 부분이다. 받는 값이 하나라면 단순하게 excuteQuery()부분에 ~where '"+ 받는값 +"'"~ 이런식으로 해주면 되지만, 받는 값이 불규칙하기 때문에 이거를 어떻게 처리해야하나 고민을 막했던 것 같다. 여기 부분이 정말 오래 걸렸다. 저 위에 인코딩이랑 비슷하게 시간이 걸렸다.
받는 값이 null이 아니라면 string 배열에 넣고 이를 다시 문자열에 and와 함께 넣어준다.(처음에 , 인줄 알고 , 넣고 왜 안되는건가 고민을 많이 했다) 그리고 마지막에 붙은 and는 오류를 띄우는데 한 몫 함으로 뒤에서 3글자를 문자열에서 떼와서 and인지 아닌지 확인 후에 and라면 뒤에 3글자를 지워주고 executeQuery()에 명령어 부분과 함께 넣어주면 된다. 코드가 무식하게 긴 것 같은데 사실이다. 나중에 좀 더 좋은 방법 있으면 수정해야겠다. 글이 거지같이 두서가 없이 느껴진다면 막 써서 그렇다. 맞춤법도 많이 틀린 것 같은데, 그냥 올리겠다. 나만 볼 것이기 때문이다.
밑에 P_ID like 뭐시기 있는 건 왜 쿼리가 틀렸을까 고민한 흔적이다. 모르겠으면 의심가는 부분을 출력해봐야한다. 처음에 console로 하려다가 포기하고 저렇게 눈에 잘띄게 만들어서 출력해놨는데 마지막까지 내비뒀다. 지우기만하면 되지만 이것도 흔적이므로 내비둔다.
p.s 실험해보니 정상적으로 한글데이터가 들어갔다. 저것만 해도 되나보다.
'공부!' 카테고리의 다른 글
2- 목록 조회 게시판 만들기 (0) | 2018.01.02 |
---|---|
JSP 로그인 상태 유지 (0) | 2017.12.28 |
JSP 기초 (0) | 2017.12.21 |
JSP alert 함수, confirm 함수, prompt 함수 (0) | 2017.12.20 |
jdbc 데이터 전송-받기 (0) | 2017.12.14 |