您的位置:首页 > 运维架构 > Tomcat

通过tomcat配置上下文,通过jdbc链接数据源

2016-12-28 10:35 387 查看
tomcat中的配置

<Service name="ssd">
<Connector port="8080" maxHttpHeaderSize="8906"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
URIEncoding="utf-8" useBodyEncodingForURI="true" />
<Engine name="ssd" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase" />
<Host name="localhost" appBase="">
<Context path="" docBase="c:\Microsoft\WorkPorject\WebProject\opinion\WebRoot"
debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/union2" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://xxx.xxx.xxx:xxxx/data_center?autoReconnect=true&characterEncoding=utf-8"/>
</Context>
</Host>
</Engine>
</Service>


JDBC回忆

/**
* 取得基础信息数据库链接
* 连接的数据库有public_zjgov
* @return
*/
public static Connection getUnion2(){
try{
Connection con = null;
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
DataSource connectionPool = (DataSource)envCtx.lookup("jdbc/union2");
con = connectionPool.getConnection();
return con;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}


jdbc查询

/**
* 从文章同一库查询文章列表
* @param sql
* @param values
* @return
*/
public List<Map<String, Object>> queryForUnion2Map(String sql, Object[] values) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBConnection.getUnion2();

pstmt = conn.prepareStatement(sql);

ParameterMetaData pmd = pstmt.getParameterMetaData();   //获取SQL语句的结构
int pmdCount = pmd.getParameterCount();     //获取SQL语句中?占位符的个数

//对SQL语句中的占位符进行赋值
if(null != values) {
for(int i = 0; i < pmdCount && i < values.length; ++i) {
pstmt.setObject(i+1, values[i]);
}
}

rs = pstmt.executeQuery();

ResultSetMetaData rsmd = rs.getMetaData();      //获取查询结果的数据结构

int rsmdCount = rsmd.getColumnCount();

String[] columnName = new String[rsmdCount];
Map<String, String> columnType = new HashMap<String, String>();

for(int i = 0; i < rsmdCount; ++i) {
columnName[i] = rsmd.getColumnLabel(i+1);       //获取列的名字
columnType.put(rsmd.getColumnLabel(i+1), rsmd.getColumnClassName(i+1)); //获取列的JAVA数据类型名
}

Map<String, Object> map = null;
while(rs.next()) {
map = new LinkedHashMap<String, Object>();

for(int i = 0; i < rsmdCount; ++i) {
map.put(columnName[i], tools.readRow(rs, columnType.get(columnName[i]), columnName[i]));
}

list.add(map);
map = null;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
MySQLDBUtils.getInstance().free(rs, pstmt, conn);
}

return list;
}


传递拼接sql

@Override
public List<Map<String, Object>> getMonitorKeywordsList(String ids) {

StringBuffer sql = new StringBuffer();
sql.append("SELECT ai.artKeyword,ai.id FROM "+CommonPublic.ARTICLE_INFO +" ai WHERE 1=1 and ai.id in ("+ids+")");
List<Object> values = new ArrayList<Object>();
QueryResultMap query = new QueryResultMap();
List<Map<String, Object>> list = query.queryForMap(sql.toString(), values);
return list;
}


根据文章id查询关键字并排序统计截取

public  Map<String,Integer> queryRelationKeywordsStat(int monitorType,int sortType,int peopleId,String startDate,String endDate,String peopleName){
Page pg=new Page();
Map<String,Integer> countMap = new HashMap<String,Integer>();

for(int i=0;i<100;i++){
pg.setCurrentPage(i);
pg.setPageSize(100);
Page moniList=monitorpersonService.monitorAtricle(monitorType, sortType, peopleId, startDate, endDate, pg);
if(moniList.getTotalRow()==0||moniList.getTotalPage()<=i)break;
List<MymMonitorBean> dataList = moniList.getData();
String ids = "";
for(int j=0;j<dataList.size();j++){
MymMonitorBean bean = dataList.get(j);
if(dataList.size()-1!=j){
ids+=bean.getId()+",";
} else {
ids+=bean.getId();
}
}
List<Map<String, Object>> monitorKeywordsMap = monitorpersonService.getMonitorKeywordsList(ids);
for(Map<String, Object> map : monitorKeywordsMap){
String keyword = map.get("artKeyword").toString();
// 分割关键词
String[] wordAry = keyword.split(",");
// 遍历关键词,并统计
for(String word : wordAry){
if(countMap.containsKey(word)){
int newCount = countMap.get(word)+1;
countMap.put(word, newCount);
} else {
if(word.equals(peopleName))continue;
countMap.put(word, 1);
}
}

}
}
// 排序结果集,获取前二十个
Map<String,Integer> endCountMap = sortMap(countMap,20);
return endCountMap;
}
/**
* 根据map排序,并倒叙取前几个
* @param oldMap 需要排序的map
* @param many   取的个数
* @return
*/
public static Map<String,Integer> sortMap(Map<String,Integer> oldMap,int many) {
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

@Override
public int compare(Entry<java.lang.String, Integer> arg0,
Entry<java.lang.String, Integer> arg1) {
return arg0.getValue() - arg1.getValue();
}
});
Map<String,Integer> newMap = new LinkedHashMap<String,Integer>();
int count = list.size()>many?many:list.size();
for (int i = count; i > 0; i--) {
newMap.put(list.get(list.size()-i).getKey(), list.get(list.size()-i).getValue());
}
return newMap;
}


将统计值放入名为echarts.java类中进行处理

/**
* 封装力引导关系图的数据
* @param keywordsStatMap
* @return
*/
public Map<String,Object> getRelationKeywords(Map<String, Integer> keywordsStatMap,String peopleName){
Map<String, Object> resultMap = new HashMap<String, Object>();//定义存放饼图信息的map集合
List<Map<String, Object>> nodeList = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> edgeList = new ArrayList<Map<String, Object>>();

int total = 0;

Map<String, Object> firstNodeMap = new HashMap<String, Object>();
firstNodeMap.put("id", 0);
firstNodeMap.put("name", peopleName);
firstNodeMap.put("x", "-266.82776");
firstNodeMap.put("y", "299.6904");

int i = 1;
for(Map.Entry<String, Integer> statEntry : keywordsStatMap.entrySet()){
String statKey = statEntry.getKey();
Integer statValue = statEntry.getValue();
total += statValue;
Map<String, Object> nodeMap = new HashMap<String, Object>();
nodeMap.put("id", i);
nodeMap.put("name", statKey);
nodeMap.put("x", coordinate("-266.82776", null,200,(i*15)));
nodeMap.put("y", coordinate(null, "299.6904",200,(i*15)));
nodeMap.put("num", statValue);
nodeList.add(nodeMap);
Map<String, Object> edgeMap = new HashMap<String, Object>();
if(i <= keywordsStatMap.size()){
edgeMap.put("id", i);
edgeMap.put("sourceID", 0);
edgeMap.put("targetID", i);
edgeList.add(edgeMap);
}
i++;
}
firstNodeMap.put("num", total);
nodeList.add(firstNodeMap);
resultMap.put("nodes", nodeList);
resultMap.put("edges", edgeList);
return resultMap;
}


处理后的参数回传:

@RequestMapping("getRelationChartsData")
@ResponseBody
public String getRelationData(String startDate,String endDate,int peopleId,String peopleName){
int monitorType = NumberUtils.toInt(request.getParameter("monitorType"),0);//领导类型
int sortType = NumberUtils.toInt(request.getParameter("sortType"),1); // 排序方式
if(startDate == null || startDate.equals("")){
startDate = this.getDate(defBegin);
}
if(endDate == null || endDate.equals("")){
endDate = this.getDate(defEnd);
}
//查询关系词
Map<String, Integer> keywordsStatMap =queryRelationKeywordsStat( monitorType, sortType, peopleId, startDate, endDate,peopleName);
Map<String, Object> resultMap = new HashMap<String, Object>();
//封装查询的数据
if(null!=keywordsStatMap&&!keywordsStatMap.isEmpty()){
Echarts echarts = new Echarts();
resultMap =echarts.getRelationKeywords(keywordsStatMap, peopleName);
}
return JsonMapper.toJson(resultMap);
}


关系图前端js调用

function getSimpleRelationCharts(){
$("#relationCharts").html(imgLoading);
var peopleId = $("#monitorList").find(".active").attr("monitor_id");
var peopleName = $("#monitorList").find(".active").attr("monitor_name");
$("#peopleId").val(peopleId);
$("#peopleName").val(peopleName);
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
var param = {
startDate : startDate,
endDate : endDate,
peopleId : peopleId,
peopleName:peopleName,
rnd : Math.random()
};
$.ajax({
type:"post",
url:"/opinion/monitorperson/getRelationChartsData",
dataType:"json",
async:false,
data:param,
success:function(data){
//console.log(data);
if(data){
forceRelationChart("relationCharts", data);
}
}
});
}
<script type="text/javascript" src="/opinion/plugins/echarts3.0/echarts.min.js"></script>
<script type="text/javascript">
function forceRelationChart(id,data){
var myChart = echarts.init(document.getElementById(id));

var nodes = [];
var edges = [];
if(data){
nodes = data["nodes"];
edges = data["edges"];
}

$.each(nodes, function(n, node){
//console.log(node.id+","+node.num);
node.id = ""+node.id+"";
node.value = node.num;
node.symbolSize = node.num*10;
node.symbolSize = 40;
node.category = 0;
node.draggable = true;
node.label = {
normal: {
//show: node.symbolSize > 30
show: true
}
};
node.itemStyle = {
normal: {
color: 'rgb(' +[
106 | 0,
176 | 0,
184 | 0
].join(',') + ')'
}
};
if(node.id == 0){
node.symbolSize = 60;
node.itemStyle = {
normal: {
color: 'rgb(' +[
236 | 0,
81 | 0,
72 | 0
].join(',') + ')'
}
};
}
});

$.each(edges, function(n, edge){
console.log(edge.sourceID+","+edge.targetID);
edge.id = ""+edge.id+"";
edge.source = ""+edge.sourceID+"";
edge.target = ""+edge.targetID+"";
edge.lineStyle = {
normal: {
color: 'rgb(' +[
106 | 0,
176 | 0,
184 | 0
].join(',') + ')'
}
};
});

var categories = [];
categories = [
{name: ''}
];

console.log(nodes);
console.log(edges);

option = {
title: {
text: '关系图',
//subtext: 'Default layout',
top: 'bottom',
left: 'right'
},
tooltip: {},
legend: [{
// selectedMode: 'single',
data: categories.map(function (a) {
return a.name;
})
}],
animationDuration: 1500,
animationEasingUpdate: 'quinticInOut',
series : [
{
name: '关系',
type: 'graph',
//layout: 'none',
layout: 'force',
data: nodes,
links: edges,
categories: categories,
roam: true,
label: {
normal: {
position: 'right',
formatter: '{b}'
}
},
lineStyle: {
normal: {
color: 'source',
//curveness: 0.3
}
},
force: {
repulsion: 700
}
}
]
};

myChart.setOption(option);
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdbc 数据 tomcat