본문 바로가기

개발하자/ajax&json

$.toJSON(obj)을 이용하여 db에 id,pw,addr,tel insert하기

a.jsp

========================

<%@ page language="java" contentType="text/html; charset=EUC-KR"
 pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script src="js/jquery.json-2.3.js"></script>
<style type="text/css">
 td { border:2px solid green; }
</style>
 </script>
<script>
$(document).ready(function(){
 $("#add").click(function(){
 var buffer=[];
 $("tr").eq(0).children().each(function(i){
 buffer.push($(this).text());
 });

 var obj={"id":"","pw":"","addr":"","tel":""};
 var cnt=0;
 for(var key in obj){
 obj[key]=buffer[cnt++];
 }
 //alert(buffer.join(","));
 //alert(obj.id);
 var str='{"member":'+$.toJSON(obj)+'}';
 
 $.ajax({
  url:"b.jsp",
  data:{"aa":str},
  cache:false,
  success:function(data){
 alert("성공");
  }
  });
 });
});
</script>
</head>
<body>
 <table>
 <tr><td>aa</td><td>bb</td><td>cc</td><td>dd</td></tr>
 </table>
 <input type="button" value="추가" id="add">
</body>
</html>

 

b.jsp

====================================

<%@ page language="java" contentType="text/html; charset=EUC-KR"
 pageEncoding="EUC-KR"%>
<%@ page import="java.util.*" %>
<%@ page import="kr.co.seoulit.member.dao.*" %>
<%@ page import="kr.co.seoulit.member.to.*" %>
<%@ page import="net.sf.json.*"%>
<%
 String str=request.getParameter("aa");

 JSONObject jsonObject=JSONObject.fromObject(str).getJSONObject("member");
 MemberBean bean=(MemberBean)JSONObject.toBean(jsonObject,MemberBean.class);
 MemberDAOImpl.getInstance().insertMember(bean);

%>

 

MemberDAOImpl.java

===========================================

 public int insertMember(MemberBean m){
  Connection con = null;
  PreparedStatement pstmt = null;
  int rs;
  try {
   StringBuffer query = new StringBuffer();
   query.append("insert into member values(?,?,?,?)");
   DataSource dataSource=ServiceLocator.getInstance().getDataSource("jdbc/myoracle");
   con = dataSource.getConnection();
   pstmt = con.prepareStatement(query.toString());
   pstmt.setString(1,m.getId());
   pstmt.setString(2,m.getPw());
   pstmt.setString(3,m.getAddr());
   pstmt.setString(4,m.getTel());
   rs=pstmt.executeUpdate();
   return rs;
  } catch(Exception sqle) {
   throw new DataAccessException(sqle.getMessage());   
  } finally {
   try{
   if(pstmt!=null){ pstmt.close(); pstmt=null; }
   if(con!=null){ con.close(); con=null; }
   }catch(Exception e){throw new DataAccessException(e.getMessage()); }
  }
 }