宇而靜...

JFreeChart X/Y Chart 예제 본문

Development/Java

JFreeChart X/Y Chart 예제

우™ 2007. 6. 18. 23:36

package itea.Chart;

import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import org.jfree.chart.*;
import org.jfree.data.xy.*;
import org.jfree.chart.plot.*;
/**
 * Servlet implementation class for Servlet: XYChartTest
 *
 */
 public class XYChartTest extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
 
 ///Fields
 DataSource ds;
 Connection con;
 
 public XYChartTest() {
  super();
  try{
   Context initContext = new InitialContext();
   Context envContext  = (Context)initContext.lookup("java:/comp/env");
   // server.xml(or context.xml)&web.xml에 설정한 JNDI 이름
   // 즉, "jdbc/myoracle"을 일치시켜 줍니다.
   ds = (DataSource)envContext.lookup("jdbc/myoracle");
   
  }catch(Exception e){
   e.printStackTrace();
  }
 }    

 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try {
   con = ds.getConnection();
   String sql="select value from lge";
   PreparedStatement st = con.prepareStatement(sql);
   ResultSet rs = st.executeQuery();
   XYSeries vs = new XYSeries("주가동향");
   int x = 1;
   while(rs.next()){
    vs.add(x, rs.getInt(1));
    x+=1;
   }
   XYSeriesCollection sc = new XYSeriesCollection(vs);
   JFreeChart chart = ChartFactory.createXYLineChart("주가동향",
     "날짜", "가격", sc, PlotOrientation.VERTICAL, true, true, true);
   ServletOutputStream out = response.getOutputStream();
   ChartUtilities.writeChartAsPNG(out, chart, 400, 400);
   st.executeUpdate();
   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }          
}

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

데이터 테이블

 

create table lge(
 num number(7) primary key,
 value number(9) not null);

 

insert into lge(num, value) values(1, 510);
insert into lge(num, value) values(2, 515);
insert into lge(num, value) values(3, 400);
insert into lge(num, value) values(4, 450);
insert into lge(num, value) values(5, 520);
insert into lge(num, value) values(6, 523);
insert into lge(num, value) values(7, 540);
insert into lge(num, value) values(8, 545);
insert into lge(num, value) values(9, 510);

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