• Home
  • About
    • Young's Github Pages photo

      一日不作一日不食

    • About
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Java EE 정리 24

01 Apr 2019

Reading time ~5 minutes

Java EE 정리 24 - AJAX(3), Model2(1)


JSONArray Parsing

[{"name":"노진경", "age":30 },
 {"name":"김정윤", "age":20 },
 {"name":"공선의", "age":25 },
  • AJAX로 요청 후 반환되는 JSONArray가 위와 같을 때
$.ajax({
    url:"URL",
    data:QueryString,
    type:"get|post",
    error:function(xhr) {
        ...
    },
    success:fucntion(jsonArry) {
        $.each(jsonArry, function(idx,jsonObj) {
            // jsonObj.name, jsonObj.age로 값을 파싱해서 사용
        }
    }
});
  • AJAX를 사용한 JSONArray Parsing 예
<!-- json_array_result.jsp -->
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
      String[] nameArr = {"김희철","김정윤","노진경","공선의"};
      String[] addrArr = {"서울시 동작구","서울시 역삼동","서울시  방화동","서울시 신정동"};
      int[] ageArr = {30,28,31,29};
      JSONArray jsonArr = new JSONArray();
      
      JSONObject jsonObj = null;
      for(int i=0; i < nameArr.length; i++) {
            jsonObj = new JSONObject();
            jsonObj.put("name", nameArr[i]);
            jsonObj.put("addr", addrArr[i]);
            jsonObj.put("age",ageArr[i]);
            
            jsonArr.add(jsonObj);
      }
      
      out.println(jsonArr.toJSONString());
%>

01

<!-- ajax_json_array.jsp -->
...
<script type="text/javascript">
      $(function() {
            
            $("#getJsonArr").click(function() {
                  $.ajax({
                        url:"json_array_result.jsp",
                        type:"get",
                        dataType:"json",
                        error:function(xhr) {
                              alert(xhr.status + "/" + xhr.statusText);
                        },
                        success:function(json_array) {
                              var output="<ul>";
                              $.each(json_array, function(idx, json_obj)  {
                                    output+="<li>"+json_obj.name
                                    +"/"+  json_obj.age +"/"
                                    + json_obj.addr +"</li>";
                              });
                              output+="</ul>";
                              
                              $("#jsonArrDiv").html(output);
                        }
                  });   
            });
      }); // ready
</script>
...
<div>
      <a href="#void" id="getJsonArr">값 얻기</a>
</div>
<div id="jsonArrDiv"></div>
...

02

  • DB, AJAX를 이용한 JSONArray Parsing 예
<!-- json_db.jsp, 3월 28일에 만든 DB에서 조회 후 JSON반환하는 메서드 사용 -->
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="date0328.JsonService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
      String deptno = request.getParameter("deptno");
      
      JSONObject empData = null;
      try {
            int intDeptno = Integer.parseInt(deptno);
            JsonService js = new JsonService();
            empData = js.searchEmpData(intDeptno);
            
      } catch(NumberFormatException nfe) {
            // 성공하든 실패하든 무조건 JSON이 나와야 한다.
            empData = new JSONObject();
            empData.put("result",false);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
            empData.put("pubDate", sdf.format(new Date()));
            empData.put("resultData",null);
      }
      out.println(empData.toJSONString());
%>
<!-- ajax_json_db.jsp -->
...
<script type="text/javascript">
      $(function() {
            
            $("#btn").click(function() {
                  var deptno = $("#deptno").val();
                  
                  if(deptno == "") {
                        alert("부서번호는 필수 입력입니다.");
                        $("#deptno").focus();
                        return;
                  }
                  
                  var queryString = "deptno="+deptno;
                  
                  $.ajax({
                        url:"json_db.jsp",
                        type:"get",
                        data:queryString,
                        dataType:"json",
                        error:function(xhr) {
                              alert(xhr.status());
                        },
                        success:function(jsonObj) {
                              var result = jsonObj.result;
                              
                              if (result) {
                                    var  output="<strong>"+deptno+"</strong>번 부서사원 조회 결과<br/>";
                                    var jsonArr=jsonObj.resultData;
                                    
                                    $.each(jsonArr, function(idx,  jsonEmpData) {
                                          output+="<div  style='margin-bottom:10px;'>"
                                                +"<table  border='1'><tr><td width='100'>사원번호</td><td width='50'>"
                                                +jsonEmpData.empno+"</td><td width='120'>사원명</td><td  width='120'>"
                                                +jsonEmpData.ename+"</td><td width='120'>입사일</td><td  width='150'>"
                                                +jsonEmpData.hiredate+"</td></tr>"
                                                +"<tr><td  width='80'>연봉</td><td>"+"<input type='text' name='sal' value='"
                                                +jsonEmpData.sal+"'/></td><td>직무</td><td colspan='3'>"
                                                +"<input type='text'  name='job' value='"+jsonEmpData.job+"'/>"
                                                +"</td></tr></table></div>";
                                    });
                                    
                                    $("#empView").html(output);
                              } else {
                                    var img="<img  src='../common/images/sist_log.jpg'/>"
                                    img += "<br/>잘못된 입력값이거나  잠시 문제가 발생하였습니다.";
                                    $("#empView").html(img);
                              }
                        }
                  });
            });
      }); // ready
</script>
...
<div>
      <label>부서번호:</label>
      <input type="text" name="deptno" id="deptno" class="inputBox"/>
      <input type="button" value="사원조회" id="btn" class="btn"/>
</div>
<div id="empView">
...

03

DB, AJAX사용 ID 중복 검사하기

  • DB를 바로 쓰지 않고 Service를 거쳐서 사용
// servlet_prj에서 사용했던 WebMemberDAO 사용
public class WebMemberDAO {
      private static WebMemberDAO wm_dao;
      private WebMemberDAO() {}
      public static WebMemberDAO getInstance() {
            if (wm_dao == null) {
                  wm_dao = new WebMemberDAO();
            }
            return wm_dao;
      }
      // DBCP 사용 Connection 얻는 메소드
      private Connection getConn() {
            Connection con = null;
            try {
                  // 1. JNDI 사용객체 생성
                  Context ctx = new InitialContext();
                  
                  // 2. DBCP에서 DataSource 얻기
                  DataSource ds =  (DataSource)ctx.lookup("java:comp/env/jdbc/jsp_dbcp");
                  
                  // 3. DataSource에서 Connection 얻기
                  con = ds.getConnection();
            } catch (NamingException e) {
                  e.printStackTrace();
            } catch (SQLException e) {
                  e.printStackTrace();
            }
            
            return con;
      }
      
      // 아이디가 존재하는지 중복 검사
      public boolean selectId(String id) throws SQLException {
            boolean flag = false;
            
            Connection con = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            
            try {
                  // 1. JNDI 사용객체 생성
                  // 2. DBCP에서 DataSource 얻기
                  // 3. DataSource에서 Connection 얻기
                  con = getConn();
                  // 4. 쿼리수행 객체 얻기
                  String selectId = "SELECT id FROM web_member WHERE  id=?";
                  pstmt = con.prepareStatement(selectId);
                  pstmt.setString(1, id);
                  
                  // 5. 쿼리 실행 결과 얻기
                  rs = pstmt.executeQuery();
                  
                  flag = !rs.next(); // 조회되는게 있는지 없는지 여부만  판단
                  
            } finally {
                  // 6. 연결 끊기
                  if (rs != null) { rs.close(); }
                  if (pstmt != null) { pstmt.close(); }
                  if (con != null) { con.close(); }
            }
            return flag;
      }
}
// WebMemberService
public class WebMemberService {
      
      public JSONObject searchId(String id) {
            JSONObject json = new JSONObject();
            
            WebMemberDAO wm_dao = WebMemberDAO.getInstance();
            boolean flag = false;
            try {
                  flag = wm_dao.selectId(id);
            } catch (SQLException e) {
                  e.printStackTrace();
            }
            
            // DB조회 결과를 JSONObject에 추가
            json.put("idResult", flag);
            
            return json;
      }
}
<!-- json_dup_id.jsp -->
<%
      String id = request.getParameter("id");
      WebMemberService wms = new WebMemberService();
      JSONObject json = wms.searchId(id);
      out.println(json.toJSONString());
%>

05

  • 서버에서 모두 처리 후 callback 함수가 호출되어야 한다면 async를 false로 동기처리한다.
<!-- ajax_json_dup_id -->
...
<script type="text/javascript">
     $(function() {
          $("#id").keyup(function() {
                 var id = $("#id").val();
                 if(id.length > 2) { // 세자부터 체크
                       if(id.trim() == "") {
                            $("#idResult").text("아이디를  입력해주세요!").css("color","#FF0000");
                             $("#id").val("");
                             return;
                       }
                 
                      // ID중복확인을 비동기로 처리
                       $.ajax({
                             url:"json_dup_id.jsp",
                             type:"get",
                             async:false,
                             data:"id="+id,
                             dataType:"json",
                             error:function(xhr) {
                                   alert("서비스가 원활하지 못합니다.  잠시 후 다시 시도해주세요.");
                                   console.log(xhr.status+" /  "+xhr.statusText);
                             },
                            success:function(jsonObj) {
                                   var output =  "[<strong>"+id+"</strong>]는 사용불가";
                                   var color="#FF0000";
                                   if (jsonObj.idResult) {
                                         output =  "[<strong>"+id+"</strong>]는 사용가능";
                                         color="#0000FF";
                                   }
                                   $("#idResult").html(output).css("color",color);
                                   for(var i=0; i<4; i++) { // 반짝반짝
                                         $("#idResult").fadeIn(1000).fadeOut(1000).fadeIn(1000);
                                   }
                             }
                       });  
                 }
           });
     }); // ready
</script>
...
<strong>회원가입</strong><br/>
<table>
     <tr>
           <td>아이디</td>
           <td width="500"><input type="text" name="id"  class="inputBox" id="id"/>
           <span id="idResult"></span><br/>
           <span style="color:#333">아이디는 3자이상 입력하셔야  합니다.</span>
           </td>
     </tr>
</table>
...

06

...
                 }); // ajax
           } else {
                 // 3자보다 적을 때
                 if (id.length < 3) {
                       var output = "아이디를 입력해주세요.";
                       var color="#00FF00";
                       $("#idResult").html(output).css("color",color);
                 }
           }
     });
}); // ready

07

Model 2 개발 방식

  • 유지보수 성능 향상
  • 업무구분이 쉽다
    • 코드를 분리하여 제작
  • 개발 속도가 느리다
  • 파일 관리가 어렵다
  • 에러처리가 어렵다
  • Servlet + DAO + JSP로 구분되어 작성

08

Model 2의 각 역할

  • Main Controller : 진입점(무조건 하나)
    • Servlet : 모든 요청을 받아 해당요청을 처리할 수 있는 Controller를 실행
      • Controller 실행 결과를 보여줄 View로 이동
  • Controller
    • 일반 클래스
    • Spring MVC 이전 이름은 Action
    • Web Parameter를 처리
    • 관계 유지
    • View 페이지명 반환
    • 이동방식 결정
    • Service 클래스 사용
      • Service가 처리한 결과를 받아 Main Controller에 전달
  • Service
    • 일반 클래스
    • 업무로직에 대한 처리
    • DAO단의 사용
      • DB처리 결과를 받아 사용
  • DAO
    • 일반 클래스
    • DB에 업무를 처리
  • View
    • JSP
    • 업무 처리한 결과를 받아서 접속자가 사용할 화면을 만드는 일

Model 2 흐름

09



Java EEAJAXModel2