본문 바로가기

[Spring 기능구현] 차트 형식으로 출력하기-highcharts

인포꿀팁 발행일 : 2020-12-17

www.highcharts.com/

 

Interactive JavaScript charts for your webpage | Highcharts

"I absolutely LOVE Highcharts & maps, very cool! We use it for a web metrics dashboard, which is shared with internal marketing stakeholders. The tool is brilliant and the API documentation is super-helpful. I set up some basic, manual reports using Highch

www.highcharts.com

위 사이트에서 제공하는 자바스크립트 라이브러리를 통해 나름 간단하게 데이터를 차트형식으로 출력할수 있다.

 

 

1)먼저 위 사이트에서 view option에서 데이터를 어떤 방식으로 받아오는지 체크한다.

내가 나타낼 차트 방식은 아래와 같은 방식이다.

여기서 series에 해당하는 게 넘겨받는 데이터이다.

위와 같이 배열로 넘어가는 걸 볼 수 있다.

 

2)컨트롤러에 데이터를 map으로 put하여 이를 배열로 받을 수 있는 list에 넣는다.

이 리스트의 이름은 series로 설정한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    @RequestMapping("line1")
    @ResponseBody
    public Map<String, Object> line1() throws Exception{
        Map<String, Object> model = new HashMap<>();
        
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name""서울");
        map.put("data"new double[] {-0.9,1.0,6.3,13.3,18.9,23.6,25.8,26.3,22.4,15.5,8.9,1.6});
        
        list.add(map);
        
        model.put("series", list);
        
        return model;
    }
cs

 

3) view단에서 제이쿼리를 통해 ajax 처리 결과를 json으로 반환받는다.

x축과 y축에 노출될 이름들을 설정정하고 series에 넘겨온 데이터를 반환한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(function(){
    var url="${pageContext.request.contextPath}/hchart/line1";
    
    // $.getJSON : AJAX 처리결과를 json으로 반환 받는 함수
    $.getJSON(url, function(data){
        //console.log(data);
        Highcharts.chart("lineContainer1",{
            title:{
                text: "서울 평균 기온"
            },
            
            xAxis : {
                categories:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"]
            },
            
            yAxis : {
                title:{
                    text:"기온(C)"
                }
            },
            series: data.series
        });
    });
});
cs

댓글