'프로그래밍/Json'에 해당되는 글 1건

  1. 2014.11.28 JSP 에서 json 파일로 mybatis로 연결후 AJAX 사용까지
728x90

무조건 json 파일 형식으로만 파일을 뽑으면 된다.

나는 그래서 jstl을 사용하여 Json 파일을 만들어봤다.


기본적으로 이동은

jsp <--> Dao <--> Manager <--> Mapper 로 이동한다.


JSON 으로 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<%@page import="dto.Chap07Dto"%>
<%@page import="dao.Chap07Dao"%>
<%@page import="java.util.List"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
 
<%-- ---------------------------------  jSon용으로 출력 -------------------------------------------%>
    
    <jsp:useBean id="dto" class="dto.Chap07Dto">    <%-- dto 객체 생성 --%>
        <jsp:setProperty property="*" name="dto"/>    <%-- dto 객체 다 받아옴 --%>
    </jsp:useBean>
    <%
        Chap07Dao dao = new Chap07Dao();    // dao객체 생성
        List<Chap07Dto> list = dao.getList();    // list변수에 dao의 getList 사용
        request.setAttribute("list", list);    
    %>
    
            <%-- json용으로 뿌려준다 --%>
        
        [
        <c:forEach items="${list }" var="v1" varStatus="i">    <%-- 위에서 만들 list를 뿌려줄 준비 --%>
            <c:if test="${!i.first }">,</c:if>    <%-- 만약 i 가 처음이 아니면 , 을 뿌려준다. --%>
            {
                "id" : "${v1.id }",
                "name" : "${v1.name }",
                "content" :"${v1.content }"
            }
        </c:forEach>
        ]



여기서 중요한건 25 ~ 34줄이다. 

나 같은 경우는

 [ { "id" : "1", "name" : "name", "content" :"content" } , { "id" : "2", "name" : "하이", "content" :"테스트1" } , { "id" : "3", "name" : "jsp", "content" :"콘텐츠" } ]

이런식으로 나온다.


14 ~21줄은 dao에서 mybatis를 거쳐 db의 자료를 가져오는 작업이다.



Ajax에서의 사용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            // $.ajax()에서 반복 사용하는 속성을 상단에 설정 후 $.ajax에서 상속받아 사용
            $.ajaxSetup({
                url: "./commentlist.jsp",
                dataType: "json"
            });
            
            $.ajax({
                success: function (data) {
                    $.each(data, function () {
                        $('#tblList').append("<tr><td>" + this.id + "</td><td>"
                            + this["name"] + "</td></tr>");
                    });
                }
            });
        });
    </script>
</head>
<body>
    <table id="tblList" border="1"></table>
</body>
</html>


url = json파일의 위치



chap07Dao.java   -  Dao


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package dao;
 
import java.util.List;
 
import mybatis.Chap07Manager;
 
public class Chap07Dao
{
 
    public List getList() 
    {
        List list = Chap07Manager.getList();
        return list;
    }
}
 





Chap07Manager.java   -  Manager



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package mybatis;
 
import dto.Chap07Dto;
 
import java.io.Reader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.sql.SQLException;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
public class Chap07Manager {
 
    private static SqlSessionFactory sqlMapper;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis/SqlMapConfig.xml"); // classes
                                                                                // 폴더안에있으면
                                                                                // 경로가
                                                                                // 없어도된다.
            sqlMapper = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            // Fail fast.
            throw new RuntimeException(
                    "Something bad happened while building the SqlMapClient instance."
                            + e, e);
        }
    }
 
    public static List getList() 
    {
        System.out.println("Chap07Manager 의 getList");
        List list = null;
        
        SqlSession session = sqlMapper.openSession();
        list = session.selectList("getList");
        session.commit();
        session.close();
        return list;
    }
    
    
 
    
 
}
 



Chap07Mapper.xml   -  Mapper


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8" ?>
 
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="mybatis.Chap07Mapper">
 
  
  <!-- Select with no parameters using the result map for Account class. -->
  <select id="getList" resultType="Chap07Dto">    <!-- value값이 resultMap 값으로 사용가능  //만약 SqlMapConfig에서 typeAliases를 지정해주지않았으면 패키지이름까지 다 써줘야된다.-->
    select * from COMMENT order by ID
  </select>
  
  
  
  
 
</mapper>


Posted by 앗뜨거
,