jsp提供了很多简单实用的工具,其中包括从数据库中读出数据,发送数据,并能够把结果显示在一个饼状图形。现在让我们看看这一简单而实用的方法。
你所需要的东西
为了能正确运行这一文章相关的范例,你必须需要jdk 1.2或更高的版本、一个关系数据库管理系统、一个jsp网络服务器。我都是在tomcat调试这些例子,同时我也使用了sun java 2 sdk发布的com.sun.image.codec.jpegclasses。
数据库设计
假设你在一家从事销售新鲜水果的公司上班,公司出售的水果包括:苹果、桔子、葡萄。现在你的老板想用一个饼状图形显示每一种水果的总出售量,饼状图形能使每一种产品的销售情况一目了然,老板可以迅速掌握公司的产品成交情况。
表a使用了本文中的两种数据库列表。第一种列表(products)包含所有销售产品的名称;第二种列表(sales)包含每一种产品对应的销售量。
listing a
database design
---------------
p_products table
----------------
productid int (number) not null
productname string (varchar) not null
p_sales table
-------------
saleid int (number) not null
productid int (number) not null
amount float not null
产品(products)列表包含productid和productname两个域。销售(sales)列表包含saleid, productid,以及总额。销售列表中的productid提供了这两个列表之间的关联。销售列表中的总额包含了每一次出售的现金数额,这些数额以浮点型数据出现。
表b中的getproducts()方法连接了两个数据库,并把所有的产品名称保存在数组中:
listing b
| //////////////////////////////////////////////////////////// //get products from the database as a string array //////////////////////////////////////////////////////////// public string[] getproducts() { string[] arr = new string[0]; connection con; statement stmt; resultset rs; int count = 0; string sql = "select * from p_products order by productid"; try { //load driver: class.forname(driver); //connect to the database with the url con = drivermanager.getconnection(dburl , dbuid , dbpwd); stmt = con.createstatement(); //get resultset rs = stmt.executequery(sql); //count the records while(rs.next()) {count++;} //create an array of the correct size arr = new string[count]; //get resultset (the portable way of using rs a second time) rs = stmt.executequery(sql); while(rs.next()) { arr[rs.getint("productid")] = rs.getstring("productname"); } stmt.close(); con.close(); } catch (java.lang.exception ex) { arr[0] = ex.tostring(); } return arr; } |
| arr[rs.getint("productid")] = rs.getstring("productname"); |
| //////////////////////////////////////////////////////////// //get the sales totals from the database //////////////////////////////////////////////////////////// public float[] getsales(int products) { float[] arr = new float[products]; connection con; statement stmt; resultset rs; int count = 0; string sql = "select productid, amount from p_sales"; try { //load driver: class.forname(driver); //connect to the database with the url con = drivermanager.getconnection(dburl , dbuid , dbpwd); stmt = con.createstatement(); //get resultset rs = stmt.executequery(sql); while(rs.next()) { int product = rs.getint("productid"); //check that the productid is valid if (product >= 0 && product < products) { //add to product total arr[product] += rs.getfloat("amount"); count++; } } stmt.close(); con.close(); } catch (java.lang.exception ex) { arr[0] = -1.0f; } return arr; } |
| int product = rs.getint("productid"); arr[product] += rs.getfloat("amount"); |
| color piecolorarray[] = {new color(210,60,60), new color(60,210,60)…} |
| curpiecolor++; if(curpiecolor >= piecolorarray.length) {curpiecolor = 0;} |
| renderinghints renderhints = new renderinghints(renderinghints.key_antialiasing, renderinghints.value_antialias_on); g2d.setrenderinghints(renderhints); |
| g2d.fillarc(x_position, y_position, width, height, startangle, sweepangle); |
| g2d.setcolor(pc.getpiecolor()); |
| salestotal += sales[i]; |
| float perc = (sales[i]/salestotal); |
| int sweepangle = (int)(perc * 360); |
| <%@ page language="java" %> <%@ page import="java.io.outputstream" %> <%@ page import="java.sql.*" %> <%@ page import="java.awt.*" %> <%@ page import="java.awt.geom.*" %> <%@ page import="java.awt.image.bufferedimage" %> <%@ page import="com.sun.image.codec.jpeg.*" %> <%! //////////////////////////////////////////////////////////// // piecolors class manages the colors used in the pie chart //////////////////////////////////////////////////////////// class piecolors { color piecolorarray[] = { new color(210,60,60), new color(60,210,60), new color(60,60,210), new color(120,60,120), new color(60,120,210), new color(210,120,60) }; int curpiecolor = 0; public color getpiecolor() { return piecolorarray[curpiecolor]; } public void setnewcolor() { curpiecolor++; if(curpiecolor >= piecolorarray.length) {curpiecolor = 0;} } } %> <%! string driver = "com.mysql.jdbc.driver"; string dburl = "jdbc:mysql://localhost/articles"; string dbuid = "myuid"; string dbpwd = "mypwd"; //////////////////////////////////////////////////////////// // get the products from the database as a string array //////////////////////////////////////////////////////////// public string[] getproducts() { string[] arr = new string[0]; connection con; statement stmt; resultset rs; int count = 0; string sql = "select * from p_products order by productid"; try { //load driver: class.forname(driver); //connect to the database with the url con = drivermanager.getconnection(dburl , dbuid , dbpwd); stmt = con.createstatement(); //get resultset rs = stmt.executequery(sql); //count the records while(rs.next()){count++; } //create an array of the correct size arr = new string[count]; //get resultset (the most portable way of using rs a second time) rs = stmt.executequery(sql); while(rs.next()) { arr[rs.getint("productid")] = rs.getstring("productname"); } stmt.close(); con.close(); } catch (java.lang.exception ex) {arr[0] = ex.tostring();} return arr; } //////////////////////////////////////////////////////////// //get the sales totals from the database //////////////////////////////////////////////////////////// public float[] getsales(int products) { float[] arr = new float[products]; connection con; statement stmt; resultset rs; string sql = "select productid, amount from p_sales"; try { //load driver: class.forname(driver); //connect to the database with the url con = drivermanager.getconnection(dburl , dbuid , dbpwd); stmt = con.createstatement(); //get resultset rs = stmt.executequery(sql); while (rs.next()) { int product = rs.getint("productid"); //check that the productid is valid if (product >= 0 && product < products) { //add to product total arr[product] += rs.getfloat("amount"); } } stmt.close(); con.close(); } catch (java.lang.exception ex) {arr[0] = -1.0f; } return arr; } %> <% //get an array that contains the product names string products[] = getproducts(); //read the data and store the totals in an array float sales[] = getsales(products.length); //declare piecolors piecolors pc = new piecolors(); //colors color dropshadow = new color(240,240,240); //inner padding to make sure bars never touch the outer border int inneroffset = 20; //set the graph's outer width & height int width = 400; int height = 200; int pieheight = height - (inneroffset * 2); int piewidth = pieheight; //to make a square (circular) pie int halfwidth = width/2; //width of the inner graphable area int innerwidth = width - (inneroffset * 2); //graph dimensions dimension graphdim = new dimension(width,height); rectangle graphrect = new rectangle(graphdim); //border dimensions dimension borderdim = new dimension(halfwidth-2,height-2); rectangle borderrect = new rectangle(borderdim); ///////////////////////////////////////////////////////////// //set up the graph //////////////////////////////////////////////////////////// //set content type response.setcontenttype("image/jpeg"); //create bufferedimage & graphics2d bufferedimage bi = new bufferedimage(width, height, bufferedimage.type_int_rgb); graphics2d g2d = bi.creategraphics(); // set antialiasing renderinghints renderhints = new renderinghints( renderinghints.key_antialiasing,renderinghints.value_antialias_on); g2d.setrenderinghints(renderhints); //set graph background color to white: g2d.setcolor(color.white); g2d.fill(graphrect); //draw black border g2d.setcolor(color.black); borderrect.setlocation(1,1); g2d.draw(borderrect); //now draw border for legend borderrect.setlocation((width/2) + 1,1); g2d.draw(borderrect); //////////////////////////////////////////////////////////////////// //draw data onto the graph: //////////////////////////////////////////////////////////////////// int x_pie = inneroffset; int y_pie = inneroffset; int border = 20; //main chart ellipse //ellipse2d.double el = new ellipse2d.double(x_pie, y_pie, piewidth, pieheight); ellipse2d.double elb = new ellipse2d.double(x_pie - border/2, y_pie - border/2, piewidth + border, pieheight + border); //shadow g2d.setcolor(dropshadow); g2d.fill(elb); //border g2d.setcolor(color.black); g2d.draw(elb); ///////////////////////////////////////////////////////////////// //calculate the total sales ///////////////////////////////////////////////////////////////// float salestotal = 0.0f; int lastelement = 0; for(int i=0; i<products.length; i++) { if(sales[i] > 0.0f) { salestotal += sales[i]; lastelement = i; } } ////////////////////////////////////////////////////////////// //draw the pie chart ///////////////////////////////////////////////////////////// //chart variables int startangle = 0; //legend variables int legendwidth = 20; int x_legendtext = halfwidth + inneroffset/2 + legendwidth + 5; int x_legendbar = halfwidth + inneroffset/2; int textheight = 20; int curelement = 0; int y_legend = 0; //dimensions of the legend bar dimension legenddim = new dimension(legendwidth , textheight/2); rectangle legendrect = new rectangle(legenddim); for(int i=0; i<products.length; i++) { if(sales[i] > 0.0f) { //calculate percentage sales float perc = (sales[i]/salestotal); //calculate new angle int sweepangle = (int)(perc * 360); //check that the last element goes back to 0 position if (i == lastelement) { sweepangle = 360-startangle; } // draw arc g2d.setcolor(pc.getpiecolor()); g2d.fillarc(x_pie, y_pie, piewidth, pieheight, startangle, sweepangle); //increment startangle with the sweepangle startangle += sweepangle; ///////////// //draw legend ///////////// //set y position for bar y_legend = curelement * textheight + inneroffset; //display the current product string display = products[i]; g2d.setcolor(color.black); g2d.drawstring(display, x_legendtext, y_legend); //display the total sales display = "" + (int)sales[i]; g2d.setcolor(color.black); g2d.drawstring(display, x_legendtext + 80, y_legend); //display the sales percentage display = " (" + (int)(perc*100) + "%)"; g2d.setcolor(color.red); g2d.drawstring(display, x_legendtext + 110, y_legend); //draw the bar g2d.setcolor(pc.getpiecolor()); legendrect.setlocation(x_legendbar,y_legend - textheight/2); g2d.fill(legendrect); //set new pie color pc.setnewcolor(); //increment curelement++; } } //////////////////////////////////////////////// // encode the graph ///////////////////////////////////////// outputstream output = response.getoutputstream(); jpegimageencoder encoder = jpegcodec.createjpegencoder(output); encoder.encode(bi); output.close(); %> |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器