首页 > 代码库 > Echarts在java中使用

Echarts在java中使用

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="http://www.mamicode.com/">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>This is my JSP page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">
-->
<link href="http://www.mamicode.com/assets/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">

html,body,#wrapper{
width: 100%;
height: 100%;
}

.navbar-inverse{
border-radius:0;
margin-bottom: 0;
}
.navbar-inverse .navbar-header{
width: 180px;
text-align: center;
border-right: 1px solid rgba(255,255,255,0.4);
}
.navbar-inverse .navbar-header .navbar-brand{
float: none;
display: inline-block;
}
.slider{
width: 180px;
min-width:180px;
top:52px;
bottom: 0;
position: absolute;
background-color: rgba(0,0,0,0.00);
box-shadow:3px 0 6px rgba(0,0,0,0.3)
}
.slider .nav li a:hover,
.slider .nav li.active > a{
background-color: rgba(0,0,0,0.2)!important;
}
.slider .sub-menu li a{
padding-left:40px;
}
.slider .sub-menu{
/* border-bottom:1px solid #e5e5e5; */
border-top:1px solid #e5e5e5;
}
#wrap{
margin: 0 0 0 180px;
}

#wrap .wrap{
padding:5px 10px;
}

.panel .panel-footer{
background-color: #ffffff;
padding: 0 15px;
}

.panel-footer .pagination{
margin: 5px;
}

</style>
</head>

<body>
<div id="wrapper">
<nav class="navbar navbar-inverse">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="http://www.mamicode.com/#">后台系统</a>
</div>

<ul class="nav navbar-nav">
<li class="active"><a href="http://www.mamicode.com/#">首 页 <span class="sr-only">(current)</span></a></li>
<li><a href="http://www.mamicode.com/views/login.jsp">登 录</a></li>
<li class="dropdown"><a href="http://www.mamicode.com/#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">更 多 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="http://www.mamicode.com/#">注 册</a></li>
<li><a href="http://www.mamicode.com/#">Another action</a></li>
<li><a href="http://www.mamicode.com/#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="http://www.mamicode.com/#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="http://www.mamicode.com/#">One more separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav pull-right">
<li><a href="http://www.mamicode.com/logout" title="安全退出">安全退出</a></li>
</ul>
</nav>
<div class="slider">
<ul class="nav">
<li class="active">
<a href="javascript:void(0);" onclick="openOrClose(this)"><i class="glyphicon glyphicon-user"></i> 用户管理 <i class="glyphicon glyphicon-chevron-down pull-right"></i></a>
<ul class="nav sub-menu">
<li><a href="http://www.mamicode.com/users/usersController?_method=findAll"><i class="glyphicon glyphicon-list"></i> 用户列表</a></li>
<li class="active"><a href="http://www.mamicode.com/#"><i class="glyphicon glyphicon-plus"></i> 用户添加</a></li>
</ul>
</li>
<li>
<a href="javascript:void(0);" onclick="openOrClose(this)"><i class="glyphicon glyphicon-th-list"></i> 地址管理 <i class="glyphicon glyphicon-chevron-left pull-right"></i></a>
<ul class="nav sub-menu hidden">
<li ><a href="http://www.mamicode.com/#"><i class="glyphicon glyphicon-list"></i> 地址列表</a></li>
<li><a href="http://www.mamicode.com/#"><i class="glyphicon glyphicon-plus"></i> 地址添加</a></li>
</ul>
</li>

</ul>
</div>

<div id="wrap">
<div class="wrap">
<div class="panel panel-info">
<div class="panel-heading">
用户列表

<form action="users/usersController" style="display:inline;">
<div class="col-sm-4 pull-right" style="margin-top: -7px;">
<div class="input-group">
<input type="text" class="form-control" name="keyword" placeholder="搜索..." value="http://www.mamicode.com/${page.keywords[‘username‘] }">
<input type="hidden" name="_method" value="http://www.mamicode.com/findAll">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">搜 索</button>
</span>
</div>
</div>
</form>
<button type="button" class="btn btn-default btn-sm pull-right" style="margin-top:-5px;" data-toggle="modal" data-target="#gridSystemModalLabel">年龄分析</button>
</div>
<table class="table table-bordered table-hover" style="margin-bottom: 0">
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${page.data }" var="user">
<tr>
<td>${user.id }</td>
<td>${user.username }</td>
<td>${user.password }</td>
<td>${user.age }</td>
<td>${user.email }</td>
<td>
<a href="http://www.mamicode.com/#" class="btn btn-info">详情</a>
<a href="http://www.mamicode.com/users/usersController?_method=findById&id=${user.id }" class="btn btn-warning">修改</a>
<a href="http://www.mamicode.com/users/usersController?_method=deleteById&id=${user.id }" onclick="return confirm(‘确认删除?‘);" class="btn btn-danger">删除</a>
</td>
</tr>
</c:forEach>
</table>
<div class="panel-footer text-right">
<ul class="pagination">
<li><span>${page.curr } / ${page.pageCount }</span></li>
<li ${(page.curr eq page.first)?‘class="disabled"‘:‘‘ }>
<a href="http://www.mamicode.com/users/usersController?_method=findAll&keyword=${page.keywords[‘username‘] }&curr=${page.first }" title="首页">首页</a>
</li>
<li ${(page.curr eq page.first)?‘class="disabled"‘:‘‘ }>
<a href="http://www.mamicode.com/users/usersController?_method=findAll&keyword=${page.keywords[‘username‘] }&curr=${page.prev }" title="上一页">上一页</a>
</li>

<c:forEach begin="${page.start }" end="${page.end }" var="num">
<c:choose>
<c:when test="${page.curr == num }">
<li class="active"><a title="第${num }页">${num }</a></li>
</c:when>
<c:otherwise>
<li><a href="http://www.mamicode.com/users/usersController?_method=findAll&keyword=${page.keywords[‘username‘] }&curr=${num }" title="第${num }页">${num }</a></li>
</c:otherwise>
</c:choose>
</c:forEach>

<li ${(page.curr eq page.last)?‘class="disabled"‘:‘‘ }>
<a href="http://www.mamicode.com/users/usersController?_method=findAll&keyword=${page.keywords[‘username‘] }&curr=${page.next }" title="下一页">下一页</a>
</li>
<li ${(page.curr eq page.last)?‘class="disabled"‘:‘‘ }>
<a href="http://www.mamicode.com/users/usersController?_method=findAll&keyword=${page.keywords[‘username‘] }&curr=${page.last }" title="尾页">尾页</a>
</li>
</ul>
</div>
</div>
</div>
</div>



<div class="modal fade" role="dialog" aria-labelledby="gridSystemModalLabel" id="gridSystemModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">用户年龄分析</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div id="charts" style="width: 100%;height:60%;"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->







</body>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/echarts.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/Utils.js"></script>
<script type="text/javascript">


$(‘#gridSystemModalLabel‘).on(‘shown.bs.modal‘,function(){
var charts = echarts.init(document.getElementById("charts"));

var option = {
title: {
text: ‘用户年龄分析‘,
left:‘center‘
},
tooltip: {},
legend: {
orient:‘vertical‘,
left:‘left‘,
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
series: [{
name: ‘用户年龄分析‘,
type: ‘pie‘,
radius:‘65%‘,
data: []
}]
};
charts.showLoading();
utils.ajax({
url:‘users/usersController‘,
data:{"_method":"analyzeAge"},
success:function(data){
charts.hideLoading();
eval("data = "http://www.mamicode.com/+data);
//为了得到名字
var names = [];
for(var i in data){
names.push(data[i][‘name‘]);
}
//设置值
option.legend.data = http://www.mamicode.com/names;
option.series[0].data = http://www.mamicode.com/data;
charts.setOption(option);
}
});


});
//打开或是关闭菜单
function openOrClose(_dom){
var sub_menu = getNextSilbing(_dom);
var flag = _dom.querySelector(".pull-right");
//如果包含某些样式 则做一些事情
if(hasClass(sub_menu,"hidden")){
//去掉 关于隐藏的class
removeClass(sub_menu,"hidden");
//去掉菜单上的向左的箭头
removeClass(flag,"glyphicon-chevron-left");
//添加上向下的箭头
addClass(flag,"glyphicon-chevron-down");
}else{
//添加是 隐藏的class
addClass(sub_menu,"hidden");
//移除向下的箭头
removeClass(flag,"glyphicon-chevron-down");
//添加上向左的箭头
addClass(flag,"glyphicon-chevron-left");
}
//console.log();

}
//得到下一个兄弟节点
function getNextSilbing(_dom){
_dom = _dom.nextSibling;
while(_dom.nodeType!=1){
_dom = _dom.nextSibling;
}
return _dom;
}
//判断是否包含没有个class样式
function hasClass(_dom,_className){
if(_dom.className.indexOf(_className)!=-1){
return true;
}
return false;
}
//给指定的元素添加指定的样式
function addClass(_dom,_className){
_dom.className = _dom.className+" "+_className;
}
//给指定的元素移除指定的样式
function removeClass(_dom,_className){
_dom.className = _dom.className.replace(_className,"");
//将每次添加上的多余的空格去掉
_dom.className = _dom.className.replace(/\s+/ig," ");
}
</script>
</html>

 

 

UsersController.java

package com.huawei.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.huawei.common.Page;
import com.huawei.po.Users;
import com.huawei.service.UsersService;

/**
* Servlet implementation class UsersController
*/
public class UsersController extends HttpServlet {
private static final long serialVersionUID = 1L;

private UsersService usersService = new UsersService();

/**
* @see HttpServlet#HttpServlet()
*/
public UsersController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 将 当前的doPost方法 当作中专站
*/
String _method = request.getParameter("_method");

if("findAll".equalsIgnoreCase(_method)){
this.findAll(request, response);
}else if("deleteById".equalsIgnoreCase(_method)){
this.deleteById(request, response);
}else if("register".equalsIgnoreCase(_method)){
this.register(request, response);
}else if("findById".equalsIgnoreCase(_method)){
this.findById(request, response);
}else if("update".equalsIgnoreCase(_method)){
this.update(request, response);
}else if("analyzeAge".equalsIgnoreCase(_method)){
this.analyzeAge(request, response);
}
}


private void analyzeAge(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
// TODO Auto-generated method stub
response.getWriter().write(this.usersService.analyzeAge());

}

private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

Users curr = (Users) request.getSession().getAttribute("admin");



if(ServletFileUpload.isMultipartContent(request)){
Map<String, FileItem> map = new HashMap<String, FileItem>();
//创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//得到JVM提供的缓存目录
ServletContext context = this.getServletContext();
File repository = (File)context.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
//创建ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);

//解析请求
try {
List<FileItem> items = upload.parseRequest(request);
//users = new Users();

for(FileItem item:items){
//form表单里面的每一个字段
map.put(item.getFieldName(), item);
}


Users u = new Users();

u.setId(Integer.parseInt(map.get("id").getString()));
u.setUsername(map.get("username").getString());
u.setPassword(map.get("password").getString());
u.setEmail(map.get("email").getString());
//u.setImage(Integer.parseInt(map.get("id").getString()));
u.setAge(Integer.parseInt(map.get("age").getString()));





//处理 前一步的数据没有顺序的问题
//for(String key:map.keySet()){
//FileItem item = map.get(key);

//if(item.isFormField()){

//没有顺序

//}else{
//得到跟路径
String path = context.getRealPath("/");
//得到附件目录
File attachment = new File(path,"attachment/"+map.get("username").getString());
//如果没有 就创建目录
System.out.println(attachment.getAbsolutePath());
System.out.println(attachment.exists());
if(!attachment.exists()){
attachment.mkdirs();
}

FileItem image = map.get("image");

File output = new File(attachment,System.currentTimeMillis()+"."+getSuffix(image.getName()));

image.write(output);
u.setImage("attachment/"+map.get("username").getString()+"/"+output.getName());
//System.currentTimeMillis()
this.usersService.update(u);
this.findAll(request, response);
//}
//}
//map.get("id");
} catch (Exception e) {
e.printStackTrace();
}
}


}

private String getSuffix(String name){
if(name!=null){
String[] suffixs = name.split("\\.");
if(suffixs.length>1){
return suffixs[suffixs.length-1];
}
}
return "";
}

private void findById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if(id!=null && id.trim()!=""){
Users users = this.usersService.findById(Integer.parseInt(id));
request.setAttribute("users", users);
request.getRequestDispatcher("/views/update.jsp").forward(request, response);
return ;
}
}

private void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Users users = null;
//判断是否有文件上传
if(ServletFileUpload.isMultipartContent(request)){
//创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//得到JVM提供的缓存目录
ServletContext context = this.getServletContext();
File repository = (File)context.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
//创建ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);

//解析请求
try {
List<FileItem> items = upload.parseRequest(request);
users = new Users();

for(FileItem item:items){
//form表单里面的每一个字段

}
//得到跟路径
String path = context.getRealPath("/");
//得到附件目录
File attachment = new File(path,"attachment");
//如果没有 就创建目录
if(!attachment.exists()){
attachment.mkdirs();
}


} catch (FileUploadException e) {
e.printStackTrace();
}
}

}

protected void deleteById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
this.usersService.deleteById(Integer.parseInt(id));
response.sendRedirect("usersController?_method=findAll");

}

protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//List<Users> users = this.usersService.findAll();
//request.setAttribute("users", users);

String keyword = request.getParameter("keyword");

if(keyword==null){
keyword = "";
}

Page page = new Page();
String curr = request.getParameter("curr");
if(curr ==null || curr.trim().equals("")){
curr ="1";
}
page.getKeywords().put("username", keyword);
page.setCurr(Integer.parseInt(curr));
page = this.usersService.find4Page(page);
request.setAttribute("page", page);
request.getRequestDispatcher("/views/index.jsp").forward(request, response);
return;
}

}

 

 

UsersService.java

package com.huawei.service;

import java.util.List;

import com.huawei.common.Page;
import com.huawei.dao.UsersDAO;
import com.huawei.po.Users;

public class UsersService {

private UsersDAO usersDAO = new UsersDAO();

public List<Users> findAll(){
return this.usersDAO.findAll();
}

public void deleteById(Integer id) {
// TODO Auto-generated method stub
this.usersDAO.delete(id);
}

public Page find4Page(Page page){
return this.usersDAO.find4Page(page);
}

public Users findByUsername(String username) {
List<Users> users = this.usersDAO.findBy("username",username);
return users.size()>0?users.get(0):null;
}

public Users findById(Integer id){
return this.usersDAO.findById(id);
}

public void update(Users users){
this.usersDAO.update(users);
}

public String analyzeAge(){
return this.usersDAO.analyzeAge();
}
}

 

 

 

UsersDAO.java

package com.huawei.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.huawei.base.BaseDAO;
import com.huawei.common.CallBack;
import com.huawei.common.Page;
import com.huawei.po.Users;
import com.huawei.utils.BeanUtil;

public class UsersDAO extends BaseDAO<Users, Integer>{

@Override
public Page find4Page(Page page) {
//构建sql语句
String sql = "SELECT * FROM "+BeanUtil.getTableName(clazz)+" WHERE username LIKE ? LIMIT ?,?";
String count = "SELECT COUNT(1) FROM "+BeanUtil.getTableName(clazz)+" WHERE username LIKE ?";
//得到数据
List<Users> data = http://www.mamicode.com/this.find(sql, new Object[]{"%"+page.getKeywords().get("username")+"%",(page.getCurr()-1)*page.getPageSize(),page.getPageSize()});
page.setRowCount(this.getCount(count,new Object[]{"%"+page.getKeywords().get("username")+"%"}));
page.setData(data);
return page;
}

public String analyzeAge(){

final StringBuilder sb = new StringBuilder("[");

String sql = "SELECT "+
"CASE "+
"WHEN age>0 && age<11 THEN ‘十岁以下‘ "+
"WHEN age>10 && age<21 THEN ‘11-20‘ "+
"WHEN age>20 && age<31 THEN ‘21-30‘ "+
"WHEN age>30 && age<41 THEN ‘31-40‘ "+
"WHEN age>40 && age<51 THEN ‘41-50‘ "+
"WHEN age>50 && age<61 THEN ‘51-60‘ "+
"WHEN age>60 && age<71 THEN ‘61-70‘ "+
"WHEN age>70 && age<81 THEN ‘71-80‘ "+
"WHEN age>80 && age<91 THEN ‘81-90‘ "+
"WHEN age>90 && age<101 THEN ‘91-100‘ "+
"WHEN age>100 THEN ‘一百岁以上‘ "+
"END as ‘label‘,count(age) as ‘value‘ "+
"FROM "+
"users "+
"GROUP BY label ";

this.executeQuery(sql, null, new CallBack() {

@Override
public void execute(ResultSet rs) throws SQLException {
//处理数据
//"{\"name\":\"\",\"value\":\"\"}"
while(rs.next()){
sb.append("{").append("\"name\":\"").append(rs.getString("label")+"\",\"value\":\"").append(rs.getInt("value")+"\"").append("},");
}
}
});

if(sb.length()>1){
sb.deleteCharAt(sb.length()-1);
}

sb.append("]");
return sb.toString();
}

}

Echarts在java中使用