JSP page draws a chart instance with Highcharts

Source: Internet
Author: User
Tags json min jquery library

Highcharts provides a simpler way to insert beautiful, interactive icons into a Web page. Currently support a variety of line, area, column, hash chart, as well as a combination of several diagrams, in addition to support instrumentation, geothermal, radar, polar area, pyramid, waterfall and other professional charts. Compared to the fusioncharts and Anycharts, highcharts free (free-non-commercial license), and the flat design has a great advantage, and the official provided a large number of examples for research.

Using Highcharts on JSP pages

The reference tutorial first introduces the jquery library and the Highcharts.js file, which can then be used in the page. If you are just creating a new static chart, follow the tutorial to produce a beautiful icon. But if you want to use it in a JSP, you need to use JSON (or a similar data serialization format) and Ajax methods to get it done. Struts2 and TOMCAT7 are used here to design, and the environment is well configured.

1. New action

Create a new Jsonaction.java class in the SRC directory and define the data, showing the values for each quarter, using a map to store.
public class Jsonaction extends Actionsupport implements Servletrequestaware {
Private map<string, string> seasonmap = new linkedhashmap<string, string> ();
Parameter from Jquery
Private String CountryName;
Public String execute () {
Seasonmap.put ("S1", "12");
Seasonmap.put ("S2", "55");
Seasonmap.put ("S3", "26");
Seasonmap.put ("S4", "88");
Setcountryname ("the");
return SUCCESS;
}
@Override
public void Setservletrequest (HttpServletRequest request) {
}
Public map<string, String> Getseasonmap () {
return seasonmap;
}
public void Setseasonmap (map<string, string> seasonmap) {
This.seasonmap = Seasonmap;
}
Public String Getcountryname () {
return countryname;
}
public void Setcountryname (String countryname) {
This.countryname = CountryName;
}
}

public class Jsonaction extends Actionsupport implements Servletrequestaware {
Private map<string, string> seasonmap = new linkedhashmap<string, string> ();
Parameter from Jquery
Private String CountryName;
Public String execute () {
Seasonmap.put ("S1", "12");
Seasonmap.put ("S2", "55");
Seasonmap.put ("S3", "26");
Seasonmap.put ("S4", "88");
Setcountryname ("the");
return SUCCESS;
}
@Override
public void Setservletrequest (HttpServletRequest request) {
}
Public map<string, String> Getseasonmap () {
return seasonmap;
}
public void Setseasonmap (map<string, string> seasonmap) {
This.seasonmap = Seasonmap;
}
Public String Getcountryname () {
return countryname;
}
public void Setcountryname (String countryname) {
This.countryname = CountryName;
}
}

2. Specify action point and jump mode in Struts.xml

<package name= "test" namespace= "/" extends= "Json-default" >
<action name= "ajaxaction" class= "com.action.JsonAction" method= "execute" >
<result type= "json"/>
</action>
</package>

<package name= "test" namespace= "/" extends= "Json-default" >
<action name= "ajaxaction" class= "com.action.JsonAction" method= "execute" >
<result type= "json"/>
</action>
</package>

Next, the test http://localhost:8080/ajaxAction should return the following
{"CountryName": "Seasonmap": {"S1": "A", "S2": "," "S3": "", "S4": "88"}

{"CountryName": "Seasonmap": {"S1": "A", "S2": "," "S3": "", "S4": "88"}

The JSON format result.

3, the JSP page in the call

Create a new JSP page with the following contents
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<script src= "Js/jquery.js" ></script>
<script src= "Js/highcharts.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (

function () {

$.ajax ({
Type: "POST",
URL: "Ajaxaction",
DataType: "Text",
Success:function (data) {
data = $.parsejson (data);
var country = data.countryname;
Keys
var keys = [];
Values
var vals = [];
$.each (Data.seasonmap, function (key, value) {
Keys.push (key);
Note convert JSON data to int (or float data type, not string type)
Vals.push (parseint (value));
Console output
Console.log (key, value);
});
var drawchart = function () {
$ (' #container '). Highcharts (
{
Title: {
Text: ' Monthly Average Values ',
X: -20//center
},
Subtitle: {
Text: ' Source: ' + country,
X:-20
},
Xaxis: {
Categories:keys
},
YAxis: {
Title: {
Text: ' Values '
},
Plotlines: [{
value:0,
Width:1,
Color: ' #808080 '
}]
},
ToolTip: {
Valuesuffix: '
},
Legend: {
Layout: ' Vertical ',
Align: ' right ',
VerticalAlign: ' Middle ',
borderwidth:0
},
Series: [{
Name: ' Series 1 ',
Data:vals
}]
});
};
Drawchart ();
}
});
});
</script>
<body>
<div id= "Container"
Style= "min-width:310px; height:400px; margin:0 Auto "></div>

</body>


<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<script src= "Js/jquery.js" ></script>
<script src= "Js/highcharts.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (

function () {

$.ajax ({
Type: "POST",
URL: "Ajaxaction",
DataType: "Text",
Success:function (data) {
data = $.parsejson (data);
var country = data.countryname;
Keys
var keys = [];
Values
var vals = [];
$.each (Data.seasonmap, function (key, value) {
Keys.push (key);
Note convert JSON data to int (or float data type, not string type)
Vals.push (parseint (value));
Console output
Console.log (key, value);
});
var drawchart = function () {
$ (' #container '). Highcharts (
{
Title: {
Text: ' Monthly Average Values ',
X: -20//center
},
Subtitle: {
Text: ' Source: ' + country,
X:-20
},
Xaxis: {
Categories:keys
},
YAxis: {
Title: {
Text: ' Values '
},
Plotlines: [{
value:0,
Width:1,
Color: ' #808080 '
}]
},
ToolTip: {
Valuesuffix: '
},
Legend: {
Layout: ' Vertical ',
Align: ' right ',
VerticalAlign: ' Middle ',
borderwidth:0
},
Series: [{
Name: ' Series 1 ',
Data:vals
}]
});
};
Drawchart ();
}
});
});
</script>
<body>
<div id= "Container"
Style= "min-width:310px; height:400px; margin:0 Auto "></div>

</body>

The page uses AJAX to load the JSON data returned by Ajaxaction, then stores the keys and values separately, and then draws the graph, which can be viewed through the API on how graphics are plotted and each property.
Remove highchart.com link in lower right corner

In Highcharts ({...}) method, increase
Credits: {
Enabled:false
},

Credits: {
Enabled:false
},

option to remove the connection, or, depending on the description, manipulate the attributes of href, style, text, and customize your own links and realistic styles.
Summarize

While using JavaScript, it's certainly easy to use other languages, and highcharts is a great tool for people who want to showcase their HTML5 interactive charts on the site.


highcharts AJAX JSON JQuery Implement Dynamic Data Interactive display Chart Column chart

Look at the effect chart first.




Highcharts Chinese API Instance website

http://www.hcharts.cn/index.php---------------------Chinese official website

http://www.hcharts.cn/docs/index.php----------------Chinese Course

http://www.hcharts.cn/demo/index.php---------------Online Demo

http://bbs.hcharts.cn/forum.php-----------------------Chinese Forum

Download Highcharts and use

http://www.hcharts.cn/resource/index.php to use the latest on it.

The Http://www.hcharts.cn/docs/index.php?doc=start-download website has a detailed description of the role of each folder.

Required file jquery Download it yourself.

<script type= "Text/javascript" src= "${ctx}/js/jquery-1.10.2.js" ></script>
<script type= "Text/javascript" src= "${ctx}/js/highcharts/highcharts.js" ></script>

Added code for page index.jsp

HTML code
<a href= "javascript:void (0);" id= "Highchart" onclick= "Gotohighchart ();" > View charts </a>

JS Code
function Gotohighchart () {
var url = ' ${ctx}/user/chartpage ';
Window.location.href=url;
}

Action when clicking the Jump page

Controller code

@RequestMapping (value = "Chartpage")
Public String Chartpage (HttpServletRequest request,
HttpServletResponse response) {
return "Views/user/chartpage";
}
Corresponds to the 5th step.

The required page code chartpage.jsp

<body>

<div id= "Container" style= "width:800px; height:400px; margin:0 Auto "></div>

</body>

The above implementation of the page jump function. The data for the chart is required. We have to continue.

Data methods required by the chart

Controller

Accept the service to pass the JSON string to the page

@RequestMapping (value = "/chart")
Public String Chart (HttpServletRequest request,
HttpServletResponse response) throws Exception {
String result = null;
try {
result = Userservice.chart ();
catch (Exception e) {
if (log.iserrorenabled ()) {
Log.error ("Query list failed", E);
}
result = NULL;
}
Stringutil.writetoweb (result, "HTML", response);
return null;
}

Service

Stores a list object in a map. and convert to a JSON string array

/**
* Highcharts used.
* @Title: Chart
* @Description: Direct transfer out of JSON to the front page to accept
* @return
*/
Public String chart () {
list<map<string, object>> list = Userdao.chart ();
map<string, object> map = new hashmap<string, object> ();
Map.put ("list", list);
Gson Gson = new Gsonbuilder (). Setdateformat ("Yyyy-mm-dd"). Create ();
String s = Gson.tojson (map);
return s;
}

DAO

The jdbctemplate that is used passes the SQL statement query. Return List Object

Public list<map<string,object>> chart () {
String sql = "Select u.name,u.age from userinfo u";
return jdbctemplate.queryforlist (SQL);
}

The above basically completes the data to obtain and to turn the JSON string array the rest is to accept JSON on the page and populate the Highcharts chart

JS code. Use Ajax to pass over. and fill it inside the highcharts. The final step is also the most fatal step.

Be sure to note the parsing of the JSON string array. I was here in the tangle of more than half a day. Blame yourself for not studying jquery well. And a powerful JSON string.

My JSON is so I need to pay attention to the data in the array of my list when I traverse it. Can ignore this sentence. It's my fault.

{' list ': [{' Name ': ' # ', ' Age ': 19},{' name ': ' # second ', ' Age ': 22},{' name ': ' Test ', ' age ': 19} ...]}

$ (function () {
var x = [];//x axis
var y = [];//y axis
var xtext = [];//x axis text
var color = ["Gray", "Pink", "red", "blue", "yellow", "green", "#fff"];
$.ajax ({
Type: ' Get ',
URL: ' ${ctx}/user/chart ',//address of request data
Success:function (data) {
var json = eval ("+data+"));
var s = 1;
for (var key in json.list) {
Json.list[key].y = Json.list[key].age; Assign a value to the Y axis
Xtext = json.list[key].name;//to x-axis text assignment
Json.list[key].color= Color[key];
}
Chart.series[0].setdata (json.list);//data populated to Highcharts above
},
Error:function (e) {
}
});
var chart = new Highcharts.chart ({
chart:{
Renderto: ' Container ',
Type: ' column '//Display Type column
},
title:{
Text: ' Age map '//Chart title
},
xaxis:{
Categories:xtext
},
yaxis:{
title:{
Text: ' Age '//y the name of the axis
},
},
series:[{
Name: "Name"
}]
});
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.