Velocity與Jsp、Freemarker的對比javascript
在java領域,表現層技術主要有三種:jsp、freemarker、velocity。macro能夠用於實現自定義指令,經過使用自定義指令,能夠將一段模板片斷定義成一個用戶指令,使用macro指令的語法格式以下:
< #macro name param1 param2 ... paramN> php
<#compress>
...
< /#compress>
用來壓縮空白空間和空白的行css
<#macro path>html
<#compress>java
${request.contextPath}node
</#compress>mysql
</#macro>linux
在引用時是<@path/>android
<#compress>web
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="renderer" content="webkit" />
<title><@projName/></title>
<script>
var path_="<@path/>";
var user = "${(visitor.name)!''}";
</script>
</#compress>
</#macro>
<#macro Select id name optList optValue showAll=false>
<select id="${id}" name="${name}" class="l-select">
<#if showAll>
<option value="">
所有
</option>
</#if>
<#list optList as opt>
<option value="${(opt.id)!}"
<#if (optValue==opt.id)>selected</#if>
>
${(opt.name)!}
</option>
</#list>
</select>
</#macro>
<#macro FormSelect id name optType optValue showAll=false>
<#list DtCache?keys as key>
<#if key==optType>
<#assign optList=DtCache[key] >
<@Select id name optList optValue showAll />
</#if>
</#list>
</#macro>
<@Select id="companyName" name="companyName" optList=companyList optValue="" showAll=true/>
<@FormSelect id="devType" name="devType" optType="DevType" optValue="" showAll=true />
jQuery ajax異步請求
jQuery
.ajax({
url : "<@path/>/resources/box/startExportMatrix.do",
type : "POST",
data : {
"params[boxCode]" : boxCode,
"params[boxName]" : boxName,
"params[boxType]" : boxType,
"params[vender]" : vender,
"params[period]" : period,
"params[areaName]" : areaName
},
success : function(data) {
window.location = "<@path/>/resources/box/downloadPdf.do";
$(".l-icon-up").parent().next().html("");
},
error : function() {
$(".l-icon-up")
.parent()
.next()
.html(
"<span style='color:red;padding-left:10px;'>導出二維碼爲空!</span>");
}
});
/**
* 生成二維碼
*/
@RequestMapping("/startExportMatrix")
public void startExportMatrix(HttpServletRequest request,HttpServletResponse response,ResBoxForm form) throws Exception{
List<ResBox> resBox = resBoxService.find(form);
response.setContentType("application/x-www-form-urlencoded; charset=GBK");
resBoxService.exportMatrix(resBox, request, response);
}
@Override
public void exportMatrix(List<ResBox> resBox,HttpServletRequest request,HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
ServletContext ctx = request.getSession().getServletContext();
String root = ctx.getRealPath("WEB-INF");
String separator = File.separator;
String savePath = root + separator + "download" + separator + "data" + separator;
File dir2 = new File(savePath);
if (!(dir2.exists())) {
dir2.mkdirs();
}
Document doc = new Document();
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 10, Font.NORMAL);
int startRow=0;
String fileName="二維碼信息.pdf";
String filePath=savePath+fileName;
FileOutputStream out = new FileOutputStream(filePath);
doc=new Document();
PdfWriter.getInstance(doc, out);
doc.setMargins(10, 10, 10, 10);
doc.open();
for (int i=0;i<resBox.size();i+=2) {
ResBox box=null;
try {
box = resBox.get(startRow);
} catch (Exception e) {
// TODO: handle exception
box=null;
}
ResBox box2 = null;
if(resBox.size()>startRow+1)box2=resBox.get(startRow+1);
String boxPath = "";
String matrixPath = request.getSession().getServletContext().getRealPath("images") + File.separator
+ "matrix"+File.separator;
File dir = new File(matrixPath);
if (!(dir.exists())) {
dir.mkdirs();
}
if (box != null) {
boxPath = ctx.getRealPath("images") + File.separator+ "matrix"+File.separator+box.getBoxCode()+".jpg";
String str = "{'boxCode':'" + box.getBoxCode()
+ "','boxName':'" + box.getBoxName() + "','boxType':'"
+ box.getBoxType() + "','capacity':'"
+ box.getCapacity() + "'}";
String content = JSONSerializer.toJSON(str).toString();
content=new String(content.getBytes("utf-8"),"iso-8859-1");
MatrixEncoder.encode(content,matrixPath ,box.getBoxCode(), "jpg");
}
String box2Path = "";
if (box2 != null) {
box2Path = ctx.getRealPath("images") + File.separator+ "matrix"+File.separator+box2.getBoxCode()+".jpg";
String str = "{'boxCode':'" + box2.getBoxCode()
+ "','boxName':'" + box2.getBoxName() + "','boxType':'"
+ box2.getBoxType() + "','capacity':'"
+ box.getCapacity() + "'}";
String content = JSONSerializer.toJSON(str).toString();
content=new String(content.getBytes("utf-8"),"iso-8859-1");
MatrixEncoder.encode(content,matrixPath ,box2.getBoxCode(), "jpg");
}
float[] widths = { 0.5f, 0.5f };
PdfPTable TotalTable = new PdfPTable(widths);
TotalTable.setWidthPercentage(100);
// 第一個單元格
if (box != null) {
PdfPTable MatrixTable0 = PdfUtil.createPdfPCell(font,
boxPath, box);
PdfPCell matrixcell0 = new PdfPCell(MatrixTable0);
matrixcell0.setBorder(Rectangle.NO_BORDER);
TotalTable.addCell(matrixcell0);
}
// 第二個單元格
if (box2 != null) {
PdfPTable MatrixTable2 = PdfUtil.createPdfPCell(font,
box2Path, box2);
PdfPCell matrixcell2 = new PdfPCell(MatrixTable2);
matrixcell2.setBorder(Rectangle.NO_BORDER);
TotalTable.addCell(matrixcell2);
}else{
PdfPCell matrixcell2 = new PdfPCell();
matrixcell2.setBorder(Rectangle.NO_BORDER);
TotalTable.addCell(matrixcell2);
}
doc.add(TotalTable);
startRow=startRow+2;
}
doc.close();
}
/**
* 下載二維碼
*/
@RequestMapping("/downloadPdf")
public void downloadPdf(HttpServletRequest request,HttpServletResponse response) throws IOException{
ServletContext ctx = request.getSession().getServletContext();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//String DATE = sdf.format(new Date());
String name = "二維碼信息.pdf";
String root = ctx.getRealPath("WEB-INF");
String separator = File.separator;
String downfile = root + separator + "download" + separator + "data" + separator + name;
InputStream in = null;
OutputStream outs = null;
File file = new File(downfile);
try {
if (!file.exists()) {
response.sendError(404);
return;
}
in = new FileInputStream(file);
outs = response.getOutputStream();
byte[] buf = new byte[1024];
long fileLength = file.length();
response.addHeader("Content-Length", "" + fileLength);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(name, "UTF-8"));
// 推送數據到客戶端
int length = in.read(buf);
while (length > 0) {
outs.write(buf, 0, length);
outs.flush();
length = in.read(buf);
}
} catch (IOException e) {
// throw e;
e.printStackTrace();
} finally {
if (in != null)
in.close();
if (outs != null)
outs.close();
//刪除文件
if(file.exists()){
file.delete();
}
}
}
var ids=new Array();;
document.write("<#list ids as mn> ");
ids.push("${mn}");
document.write("</#list>");
function exportData(){
$(".l-icon-up").parent().next().html("<span style='color:red;padding-left:10px;'>二維碼導出中...</span>");
jQuery.ajax({
url:"<@path/>/resources/box/startExportMatrix2.do?ids="+ids,
type:"GET",
success:function(data){
window.location = "<@path/>/resources/box/downloadPdf.do";
$(".l-icon-up").parent().next().html("");
},
error:function(){
$(".l-icon-up").parent().next().html("<span style='color:red;padding-left:10px;'>導出二維碼爲空!</span>");
}
});
}
for(String id:ids){
ResBox resBox2=resBoxService.get(id);
resBox.add(resBox2);
}
resBoxService.exportMatrix(resBox, request, response);
<!-- 引入打印控件 -->
<object id="LODOP_OB"
classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width=0 height=0>
<embed id="LODOP_EM" type="application/x-print-lodop" width=0 height=0></embed>
</object>
<script type="text/javascript">
/**
打印檢測
**/
function checkInstall(){
var lodopOB=document.getElementById("LODOP_OB");
var lodopEM=document.getElementById("LODOP_EM");
var LODOP=lodopEM;
if (navigator.appVersion.indexOf("MSIE")>=0) LODOP=lodopOB;
if((LODOP==null)||(typeof(LODOP.VERSION)=="undefined")){
var val = window.confirm("此功能須要安裝打印控件!您是否安裝?安裝後請重啓瀏覽器!");
if(val){
window.location.href = "<@path/>/install/install_lodop32.exe";
return false;
}
}
return LODOP;
}
/**
打印預覽
**/
function printView(){
var printTable=$("#ptable").html();
//alert(printTable);
var LODOP=checkInstall();
if ((LODOP!=null)&&(typeof(LODOP.VERSION)!="undefined")){
LODOP.SET_SHOW_MODE("HIDE_PAPER_BOARD",1);
LODOP.ADD_PRINT_HTM(5,0,"100%","100%",printTable);
LODOP.SET_PRINT_STYLE("FontSize",2);
LODOP.PREVIEW();
}
}
</script>
<div id="ptable" style="display: none">
<table>
<#list resBoxList as box>
<tr>
<td><img src='<@path/>/images/matrix/${(box.boxCode)}.jpg'
width='200px' height='200px' /></td>
<td style="font-size: 16px; line-height: 20px;">箱體編號:${box.boxCode}<br />
<br /> 箱體名稱:${box.boxName}<br />
<br /> 箱體類型:${box.boxType}<br />
<br /> 箱體容量:${box.capacity}<br />
</td>
</tr>
</#list>
</table>
</div>
XML異步請求
var xmlrequest=null;
//建立HttpRequest對象
if(window.ActiveXObject)
{
xmlrequest=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlrequest=new XMLHttpRequest();
}
if (xmlrequest) {
$("#selectCom").show();
//準備發送請求
var req = "<@path/>/resources/box/toSelectCommunity.do";
//打開請求
xmlrequest.open("get", req, true);
//指定處理結果的函數
xmlrequest.onreadystatechange = getCommunity;
//發送請求
xmlrequest.send(req);
}
function getCommunity() {
//完成
if (xmlrequest.readyState == 4) {
//成功返回!
if (xmlrequest.status == 200) {
var resCommuniy = xmlrequest.responseXML.getElementsByTagName("resCommuniy");
var tes="<tr><td colspan='5' class='yk_td_content2' align='center'><a style='cursor:pointer;' onclick='setCommunity(this)' comname=''>不選擇</a></td></tr><tr>";
for(var i = 1; i <= resCommuniy.length; i++){
tes+="<td class='yk_td_content2' align='center'><a style='cursor:pointer;' onclick='setCommunity(this)' comname="
+ resCommuniy[i-1].childNodes[0].childNodes[0].nodeValue + ">"
+ resCommuniy[i-1].childNodes[0].childNodes[0].nodeValue + "</a></td>";
if(i%4==0){
tes+="<tr></tr>"
}
}
tes+="</tr>";
$("#showComlist").html(tes);
}
}
}
/**
* 去選擇社區頁面
*/
@RequestMapping(value = "/toSelectCommunity")
public void toSelectCommunity(HttpServletRequest req, HttpServletResponse response) throws IOException{
List<ResCommunity> resCommuniyList=resCommunityService.getCommunityList();
response.setContentType("text/xml;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
//對社區名稱用xml封裝
String res = "<resCommuniyList>";
for (int i = 0; i < resCommuniyList.size(); i++) {
ResCommunity c = resCommuniyList.get(i);
res += "<resCommuniy><name>" + c.getCommunityName() + "</name></resCommuniy>";
}
res += "</resCommuniyList>";
out.write(res);
out.close();
}
@Override
public boolean exist(Serializable id) {
if(id==null)return false;
return getAbstractDao().exist(id);
}
/**
* 導入模板下載
*/
@RequestMapping("/downloadFile")
public void downloadFile(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("fileName") String fileName) throws IOException {
ServletContext ctx = request.getSession().getServletContext();
String name = "箱體數據導入模版.xls";
String root = ctx.getRealPath("WEB-INF");
String separator = File.separator;
String downfile = root + separator + "download" + separator
+ "template" + separator + name;
InputStream in = null;
OutputStream outs = null;
try {
File file = new File(downfile);
if (!file.exists()) {
response.sendError(404);
return;
}
in = new FileInputStream(file);
outs = response.getOutputStream();
byte[] buf = new byte[1024];
long fileLength = file.length();
response.addHeader("Content-Length", "" + fileLength);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
System.out.println(name);
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(name, "UTF-8"));
// 推送數據到客戶端
int length = in.read(buf);
while (length > 0) {
outs.write(buf, 0, length);
outs.flush();
length = in.read(buf);
}
} catch (IOException e) {
// throw e;
e.printStackTrace();
} finally {
if (in != null)
in.close();
if (outs != null)
outs.close();
}
}
/**
* 建立excel存放於臨時目錄
*/
@RequestMapping("/startExport")
public void exportExcel(HttpServletRequest request,HttpServletResponse response,ResBoxForm form) throws IOException{
ServletContext ctx = request.getSession().getServletContext();
String root = ctx.getRealPath("WEB-INF");
String separator = File.separator;
String savePath = root + separator + "download" + separator + "data" + separator + "box數據.xls";
String[] titles = {"區域","社區名稱","期數","箱體類型","箱體編號","箱體名稱","箱體位置","經度","緯度","芯數","備註"};
List<ResBox> resBox = resBoxService.find(form);
HSSFWorkbook workbook = createExcel(resBox,titles);
FileOutputStream out = new FileOutputStream(savePath);
ByteArrayOutputStream os = new ByteArrayOutputStream();
workbook.write(os);
out.write(os.toByteArray());
out.flush();
out.close();
}
/**
* 建立excel
*/
public HSSFWorkbook createExcel(List<ResBox> entity , String[] title){
//建立webbook
HSSFWorkbook wb = new HSSFWorkbook();
//添加sheet
HSSFSheet sheet = wb.createSheet("sheet1");
//添加表頭第0行
HSSFRow row = sheet.createRow((int) 0);
//建立單元,設置表頭,設置表頭居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//設置表頭
HSSFCell cell = null;
for(int i = 0 ; i < title.length ; i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
for(int i = 0 ; i < entity.size() ; i++){
row = sheet.createRow((int)i + 1);
ResBox resBox = entity.get(i);
//String[] titles = {"區域","社區名稱","期數","箱體類型","箱體編號","箱體名稱","箱體位置","經度","緯度","芯數","備註"};
int j = 0;
insertCell(row, j++, resBox.getAreaName());
insertCell(row, j++, resBox.getCommunityName());
insertCell(row, j++, resBox.getPeriod());
insertCell(row, j++, resBox.getBoxType());
insertCell(row, j++, resBox.getBoxCode());
insertCell(row, j++, resBox.getBoxName());
insertCell(row, j++, resBox.getBoxLocation());
insertCell(row, j++, resBox.getLon());
insertCell(row, j++, resBox.getLat());
insertCell(row, j++, resBox.getCapacity());
insertCell(row, j++, resBox.getRemark());
}
return wb;
}
/**
* 數據寫入excel
*/
private void insertCell(HSSFRow row,int i,Object object){
if(object==null){
row.createCell(i).setCellValue("");
}else{
row.createCell(i).setCellValue(object.toString());
}
}
Jquery 特效
<script type="text/javascript">
$(function(){
//頂部導航切換
$(".nav li a").click(function(){
$(".nav li a.selected").removeClass("selected")
$(this).addClass("selected");
})
})
</script>
<script type="text/javascript">
$(function(){
//導航切換
$(".menuson .header").click(function(){
var $parent = $(this).parent();
$(".menuson>li.active").not($parent).removeClass("active open").find('.sub-menus').hide();
$parent.addClass("active");
if(!!$(this).next('.sub-menus').size()){
if($parent.hasClass("open")){
$parent.removeClass("open").find('.sub-menus').hide();
}else{
$parent.addClass("open").find('.sub-menus').show();
}
}
});
// 三級菜單點擊
$('.sub-menus li').click(function(e) {
$(".sub-menus li.active").removeClass("active")
$(this).addClass("active");
});
$('.title').click(function(){
var $ul = $(this).next('ul');
$('dd').find('.menuson').slideUp();
if($ul.is(':visible')){
$(this).next('.menuson').slideUp();
}else{
$(this).next('.menuson').slideDown();
}
});
})
</script>
<dl class="leftmenu">
<dd>
<div class="title">
<span><img src="images/leftico01.png" /></span>管理信息
</div>
<ul class="menuson">
<li>
<div class="header">
<cite></cite>
<a href="index.html" target="rightFrame">首頁模版</a>
<i></i>
</div>
<ul class="sub-menus">
<li><a href="javascript:;">文件管理</a></li>
</ul>
</li>
<li>
<div class="header">
<cite></cite>
<a href="right.html" target="rightFrame">數據列表</a>
<i></i>
</div>
<ul class="sub-menus">
<li><a href="javascript:;">文件數據</a></li>
</ul>
</li>
<li><cite></cite><a href="tab.html" target="rightFrame">Tab頁</a><i></i></li>
<li><cite></cite><a href="error.html" target="rightFrame">404頁面</a><i></i></li>
</ul>
</dd>
</dl>
$(obj).parent().next().html(tes);
if($(obj).parent().next().is(':visible')){
$(".title2").parent().hide();
$(obj).parent().next().show();
}else{
$(".title2").parent().hide();
}
$(obj).parent().next().slideToggle();
function switchFunc(funcode) {
var leftF="<@path/>/mainLeftFrame.do?funcode="+funcode;
var rightF="<@path/>/mainRightFrame.do";
$("#leftFrame").attr("src",leftF);
$("#rightFrame").attr("src",rightF);
}
function switchFunc(func){
var funcode=$(func).attr("funcode");
parent.switchFunc(funcode);
}
function changeleft1() {
window.parent.document.getElementsByTagName("frameset")[1].cols = "11,*";
$("#leftbtn2").show();
}
parent.rightFrame.makeTab(id3, title3, sUrl3);
function addTab(id,title,sUrl){
jQuery("#tabs").addtabitem({ id: id, text: title,
isactive: true, closeable: true, url:sUrl});
}
function openTab(id,title,sUrl){
jQuery("#tabs").opentabitem({ id: idreplace(id), text: title, url: sUrl, isactive: true, closeable: true }, true);
}
function idreplace(id) {
return id.replace(/[^a-zA-Z\d_]/ig, "_")
}
Maven pom 依賴
<artifact classifier='osgi.bundle' id='org.slf4j.api' version='1.7.2.v20121108-1250'>
<properties size='1'>
<property name='download.size' value='35173'/>
</properties>
</artifact>
/**
* 建立工單關聯類對象
*/
private ProBox createProBox(Row row, String proCode) {
String BoxCode=getCellValue(row.getCell(4));
ProBoxId proBoxId=new ProBoxId();
ProBox proBox=new ProBox();
proBoxId.setBoxCode(BoxCode);
proBoxId.setProCode(proCode);
proBox.setId(proBoxId);
return proBox;
}
百度地圖
function getCurrentViewNode(minLon, minLat, maxLon, maxLat, zoom) {
var params = $.param({
"minLon" : minLon,
"minLat" : minLat,
"maxLon" : maxLon,
"maxLat" : maxLat,
"zoom" : zoom,
"layers" : layers
}, true);
var url = path_
+ "/resources/map/getCurrentViewNodes.do";
jQuery.ajax({
url : url,
dataType : "json",
type : 'POST',
data : params,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success : function(data, textStatus) {
removeOverlay();
var devArray = data;
drawDevOverLays(devArray);
}
});
}
Baidumap.js
var local;
var drawControls = {};
var deviceArray = new Array();
var clickOverLay = {};
var style_line;
var clickedMaker;
var layers=new Array();
var polyLine = new BMap.Polyline(
[ new BMap.Point(0, 0), new BMap.Point(0, 0) ], null);
/**
* 地圖初始化
*/
function initMap() {
map = new BMap.Map("map");
map.addControl(new BMap.NavigationControl());
map.enableScrollWheelZoom();
map.enableContinuousZoom();
map.addControl(new BMap.MapTypeControl({
mapTypes : [ BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP ]
}));
drawControls = {
"zoomBox" : new BMapLib.RectangleZoom(map),
"distance" : new BMapLib.DistanceTool(map)
};
initStyle();
toggleToolbar();
}
function initStyle() {
style_line = {
strokeColor : "green",
strokeWeight : 2,
strokeOpacity : 0.9
};
style_line2 = {
strokeColor : "#f2703d",
strokeWeight : 2,
strokeOpacity : 0.9
};
style_line3 = {
strokeColor : "#017ce5",
strokeWeight : 2,
strokeOpacity : 0.9
};
}
function toggleControl(value) {
for (key in drawControls) {
var control = drawControls[key];
if (value == key) {
control.open();
} else {
control.close();
}
}
}
function toggleToolbar() {
$('#toptoolbar .l-toolbar-item.l-panel-btn').hover(function() {
$(this).addClass("l-panel-btn-over");
}, function() {
$(this).removeClass("l-panel-btn-over");
});
$("input[type='checkbox']").each(function(i, ele) {
var val=$(ele).val();
layers.push(val);
bindEvent(i, ele);
});
$('#mapToolbar').find('img').hover(function() {
if (!$(this).attr('choose'))
this.src = this.src.replace('.png', '-active.png');
}, function() {
if (!$(this).attr('choose') && this.src.indexOf('-active.png') > -1)
this.src = this.src.replace('-active.png', '.png');
}).click(function() {
var prev = $('#mapToolbar').find('img[choose="1"]');
if (prev.length > 0) {
if (prev.get(0).src.indexOf('-on.png') != -1) {
prev.get(0).src = prev.get(0).src.replace('-on.png', '.png');
}
prev.removeAttr('choose');
}
var choose = $(this);
choose.attr('choose', '1');
if (this.src.indexOf('-active.png') == -1)
this.src = this.src.replace('.png', '-on.png');
else
this.src = this.src.replace('-active.png', '-on.png');
});
}
/**
* 圖層點擊事件
*/
function bindEvent(i, ele){
$(ele).click(function() {
var checked = $(ele).is(':checked');
var val=$(ele).val();
if(!checked){
layers=removeLayers(layers,val);
}else{
layers.push(val);
}
searchNode();
});
}
function searchNode(){
var zoom=map.getZoom();
var bounds=map.getBounds();
var maxBound=bounds.getNorthEast();
var minBound=bounds.getSouthWest();
var maxLon=maxBound.lng;
var maxLat=maxBound.lat;
var minLon=minBound.lng;
var minLat=minBound.lat;
getCurrentViewNode(minLon,minLat,maxLon,maxLat,zoom);
openMyInfoWindow();
}
function getCurrentViewNode(minLon, minLat, maxLon, maxLat, zoom) {
var params = $.param({
"minLon" : minLon,
"minLat" : minLat,
"maxLon" : maxLon,
"maxLat" : maxLat,
"zoom" : zoom,
"layers" : layers
}, true);
var url = path_
+ "/resources/map/getCurrentViewNodes.do";
jQuery.ajax({
url : url,
dataType : "json",
type : 'POST',
data : params,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success : function(data, textStatus) {
removeOverlay();
var devArray = data;
drawDevOverLays(devArray);
}
});
}
/**
* 移除已經畫的點
*/
function removeOverlay() {
for ( var i = 0; i < deviceArray.length; i++) {
map.removeOverlay(deviceArray[i][1]);
}
deviceArray = new Array();
}
function drawDevOverLays(data) {
for ( var i = 0; i < data.length; i++) {
createOverLay(data[i], true);
}
}
function createOverLay(matrix, isDev) {
var lon = matrix.lon;
var lat = matrix.lat;
createMarker(matrix, isDev);
}
/**
* 畫點
* @param matrix
* @param isDev
*/
function createMarker(matrix, isDev) {
var lon = matrix.lon;
var lat = matrix.lat;
var imgType = matrix.boxType;
var rl = 0;
if (isDev) {
rl = parseInt(matrix.capacity);
}
var pp = new BMap.Point(lon, lat);
var img = getImage(imgType, rl);
var mIcon = new BMap.Icon(img.imgPath, new BMap.Size(img.width, img.height));
var over_marker = new BMap.Marker(pp, {
icon : mIcon
});
over_marker.addEventListener("click", function() {
clickedMaker = matrix.boxCode;
map.centerAndZoom(new BMap.Point(matrix.lon, matrix.lat), 19);
});
map.addOverlay(over_marker);
if (isDev) {
deviceArray.push([ matrix, over_marker ]);
}
}
function openMyInfoWindow(){
for(var i=0;i<deviceArray.length;i++){
if(deviceArray[i][0].boxCode == clickedMaker){
var infoWin = createInfoW(deviceArray[i][0],true);
var pp=new BMap.Point(deviceArray[i][0].lon,deviceArray[i][0].lat);
map.openInfoWindow(infoWin,pp);//信息框
}
}
}
/**
* 建立信息窗口
*
* @param matrix
* @param over_marker
*/
function createInfoW(matrix, isDev) {
var infoWindow = new BMap.InfoWindow(createInfoDiv(matrix, isDev));
infoWindow.disableCloseOnClick();
infoWindow.addEventListener("clickclose", function() {
clickedMaker = "";
});
return infoWindow;
}
function createInfoDiv(matrix, isDev) {
var key = matrix.boxCode;
var tValue1 = matrix.boxName;
var tValue2 = matrix.boxType;
var tValue3 = matrix.boxCode;
var tValue4 = matrix.boxLocation;
var tValue5 = matrix.communityName;
var tValue6 = matrix.areaName
var viewFunction = 'viewInfo(\"' + key + '\");';
var html =
"<div style='width:320px;'>箱體名稱: </td><td style='color:#4487bf'>"
+ tValue1+"<hr/><div>"
+"<table><tr><td>箱體位置: </td><td style='color:#4487bf'>"
+ tValue4
+"</td></tr><tr><td style='height:15px;'></td></tr><tr><td>箱體類型 : </td><td style='color:#4487bf'>"
+ tValue2
+ "</td></tr><tr><td style='height:15px;'></td></tr><tr><td>所屬區域: </td><td style='color:#4487bf'>"
+ tValue6
+"</td></tr><tr><td style='height:15px;'></td></tr><tr><td>社區地址 : </td><td style='color:#4487bf'>"
+ tValue5
+"</td></tr><tr><td style='height:15px;'></td></tr><tr><td>"
+"<a href='javascript:void(0);' onclick='"+ viewFunction+ "'>點擊詳情 >></a></td><tr></div>"
+"</table></div>";
return html;
}
function viewInfo(key){
openDialog("詳細信息", path_+"/resources/map/getMapBoxView.do?code="+key, true, null);
}
/**
* 獲取設備圖標
* @param imgType
* @param rl
* @returns imgType
*/
function getImage(imgType, rl) {
var _width = 21;
var _height = 21;
var t = "vDEF.png";
if (imgType == "光交接箱") {
t = "vGJX.png";
}
if (imgType == "光纖分配箱") {
_width = 27;
_height = 27;
t = "vGFX_144.png";
}
if (imgType == "綜合機櫃") {
t = "vZHJG.png";
}
if (imgType == "多媒體機箱") {
t = "vJHJ.png";
}
if (imgType == "機房") {
t = "vDEF.png";
}
var imgPath = path_ + "/images/map/" + t;
var img = {
"width" : _width,
"height" : _height,
"imgPath" : imgPath
};
return img;
}
/**
* 移除數據中元素
* @param arr
* @param val
* @returns
*/
function removeLayers(arr, val) {
return $.grep(arr, function(arrayVal,i) {
return arrayVal != val;
});
}
public static <T extends Object> T json2Object(String jsonString,Class<T> clazz) throws Exception{
if(jsonString==null)return null;
try {
//mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
// mapper.getDeserializationConfig().withHandler(hs);
// mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , false);
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
T t=mapper.readValue(jsonString, clazz);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json字符串轉換list
* @param jsonStr
* @param cls
* @return
*/
public static <T extends Object> List<T> json2List(String jsonStr,Class<T> cls)
{
try
{
JavaType javaType=getCollectionType(ArrayList.class, cls);
List<T> list= mapper.readValue(jsonStr, javaType);
return list;
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses)
{
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
緩存設置
package com.eshine.common.vo;
public class DTEntity {
private String id;
private String name;
public DTEntity() {
super();
}
public DTEntity(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 查詢倉庫列表ByCode
* @param repoList
* @return
*/
public static List<DTEntity> repoListByCode(List<Repo> repoList){
List<DTEntity> entyList=new ArrayList<DTEntity>();
for(Repo rp:repoList){
DTEntity enty=new DTEntity(rp.getRepoCode(), rp.getRepoCode());
entyList.add(enty);
}
return entyList;
}
/**
* 獲取枚舉類值列表
* @param enumArgs
* @return
*/
public static List<DTEntity> enumList(DT enumArgs[]){
List<DTEntity> entyList=new ArrayList<DTEntity>();
for(DT t:enumArgs){
DTEntity enty=new DTEntity(t.getDtName(), t.getDtName());
entyList.add(enty);
}
return entyList;
}
/**
* 獲取 枚舉類數據
* @return
*/
public static Map<String, List<DTEntity>> enumMap() {
Map<String, List<DTEntity>> cache = new HashMap<String, List<DTEntity>>();
Class[] enumArgs = DTEnum.class.getClasses();
for (Class enumArg : enumArgs) {
if (enumArg.isEnum()) {
String clazzName = enumArg.getSimpleName();
List<DTEntity> entryList = new ArrayList<DTEntity>();
DT[] enums = (DT[]) enumArg.getEnumConstants();
for (DT T : enums) {
DTEntity entry = new DTEntity(T.getDtName(), T.getDtName());
entryList.add(entry);
}
cache.put(clazzName, entryList);
}
}
return cache;
}
/**
* 枚舉總類
*/
public class DTEnum {
/**
* Pon 使用狀態
*/
public static enum PonState implements DT{
ready("預分配"),
using("正使用"),
free("空閒");
private String dtName;
private PonState(String dtName) {
this.dtName = dtName;
}
public String getName(){
return name();
}
@Override
public String getDtName() {
return dtName;
}
}
}
<@FormSelect id="boxType" name="boxType" optType="BoxType" optValue="" showAll=true />
package com.eshine.common.context;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import com.eshine.common.config.Config;
import com.eshine.common.dt.DTUtil;
import com.eshine.common.vo.DTEntity;
//import com.eshine.core.bo.SaSys;
//import com.eshine.core.bo.SaSysId;
import com.eshine.core.service.SysService;
import com.eshine.util.FileUtil;
import com.eshine.util.ServletUtil;
@Component
public class ContextListener implements ApplicationContextAware {
private static ServletContext cxt;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
try {
WebApplicationContext webContext=(WebApplicationContext)applicationContext;
cxt=webContext.getServletContext();
ServletUtil.contextPath=cxt.getContextPath();
FileUtil.setBasePath(cxt.getRealPath("/"));
FileUtil.setServletClassesPath(FileUtil.getBasePath()+"/WEB-INF/classes/");
cxt.setAttribute("projectName", Config.getProject_name());
Map<String, List<DTEntity>> DtCache=DTUtil.enumMap();
cxt.setAttribute("DtCache", DtCache);
} catch (Exception e) {
e.printStackTrace();
}
}
}
function getCurrentViewNode(minLon, minLat, maxLon, maxLat, zoom) {
var params = $.param({
"minLon" : minLon,
"minLat" : minLat,
"maxLon" : maxLon,
"maxLat" : maxLat,
"zoom" : zoom,
"layers" : layers
}, true);
var url = path_
+ "/resources/map/getCurrentViewNodes.do";
jQuery.ajax({
url : url,
dataType : "json",
type : 'POST',
data : params,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success : function(data, textStatus) {
//alert(data[0].lon);
removeOverlay();
var devArray = data;
drawDevOverLays(devArray);
}
});
}
/**
* 移除已經畫的點
*/
function removeOverlay() {
for ( var i = 0; i < deviceArray.length; i++) {
map.removeOverlay(deviceArray[i][1]);
}
deviceArray = new Array();
}
function drawDevOverLays(data) {
for ( var i = 0; i < data.length; i++) {
createOverLay(data[i], true);
}
}
function createOverLay(matrix, isDev) {
var lon = matrix.lon;
var lat = matrix.lat;
createMarker(matrix, isDev);
}
/**
* 查詢當前屏幕內設備點
* @param req
* @param rsp
* @param form
* @return
*/
@RequestMapping(value = "/getCurrentViewNodes")
public @ResponseBody List<ResBox> getCurrentViewNodes(MapForm form) {
List<ResBox> resBoxList=mapService.queryResBoxByLonLat(form);
return resBoxList;
}
public List<ResBox> queryResBoxByLonLat(MapForm form) {
Double maxLon = form.getMaxLon();
Double minLon = form.getMinLon();
Double maxLat = form.getMaxLat();
Double minLat = form.getMinLat();
String layers[]=form.getLayers();
List<Object> argsList=new ArrayList<Object>();
argsList.add(minLon);
argsList.add(maxLon);
argsList.add(minLat);
argsList.add(maxLat);
String sWhere="";
if(layers!=null){
for(String layer:layers){
if(sWhere.length()>0) sWhere+=" or ";
sWhere+=" boxType=? ";
argsList.add(layer);
}
}
if(sWhere.length()>0) sWhere="("+sWhere+")";
String hql = " from ResBox where lon>? and lon<=? and lat>? and lat<?";
if(sWhere.length()>0)hql+=" and "+sWhere;
List<ResBox> resBoxList = resBoxDao.find(hql,argsList.toArray());
return resBoxList;
}
public List<LayerBox> statLayerBox(Double minLon,Double minLat,Double maxLon,Double maxLat) {
String hql="select boxType,count(*) from ResBox "
+ " where lon>? and lon<=? and lat>? and lat<?"
+ " group by boxType";
List<Object[]> argsList=resBoxDao.find(hql, new Object[]{minLon,maxLon,minLat,maxLat});
List<LayerBox> boxList=new ArrayList<LayerBox>();
for(Object[] args:argsList){
String boxType=args[0]+"";
String count=args[1]+"";
LayerBox layer=new LayerBox();
layer.setBoxType(boxType);
layer.setBoxTotal(Integer.valueOf(count));
boxList.add(layer);
}
return boxList;
}
$('#toptoolbar .l-toolbar-item.l-panel-btn').each(function(i, ele) {
var val=$(ele).find("input[type='checkbox']").val();
layers.push(val);
bindEvent(i, ele);
});
/**
* 圖層點擊事件
* @param i
* @param ele
*/
function bindEvent(i, ele){
$(ele).click(function() {
var checked = $(ele).find("input[type='checkbox']").is(':checked');
var val=$(ele).find("input[type='checkbox']").val();
if(checked){
$(ele).find("input[type='checkbox']").prop('checked', false);
layers=removeLayers(layers,val);
}else{
$(ele).find("input[type='checkbox']").prop('checked', true);
layers.push(val);
}
searchNode();
});
$(ele).find("input[type='checkbox']").click(function(){
var checked1 = $(ele).find("input[type='checkbox']").is(':checked');
var val=$(ele).find("input[type='checkbox']").val();
if(!checked1){
$(ele).find("input[type='checkbox']").prop('checked', true);
layers=removeLayers(layers,val);
}else{
$(ele).find("input[type='checkbox']").prop('checked', false);
layers.push(val);
}
searchNode();
});
$(ele).find(":contains('搜索')").click(function() {
var width = $('body').width() * 0.8;
var height = $('body').height();
var isopen = true;
var listDialog = $.ligerDialog.open({
title: "搜索",
top: 0,
left: 0,
url: path_+ "/resources/map/getSearchView.do",
height: height,
width: width,
modal: true,
showToggle: true,
buttons : [ {
text : '展開/收起',
onclick : function(item, dialog) {
if (isopen) {
dialog.collapse();
isopen = false;
dialog.unmask();
} else {
dialog.extend();
isopen = true;
dialog.mask();
}
}
}, {
text : '關閉',
onclick : function(item, dialog) {
dialog.hide();
},
cls : 'l-dialog-btn-highlight'
} ],
onCollapse : function() {
isopen = false;
listDialog.unmask();
},
onExtend : function() {
isopen = true;
listDialog.mask();
},
isResize : false,
isDrag : true,
showMax : false
});
});
}
hibernate高級查詢 Restrictions
crit.add(
Restrictions.or(Restrictions.eq("sharearea", 2),
Restrictions.or(Restrictions.isNotEmpty("owner "), Restrictions.and(Restrictions.eq("sharearea", 1), Restrictions.eq("userspace", "userspace")))));
Eclipse hibernate插件生成實體類hibernate生成策略
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "DEV_CODE", unique = true, nullable = false)
public Integer getDevCode() {
return this.devCode;
}
@DateTimeFormat(pattern="yyyy-MM-dd")
js 時間格式化
@Temporal(TemporalType.TIMESTAMP)
function dateFormat(rowdata,index,value){
if(value=="" ||value==null){
return "";
}else{
// var dateStr=new Date(value);
var now = new Date(value);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var dateStr = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":"
+ second;
return dateStr;
}
}
parent.drawLayer(communityCode,period,communityName,areaName);
/*SELECT CLIENT_NAME from res_client where LIGHTSPLITTERNAME in (select light_name from res_light where box_name = '陽江陽西方正中學-GF002' )*/
select a.client_name from res_client a LEFT JOIN res_light b on a.LIGHTSPLITTERNAME = b.LIGHT_NAME where b.BOX_NAME = '陽江陽西方正中學-GF002'
alert(manager.get("url"));
$('#toptoolbar .l-toolbar-item.l-panel-btn').each(function(i, ele) {
var val=$(ele).find("input[type='checkbox']").val();
layers.push(val);
bindEvent(i, ele);
});
function bindEvent(i, ele){
$(ele).click(function() {
var checked = $(ele).find("input[type='checkbox']").is(':checked');
var val=$(ele).find("input[type='checkbox']").val();
if(checked){
$(ele).find("input[type='checkbox']").prop('checked', false);
layers=removeLayers(layers,val);
}else{
$(ele).find("input[type='checkbox']").prop('checked', true);
layers.push(val);
}
searchNode();
});
設置爲float的div在ie下設置的margin會加倍。這是一個ie6都存在的bug。解決方案是在這個div裏面加上display:inline;
#imfloat{
float:left;
margin:5px;
display:inline;}
clear{ clear:both;}
高度不能自適應是當內層對象的高度發生變化時外層高度不能自動進行調節,特別是當內層對象使用margin 或paddign 時。
例:
#box {background-color:#eee; }
#box p {margin-top: 20px;margin-bottom: 20px; text-align:center; }
<div id="box">
<p>p對象中的內容</p>
</div>
解決技巧:在P對象上下各加2個空的div對象CSS代碼:.1{height:0px;overflow:hidden;}或者爲DIV加上border屬性。
-server -Xms800m -Xmx800m -XX:PermSize=64M -XX:MaxNewSize=256m
-XX:MaxPermSize=128m -Djava.awt.headless=true
Placeholder
function initRepoRack(){
getRepoRackList("${(exchLog.repoInCode)}","repoInCode");
getRepoRackList("${(exchLog.repoOutCode)}","repoOutCode");
}
function deleteRow(ids,gridId){
deleteGridRow({'ids':ids},gridId,"<@path/>/repo/exchMaterail/deleteExchMaterail.do")
}
Shift+alt+j 註釋(type)
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="renderer" content="webkit" />
public List<DtType> getFormDataSource(FormSelect ft,SysUser user){
Integer dataSourceType=ft.getDatasourceType();
String dataSource=ft.getDatasource();
if(dataSourceType==null)dataSourceType=1;
if(dataSource==null)return null;
if(1==dataSourceType){
return Configuration.getTypes(dataSource);
}else if(3==dataSourceType){
IFormDataSource fds=SpringContext.getBean(dataSource);
if(fds!=null)return fds.getData(user);
else return null;
}else if(2==dataSourceType){
String txt=ft.getTxt();
String val=ft.getVal();
SimpleJdbcDao jdbcDao=(SimpleJdbcDao)SpringContext.getBean(dataSource);
String sql="select * from "+dataSource;
List<DtType>dtlist=new ArrayList<DtType>();
List<Map<String,Object>>list=jdbcDao.queryForList(sql);
for(Map<String,Object> map:list){
String txts=map.get(txt)+"";
String vals=map.get(val)+"";
DtType dt=new DtType();
dt.setId(vals);
dt.setName(txts);
dtlist.add(dt);
}
}
return null;
}
@Autowired
private SimpleJdbcDao jdbcDao;
SimpleJdbcDao jdbcDao =(SimpleJdbcDao)SpringContext.getBean("jdbcDao");
@Override
public void updateJbpmGroup() {
//this.jbpmGroupDao.deleteJbpmGroupNotInSysGroup();
List<String> ids=this.jbpmGroupDao.queryRoleIdNotInJbpmGroup();
for(String id:ids){
GroupImpl user=new GroupImpl(id);
this.jbpmGroupDao.save(user);
}
if(!this.jbpmGroupDao.exists("Administrators")){
GroupImpl group=new GroupImpl("Administrators");
this.jbpmGroupDao.save(group);
}
}
/**
* 查找流程實例參數值
* @param processId
* @param variableIds
* @return Map<String,Object>
* ###################
*/
@Override
public Map<String, Object> queryVariables(Long processInstanceId,Collection<String> variableIds) {
Collection<VariableInstanceLog> variables=this.variableInstanceLogDao.findVariableInstanceByProcessInstanceId(processInstanceId);
Map<String, Object> map=new HashMap<String, Object>();
for(VariableInstanceLog vl : variables){
map.put(vl.getVariableId(), vl.getValue());
}
return map;
}
public class EventRecord implements java.io.Serializable{
// primary key
private int id;
// fields
private int taskId;
private int type;
private Integer source;
private String subject;
private String content;
private String users;
private int state;
private String ftime;
private String tempname;
/**
* Title:表單監聽
* Description: 在表單任務提交後,會加載相關的監聽事件,寫到timework這個表裏
* ----------------------------------------------
* DateMenderReason
*/
private String form_id;//表單ID
private String fcomment;//註釋
private Integer delay;//時限,單位:分鐘
private String eventType;//事件類型,msg發送消息,sql執行sql,commit自動提交
private String eventArgs;//事件參數,格式 字段名1,"常量值1",字段2 系統將按順序把字段內容依次封裝
//注:固定參數{taskName}爲自動提交的表單名字,{userCode}爲提交的用戶名,其餘的爲提交的表單內容
private String eventContent;//事件內容
//msg爲發送的消息內容,
//sql爲執行的sql,
//commit爲提交數據的json格式
//參數格式爲{0}
private String msgType;//若是類型是消息有效。一、發短信二、app消息
private Integer checkpoint;//時限是否做爲統計節點
private String usercode;
private String taskname;
private FormListener formlistener;
List<String>ownerList=new ArrayList<String>();
//獲取監聽的用戶執行人
try{
if("1".equals(checkpoint)){
String sql4owner="select p.ENTITY_ID(執行者,我的或角色組),o.DTYPE(user或grout) from peopleassignments_potowners p left "
+ "join organizationalentity o on p.entity_id=o.id "
+ "where task_id=(select id from task where formName=? and processInstanceId=? LIMIT 1)";
List<Map<String,Object>>qlist=jdbcDao.queryForList(sql4owner, taskName,piid);
for(Map<String,Object>qmap:qlist){
String dtype=""+qmap.get("DTYPE");
String entityId=""+qmap.get("ENTITY_ID");
if("User".equals(dtype)){
if("1".equals(msgType)){//若是是發送短信
SysUser u=userService.get(entityId);
if(u!=null){
ownerList.add(u.getMobile());
}
}else{
ownerList.add(entityId);
}
}
if("Group".equals(dtype)){
List<SysUser>ulist=userService.queryUserByRoleCode(entityId);
if("1".equals(msgType)){//若是是發送短信
for(SysUser u:ulist){
ownerList.add(u.getMobile());
}
}else{
for(SysUser u:ulist){
ownerList.add(u.getUserCode());
}
}
}
}
}
}catch(Exception e){
}
String[]users=usercode.split(";");
for(String user:users){
String insertSql="insert into eventrecord(taskid,type,content,users,state,ftime)values(?,?,?,?,?,?)";
jdbcDao.update(insertSql, tid,msgType,fcontent,user,0,sdf.format(date));
}
for(String user:ownerList){
String insertSql="insert into eventrecord(taskid,type,content,users,state,ftime)values(?,?,?,?,?,?)";
jdbcDao.update(insertSql, tid,msgType,fcontent,user,0,sdf.format(date));
}
SysUser user=VisitorUtil.getVisitorUserData(session);
@Override
public TaskResult startProcess(String processId, String taskName,
Map<String, Object> params, SysUser user,JbpmFormData formData) throws Exception {
String userId = user.getId();
String userName = user.getUserName();
String orgId = user.getOrgId();
String orgName = this.orgService.getOrgNameByOrgId(orgId);
RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
KieSession ksession = engine.getKieSession();
Map<String,String>info=new HashMap<String,String>();
params.put("executor_userId", userId);
params.put("executor_userName", userName);
params.put("executor_orgId", orgId);
params.put("executor_orgName", orgName);
params.put("info", info);
params.put("formData", formData.getData());
/**點擊的按鈕**/
String flowButtonValue=formData.getFlowButton();
ProcessInstance processInstance = ksession.startProcess(processId,
params);
info.put("piid", processInstance.getId()+"");
saveDescription(processInstance.getId(),processId,taskName,formData);
List<Status> status = Arrays.asList(Status.Reserved);
QueryFilter queryFilter=new QueryFilter();
queryFilter.setFilterParams("processInstanceId="+processInstance.getId());
List<TaskSummary> tasks=this.runtimeDataService.getTasksAssignedAsPotentialOwnerByStatus(userId, status, queryFilter);
for (TaskSummary ts : tasks) {
Task task = taskService.getTaskById(ts.getId());
TaskImpl ti = (TaskImpl) task;
Long taskId = ts.getId();
TaskData taskData = ti.getTaskData();
switch (taskData.getStatus()) {
case Completed:
//return TaskResult.Completed;
throw new SaveFormException(TaskResult.Completed);
case Obsolete:
//return TaskResult.Obsoleted;
throw new SaveFormException(TaskResult.Obsoleted);
case Ready: {
taskService.claim(taskId, userId);
};
case Reserved: {
taskService.start(taskId, userId);
};
case InProgress: {
User u = taskData.getActualOwner();
String uId = u.getId();
if (!userId.equals(uId)) {
return TaskResult.Claimed;
} else {
taskService.complete(taskId, userId, params);
try {
this.saveFormValue(taskId, params, user, formData);
} catch (DaoException e) {
log.error("保存表單值出錯:{0}", e);
//return TaskResult.Unknown;
throw new SaveFormException(TaskResult.Unknown);
}
return TaskResult.Success;
}
}
}
// try {
// taskService.start(taskId, userId);
// taskService.complete(taskId, userId, params);
// return TaskResult.Success;
// } catch (Exception e) {
// e.printStackTrace();
// }
break;
}
return TaskResult.Success;
}
+ (filterParamas!=null?" and "+filterParamas:"")sql語句拼接
-server -Xms800m -Xmx800m -XX:PermSize=64M -XX:MaxNewSize=256m
-XX:MaxPermSize=128m -Djava.awt.headless=true
taskService.complete(taskId, userId, data);
// 計算新建故障和預定時間的時間差
FRAC_SECOND。表示間隔是毫秒
SECOND。秒
MINUTE。分鐘
HOUR。小時
DAY。天
WEEK。星期
MONTH。月
QUARTER。季度
YEAR。年
String sql="select TIMESTAMPDIFF(MINUTE,TJTKGZ01,F19)/60 from JTKGZ where pk=?";
parent.rightFrame.makeTab(id, title, sUrl);
window.parent.document.getElementsByTagName("frameset")[1].cols = "0,*";
<input name="numUpdTime" type="hidden" id=numUpdTime
class="l-text l-input" value='${(mat.numUpdTime?string("yyyy-MM-dd"))!}'/>
yyyy-MM-dd HH(下午寫法):mm:ss
${.now?date}
${nowDate?time}
工程初始化
@Component
public class ContextListener implements ApplicationContextAware {
private static ServletContext cxt;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
try {
WebApplicationContext webContext=(WebApplicationContext)applicationContext;
cxt=webContext.getServletContext();
ServletUtil.contextPath=cxt.getContextPath();
FileUtil.setBasePath(cxt.getRealPath("/"));
FileUtil.setServletClassesPath(FileUtil.getBasePath()+"/WEB-INF/classes/");
cxt.setAttribute("projectName", Config.getProject_name());
Map<String, List<DTEntity>> DtCache=DTUtil.enumMap();
cxt.setAttribute("DtCache", DtCache);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Component
public class Configuration implements ApplicationContextAware{
Log log=LogFactory.getLog(Configuration.class);
private static DtTypeService dtTypeService;
@Autowired
public void setDtTypeService(DtTypeService service) {
dtTypeService = service;
}
private static Map<String,List<DtType>> map=new HashMap<String,List<DtType>>();
private static final Map<String,String> dtTypeMap=new HashMap<String,String>();
public Configuration() {
}
public void init(){
reloadOBjectTypes();
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 經過父ID查找同對象的類別
* @param parentId
* @return
*/
public static List<DtType> getTypes(String parentId){
if(map!=null)return map.get(parentId);
else return null;
}
public static final String getTypeName(String typeId){
return dtTypeMap.get(typeId);
}
public static void reloadOBjectTypes(){
Map<String,List<DtType>> _map=dtTypeService.getDtTypeMap();
map=_map;
try {
if (_map.size() > 0) {
dtTypeMap.clear();
Collection<List<DtType>> typeSet= _map.values();
for(List<DtType> list:typeSet){
if(list!=null){
for(DtType ot:list){
dtTypeMap.put(ot.getId(), ot.getName());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
(1)load(InputStream inStream)
這個方法能夠從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。以下面的代碼:
Properties pro = new Properties();FileInputStream in = new FileInputStream("a.properties");pro.load(in);in.close();
(2)store(OutputStream out, String comments)
這個方法將Properties類對象的屬性列表保存到輸出流中。以下面的代碼:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");pro.store(oFile, "Comment");oFile.close();
public static Properties loadProperty(String propFileName) {
InputStream inputStream = PropertiesUtil.class.getResourceAsStream("/"
+ propFileName);
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return properties;
}
jQuery.ligerDialog.error('刪除錯誤!')
win = jQuery.ligerDialog
.open({
title : "查看倉庫",
url : "<@path/>/repo/material/toEditMaterial.do?matCode="
+ matCode,
height : 500,
width : 720,
modal : true,
allowClose : true,
isHidden : false,
showMax : true,
onClosed : refreshSubGrid
});
$.ligerDefaults.Grid.formatters['inStatus'] = function (value, column) {
//value 當前的值
//column 列信息
if (!value)
{
return "未知狀態";
}else if (value == "1"){
return "未審覈";
}else if (value == "2"){
return "已審覈";
}else{
return value;
}
};
{ display: '狀態', width: '100',name:'inStatus',type:'inStatus'}
properties.load(Config.class.getClassLoader().getResourceAsStream("config/config.properties"));
不少時候咱們作界面刷新都須要經過Handler來通知UI組件更新!
流程圖解析: 相關名詞
· UI線程:就是咱們的主線程,系統在建立UI線程的時候會初始化一個Looper對象,同時也會建立一個與其關聯的MessageQueue;
· Handler:做用就是發送與處理信息,若是但願Handler正常工做,在當前線程中要有一個Looper對象
· Message:Handler接收與處理的消息對象
· MessageQueue:消息隊列,先進先出管理Message,在初始化Looper對象時會建立一個與之關聯的MessageQueue;
· Looper:每一個線程只可以有一個Looper,管理MessageQueue,不斷地從中取出Message分發給對應的Handler處理!
當咱們的子線程想修改Activity中的UI組件時,咱們能夠新建一個Handler對象,經過這個對象向主線程發送信息;而咱們發送的信息會先到主線程的MessageQueue進行等待,由Looper按先入先出順序取出,再根據message對象的what屬性分發給對應的Handler進行處理!
MainActivity.java:
public class MainActivity extends Activity { //定義切換的圖片的數組id int imgids[] = new int[]{ R.drawable.s_1, R.drawable.s_2,R.drawable.s_3, R.drawable.s_4,R.drawable.s_5,R.drawable.s_6, R.drawable.s_7,R.drawable.s_8 }; int imgstart = 0; final Handler myHandler = new Handler() { @Override //重寫handleMessage方法,根據msg中what的值判斷是否執行後續操做 public void handleMessage(Message msg) { if(msg.what == 0x123) { imgchange.setImageResource(imgids[imgstart++ % 8]); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView imgchange = (ImageView) findViewById(R.id.imgchange); //使用定時器,每隔200毫秒讓handler發送一個空信息 new Timer().schedule(new TimerTask() { @Override public void run() { myHandler.sendEmptyMessage(0x123); } }, 0,200); } }
若是是Handler寫在了子線程中的話,咱們就須要本身建立一個Looper對象了!建立的流程以下:
1 )直接調用Looper.prepare()方法便可爲當前線程建立Looper對象,而它的構造器會建立配套的MessageQueue; 2 )建立Handler對象,重寫handleMessage( )方法就能夠處理來自於其餘線程的信息了! 3 )調用Looper.loop()方法啓動Looper
使用示例: 輸入一個數,計算後經過Toast輸出在這個範圍內的全部質數
實現代碼: main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/etNum" android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請輸入上限"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="cal" android:text="計算"/> </LinearLayout>
MainActivity.java:
public class CalPrime extends Activity { static final String UPPER_NUM = "upper"; EditText etNum; CalThread calThread; // 定義一個線程類 class CalThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { // 定義處理消息的方法 @Override public void handleMessage(Message msg) { if(msg.what == 0x123) { int upper = msg.getData().getInt(UPPER_NUM); List<Integer> nums = new ArrayList<Integer>(); // 計算從2開始、到upper的全部質數 outer: for (int i = 2 ; i <= upper ; i++) { // 用i處於從2開始、到i的平方根的全部數 for (int j = 2 ; j <= Math.sqrt(i) ; j++) { // 若是能夠整除,代表這個數不是質數 if(i != 2 && i % j == 0) { continue outer; } } nums.add(i); } // 使用Toast顯示統計出來的全部質數 Toast.makeText(CalPrime.this , nums.toString() , Toast.LENGTH_LONG).show(); } } }; Looper.loop(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); etNum = (EditText)findViewById(R.id.etNum); calThread = new CalThread(); // 啓動新線程 calThread.start(); } // 爲按鈕的點擊事件提供事件處理函數 public void cal(View source) { // 建立消息 Message msg = new Message(); msg.what = 0x123; Bundle bundle = new Bundle(); bundle.putInt(UPPER_NUM , Integer.parseInt(etNum.getText().toString())); msg.setData(bundle); // 向新線程中的Handler發送消息 calThread.mHandler.sendMessage(msg); } }
Fragment是Android3.0後引入的一個新的API,他出現的初衷是爲了適應大屏幕的平板電腦, 固然如今他仍然是平板APP UI設計的寵兒,並且咱們普通手機開發也會加入這個Fragment, 咱們能夠把他當作一個小型的Activity,又稱Activity片斷!想一想,若是一個很大的界面,咱們 就一個佈局,寫起界面來會有多麻煩,並且若是組件多的話是管理起來也很麻煩!而使用Fragment 咱們能夠把屏幕劃分紅幾塊,而後進行分組,進行一個模塊化的管理!從而能夠更加方便的在 運行過程當中動態地更新Activity的用戶界面!另外Fragment並不能單獨使用,他須要嵌套在Activity 中使用,儘管他擁有本身的生命週期,可是仍是會受到宿主Activity的生命週期的影響,好比Activity 被destory銷燬了,他也會跟着銷燬!
1、安裝ant
到官方主頁http://ant.apache.org下載新版(目前爲Ant1.8.1)的ant,獲得的是一個apache-ant-1.8.1-bin.zip的壓縮包。將其解壓到你的硬盤上,例如:C:\apache-ant-1.8.1。
2、配置環境變量
window中設置ant環境變量:
ANT_HOME C:/ apache-ant-1.8.1
path C:/ apache-ant-1.8.1/bin
classpath C:/apache-ant-1.8.1/lib
注意:【
配置環境變量:個人電腦----屬性-----高級----環境變量
如:ANT_HOME:C:\apache-ant-1.8.1
PATH:%ANT_HOME%\bin (爲了方便在dos環境下操做)
實驗了老是失敗,沒辦法換成地址 C:/ apache-ant-1.8.1/bin,而再也不使用變量。。。成功了。。
】
3、驗證ant
爲了驗證ant是否成功安裝,能夠進行以下操做:
依次選擇:開始->運行->cmd,輸入以下命令:ant
若是出現以下內容,說明安裝成功:
Buildfile: build.xml does not exist!
Build failed
【說明ant安裝成功!由於ant默認運行build.xml文件,這個文件須要咱們創建。】
查看版本:ant -version
但若是出現以下內容,說明安裝失敗:(能夠重複前述步驟,直至安裝成功。)
'ant' 不是內部或外部命令,也不是可運行的程序或批處理文件。
從別處移動過來的:
使用:
(1)在D盤根目錄下創建build.xml
1<?xml version="1.0" encoding="GBK"?>
2<project name="測試腳本" default="copyfile" basedir="." >
3 <target name="copyfile">
4 <copy file="d:/a.txt" todir="e:/Temp" overwrite="true" />
5 </target>
6</project>
(2)在D盤根目錄下創建文件a.txt。
(3)進入dos,
d:
ant
此時可在E:/Temp目錄下見到文件aa.txt,內容與a.txt同樣,即拷貝成功!
Cd\進入根目錄
Cd d:aa鎖定d盤下的aa文件夾
D:則直接進入d盤下的aa文件夾
ant install.demo
ant start.demo
/**
* 判斷主鍵是否重複
*/
public boolean isExist(Row row){
String boxCode = getCellValue(row.getCell(4));
if("".equals(boxCode)){
return true;
}else{
return resBoxService.exist(boxCode);
}
}
@Override
public boolean exist(Serializable id) {
if(id==null)return false;
return getAbstractDao().exist(id);
}
fh=new com.eshine.jbpm.util.FlowHelper();
String cell=formData.get("tt").toString();
String sql3="INSERT INTO repo_in_log(IN_CODE,REPO_CODE) VALUES(?,?)";
fh.executeSql(sql3,"348",cell);
public List<ResCommunity> getCommunityList(){
String hql = "from ResCommunity a where a.communityName!='' group by a.communityName";
List<ResCommunity> resCList = resCommunityDao.find(hql, null);
return resCList;
}
mstsc--輸入服務器的IP地址--輸入服務器的用戶名和密碼--點擊開始--關機--最上面選擇從新啓動(不選擇點擊不了肯定)
若是隻使用select distinct [name] from [table]的話後面就不能加order by [score]了
select name,score from tablename group by name,score order by score;
select distinct COMMUNITY_NAME from res_community where COMMUNITY_NAME!=''
出現空的話,xml解析數據會出錯
SQL2000裏的數據類型爲datetime默認值getdate()
mysql建表語句裏把字段default now()?? 這個是不行的,now是在你insert或者update時候寫入的,好比: insert into 表 (字段) values (now());
<input type='hidden' name='hide_author' value='${(visitor.name)!""}'/>
kcontext.setVariable("setInCode",inCode);將inCode賦值給流程變量setInCode,後面的節點使用input data mapping引用setInCode
//hql
StringBuffer hql = new StringBuffer();
hql.append("select new com.eshine.ump.repo.bo.RepoIn(b.repoName,a.matName")
.append(",a.matModel,a.matUnit,a.inNum,b.inTime,b.inMan,b.inType)")
.append("from RepoInMaterail a,RepoInLog b ")
.append("where a.id.inCode = b.inCode");
//查詢條件
StringBuffer params = new StringBuffer();
String matName = form.get("matName");
if(matName !=null && !"".equals(matName)){
params.append(" and a.matName = '" + matName + "'");
}
String repoName = form.get("repoName");
if(repoName !=null && !"".equals(repoName)){
params.append(" and b.repoName = '" + repoName + "'");
}
//查詢
if(params.toString().length()==0){
//查詢相同入庫編號的記錄
Pager p = new Pager();
return this.pageByHqls(hql.toString(), p, null);
}else{
//根據條件查詢
hql.append(params);
Pager p = new Pager();
return this.pageByHqls(hql.toString(), p, null);
}
}-Xmx512M -XX:MaxPermSize=512M
$("input[name='data[F05A]']").change(function() {
var $selectedvalue = $("input[name='data[F05A]']:checked").val();
// alert($selectedvalue);
if ($selectedvalue == "IsorNo.yes") {
$("input[name='data[F05C]']").parent().parent().parent().hide();
} else {
}
});
Freemark換行
${((cname_index+1)%5==0)?string('<tr></tr>','')}
若要顯示:當前日期加時間(如:2009-06-12 12:00)
function CurentTime()
{
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
var hh = now.getHours(); //時
var mm = now.getMinutes(); //分
var clock = year + "-";
if(month < 10)
clock += "0";
clock += month + "-";
if(day < 10)
clock += "0";
clock += day + " ";
if(hh < 10)
clock += "0";
clock += hh + ":";
if (mm < 10) clock += '0';
clock += mm;
return(clock);
}
var myDate = new Date();
myDate.getYear(); //獲取當前年份(2位)
myDate.getFullYear(); //獲取完整的年份(4位,1970-????)
myDate.getMonth(); //獲取當前月份(0-11,0表明1月)
myDate.getDate(); //獲取當前日(1-31)
myDate.getDay(); //獲取當前星期X(0-6,0表明星期天)
myDate.getTime(); //獲取當前時間(從1970.1.1開始的毫秒數)
myDate.getHours(); //獲取當前小時數(0-23)
myDate.getMinutes(); //獲取當前分鐘數(0-59)
myDate.getSeconds(); //獲取當前秒數(0-59)
myDate.getMilliseconds(); //獲取當前毫秒數(0-999)
myDate.toLocaleDateString(); //獲取當前日期
var mytime=myDate.toLocaleTimeString(); //獲取當前時間
myDate.toLocaleString( ); //獲取日期與時間
jQuery.ligerDialog.
$.ligerDialog.warn('提示內容')
function onKeySearch(event){
if(event.keyCode == 13)
search();
}
</script>
</head>
<body onkeypress="onKeySearch(event)">
Js亂碼
var toBoxView = 'viewInfo(\"' + row.boxCode + '\");'
var html = "<div style='text-align:left;margin-left:25px;'>"
+ "<a style='' href='javascript:void(0)' onclick='"+toBoxView+ "'>[箱體編號]: "
set JAVA_OPTS=-Xms64m -Xmx768m -XX:PermSize=128M -XX:MaxNewSize=256m -XX:MaxPermSize=256m
1.js文件中使用encodeURI()方法。
login_name = encodeURI(encodeURI(login_name));
2.action中URLDecoder解碼
loginName = java.net.URLDecoder.decode(loginName,"UTF-8");
2.綁定事件
$(".switchbox").each(function(i, ele) {
$(ele).click(function(){
$(".switchbox").css("border-bottom","0px solid #30AED6");
$(this).css("border-bottom","2px solid #30AED6");
$(".switchbox").attr("id","");
$(this).attr("id","now");
if($(this).attr("name")=="box"){
var width = $('body').width() * 0.8;
var height = $('body').height() * 0.98;
分享| 2015-02-04 08:54灬奈丶何氵 | 瀏覽 783 次
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction("com.google.zxing.client.android.SCAN");
intent.setClassName("com.google.zxing.client.android", "com.google.zxing.client.android.CaptureActivity");
startActivityForResult(intent, 0);
}
這段代碼的括號內的代碼的意思是什麼?如今我主要看不懂的是最後一行的startActivityForResult(intent, 0);這行的做用和意思是什麼?
2015-02-04 09:33提問者採納
最後一行和startActivity區別是
在這個activity裏面會重寫這個方法onActivityResult(int requestCode, int resultCode, Intent data);當跳轉到CaptureActivity後執行能夠返回給上面你提供代碼的activity數據經過setResult( int resultCode, data); 來傳遞。有點相似回調、
裏面的0就是重寫方法裏面的第一個參數用來判斷的做用。
1.解析簡單的josn格式字符串
String msg = "{'rs':0,'fs':'登陸成功!'}";
JSONObject jsonObject = new JSONObject(msg);
System.out.println(jsonObject.getString("fs"))
1. List receiveList = offDao.findByHql(hql, page, row);
2. if(receiveList.size()>0&&receiveList!=null){
3. Iterator it = receiveList.iterator();
4. while(it.hasNext()){
5. Object[] object = (Object[])it.next();
6. OffAnnouncementReceive offReceive = new OffAnnouncementReceive();
7. String consigneeid=object[0].toString();
8. String flgs = object[1].toString();
9. String sendmail = object[2].toString();
10. String sendPeo = object[4].toString();
11. Date sendDate = (Date)object[5];
12. String announcementReceiveId = object[6].toString();
13. offReceive.setAnnouncementReceiveId(announcementReceiveId);
14. offReceive.setConsigneeId(consigneeid);
15. offReceive.setSendmailId(sendmail);
16. if(sendDate!=null&&!sendDate.equals("")){
17. offReceive.setSendDate(sdf.format(sendDate));
18. }
19. }
20. }
使用sql返回的list<Object>轉成須要的實體對象,看下面的Map的使用,很方便(須要將Query對象setResultTransformer):
[java] view plain copy
1. List list = session.createSQLQuery(sql)
2. .setResultTransformer(
3. Transformers.ALIAS_TO_ENTITY_MAP)
4. .list();
5. //此時,每一個Object能夠轉換成一個Map
6. Map map = (Map) list.get(i);
7. map.get("student_id"); //這裏的key 必定是 數據庫對應的字段名才行
作項目的時候遇到這樣的問題,hibernate執行SQL語句返回來的list集合調試斷點的時候檢查list集合有值,可是返回action遍歷的時候在list.get(i);這句話時報異常,調試結果是list集合爲空,查找到的結果就是用SQL語句不能自動轉換成bean對象,因此要轉換成數組形式在進行遍歷,這時返回的list集合裏的值就能夠遍歷出來了.
偷個懶把別人的代碼粘過來了,還有個錯誤沒有寫,有時間在總結吧:
Hibernate執行sql語句
Hibernate執行sql語句:
BasicServiceImpl basicServiceImpl = new BasicServiceImpl();
String hql = "select * from AccountInfo where selfId='0000100003' or(left(selfId,10)='0000100004' and
nodeSum=0)";
*寫SQL語句的時候作好給表名起個別名
TManager tManager = TManagerImpl.getInstance();
List accountList = tManager.getSession().createSQLQuery(hql).list();
//List accountList = tManager.getSession().createSQLQuery(hql).addEntity(AccountInfo.class).list();
for(int i=0;i<accountList.size();i++){
Object[] objects = (Object[])accountList.get(i);
for(int j=0;j<objects.length;j++){
System.out.println(objects[j].getClass().getName());// 從這個輸出結果能夠看出,objects[j]的
值其實是AccountInfo的屬性(表的字段)而不是AccountInfo對象,
}
System.out.println(objects.length);
}
信息: java.lang.ClassCastException:Ljava.lang.Object; cannot be cast to net.yjiasoft.sss.table.AccountInfo
分析:原來是查詢出來的字段並不能自動轉換爲bean對象,因此要添加addEntity(Clazz class)。
擴展:
1.SQL返回一個Map對象,也就是說在在list裏包含多個Map,代碼以下
Query query = session.createSQLQuery("select id,name from Tree t where pid in (select id from Tree) ").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //返回一個map,KEY:爲DB中名稱一致(大小寫一致)遍歷list時就能夠
Map map = (Map)list.get[i];
map.get("id");map.get("name");來取值。按你的SQL語句select後的字段名來做爲map的Key,但這個key必須與數據庫中的字段名如出一轍。
2.能夠用做函數方面的。如
Query query = session.createSQLQuery("select sum(id) SUMID from Tree t where pid in (select id from Tree)
.addScalar("SUMID",Hibernate.INTEGER) //轉換類型,按DB中的type轉
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //返回一個map,KEY:爲DB中名稱一致(大小寫一致)
直接就map.get("SUMID")能夠取值了
還有一點就是這個方法在Hibernate3.2版本上才能正常運行。
3.hibernate 中createQuery與createSQLQuery二者區別是:
前者用的hql語句進行查詢,後者能夠用sql語句查詢
前者以hibernate生成的Bean爲對象裝入list返回
後者則是以對象數組進行存儲
因此使用createSQLQuery有時候也想以hibernate生成的Bean爲對象裝入list返回,就不是很方便
忽然發現createSQLQuery有這樣一個方法能夠直接轉換對象
Query query = session.createSQLQuery(sql).addEntity(XXXXXXX.class);
XXXXXXX 表明以hibernate生成的Bean的對象,也就是數據表映射出的Bean。
呵呵之後多注意,仍是時不時的要看看hibernate各個對象方法的使用。
還有另一個相關的小細節應注意:
好比有這樣一個po
PO: User.class
properties: userId,userName
DDL: create table tuser (userid varchar(10),username varchar(20));
當執行:
session.createQuery("from User u").list()時生成的SQL:
select userid,username from tuser;
當執行:
session.createQuery("from User u").iterator()時生成的SQL:
select userid from tuser;
能夠看出list()一次將數據從數據庫中讀出直接填充到List中
iterator()將數據的主鍵從數據庫中讀出,當循環這個Iterator時才添加執行:
select userid,username from user where userid=?;把數據讀出。
在不一樣的應用範圍使用不一樣的方法,具體在hibernate應用中應當注意。
select * from " + tableName + " where 1=0
用於查看錶結構,而不讀取數據記錄
public boolean isTableCreate(String tableName) {
try {
String sql = "select * from " + tableName + " where 1=0";
jdbcDao.queryForList(sql);
return true;
} catch (Exception e) {
return false;
}
}
工做流
初始化:KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kbase = kContainer.getKieBase("kbase");
RuntimeManager manager = createRuntimeManager(kbase);
RuntimeEngine engine = manager.getRuntimeEngine(null);
KieSession ksession = engine.getKieSession();
TaskService taskService = engine.getTaskService();
啓動流程(建立流程實例)
// start a new process instance
Map<string, object=""> params = new HashMap<string, object="">();
params.put("employee", "krisv");
params.put("reason", "Yearly performance evaluation");
ksession.startProcess("org.jbpm.demo.evaluation", params);//流程id,傳入參數
System.out.println("Process started ...");
完成任務
// complete Self Evaluation
List<tasksummary> tasks = taskService.getTasksAssignedAsPotentialOwner("krisv", "en-UK");
TaskSummary task = tasks.get(0);
System.out.println("'krisv' completing task " + task.getName() + ": " + task.getDescription());
taskService.start(task.getId(), "krisv");
Map<string, object=""> results = new HashMap<string, object="">();
results.put("performance", "exceeding");
taskService.complete(task.getId(), "krisv", results);
// john from HR
tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
task = tasks.get(0);
System.out.println("'john' completing task " + task.getName() + ": " + task.getDescription());
taskService.start(task.getId(), "john");
results = new HashMap<string, object="">();
results.put("performance", "acceptable");
taskService.complete(task.getId(), "john", results);
// mary from PM
tasks = taskService.getTasksAssignedAsPotentialOwner("mary", "en-UK");
task = tasks.get(0);
System.out.println("'mary' completing task " + task.getName() + ": " + task.getDescription());
taskService.start(task.getId(), "mary");
results = new HashMap<string, object="">();
results.put("performance", "outstanding");
taskService.complete(task.getId(), "mary", results);
System.out.println("Process instance completed");
manager.disposeRuntimeEngine(engine);
manager.close();
System.exit(0);
}
http://download.eclipse.org/bpmn2-modeler/updates/nightly/luna/(jbpm插件)
項目名稱:網上書店系統 開發工具:myeclipse、mysql、tomcat 硬件環境: 軟件環境: 項目描述:前臺主要實現了通常網上購書所具備的功能。包括:用戶的註冊、登陸,書籍的展現、搜索、購物車和訂單的生成。用戶進入用戶中心後,能夠修改本身的基本信息,查看訂單信息和取消訂單。 後臺主要是實現購書網站的管理功能。員工登陸後臺管理系統後,能夠修改本身的基本信息,同時根據本身的權限能夠進行相關的操做。後臺管理系統主要是完成如下功能:書籍信息、書籍分類、訂單的處理和會員管理。責任描述:完成數據庫的設計、主界面的佈局和設計、文檔的編寫。
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
ActionContext.getContext().put("orgList", (List) map.get("orgList"));
<s:select list="#request.orgList" listValue="name" listKey="orgCode" name="stockVO.orgCode" id="orgCode" onchange="getStoreSelectList(this.value)" /><font color="red">*</font>
<!-- 加載資源文件 其中包含變量信息,必須在Spring配置文件的最前面加載,即第一個加載 classpath:jdbc_dev.properties,-->
<context:property-placeholder location="classpath:jdbc.properties,classpath:config.properties,classpath:webservice/ws.properties" />
<!-- 定義視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="prefix">
<value>/views/</value>
</property>
<property name="suffix">
<value>.html</value>
</property>
</bean>
<!-- 設置freeMarker的配置文件路徑 -->
<bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:freemarker.properties"/>
</bean>
<!-- 配置freeMarker的模板路徑 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!--property name="freemarkerSettings" ref="freemarkerConfiguration"/-->
<property name="templateLoaderPaths">
<list>
<value>/views/</value>
<value>/ftl/</value>
</list>
</property>
<property name="defaultEncoding" value="utf-8" />
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
<!-- 自動導入的模板 -->
<prop key="auto_include">head.ftl,jbpm_head.ftl</prop>
</props>
</property>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
<!-- 配置freeMarker視圖解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
<property name="contentType" value="text/html; charset=utf-8" />
<property name="cache" value="true" />
<property name="suffix" value=".html" />
<property name="order" value="0" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="requestContextAttribute" value="request"/>
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/login.do"/>
<!-- 設定web應用的環境參數 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- hibernate lazy filter -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>coreSessionFactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 錯誤/異常處理頁面 -->
<error-page>
<error-code>500</error-code>
<location>/views/core/error/error_500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/views/core/error/error_404.jsp</location>
</error-page>
<!-- 定義首頁 -->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
@Override
public List<String> queryParentIdList() {
List list=find("select distinct parentId from DtType");
return list;
}
@Override
public List<DtType> query(String parentId) {
return this.find("from DtType where parentId = ? order by parentId,id asc",parentId);
}
public Map<String, List<DtType>> getDtTypeMap() {
List<String> objectNameList=DtTypeDao.queryParentIdList();
Map<String, List<DtType>> map=new HashMap<String, List<DtType>>();
for(String objectName:objectNameList){
List<DtType> DtTypes=this.query(objectName);
map.put(objectName, DtTypes);
}
return map;
}
緩存類
@Component
public class ContextListener implements ApplicationContextAware {
private static ServletContext cxt;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
try {
WebApplicationContext webContext=(WebApplicationContext)applicationContext;
cxt=webContext.getServletContext();
ServletUtil.contextPath=cxt.getContextPath();
FileUtil.setBasePath(cxt.getRealPath("/"));
FileUtil.setServletClassesPath(FileUtil.getBasePath()+"/WEB-INF/classes/");
cxt.setAttribute("projectName", Config.getProject_name());
Map<String, List<DTEntity>> DtCache=DTUtil.enumMap();
cxt.setAttribute("DtCache", DtCache);
} catch (Exception e) {
e.printStackTrace();
}
}
}
設置緩存枚舉類
/**
* 基數數據枚舉接口
、
*/
public interface DT {
/**
* 獲取枚舉名
* @return
*/
public String getName();
/**
* 獲取數據名稱
* @return
*/
public String getDtName();
}
/**
* 枚舉總類
*/
public class DTEnum {
/**
* Pon 使用狀態
*/
public static enum PonState implements DT{
ready("預分配"),
using("正使用"),
free("空閒");
private String dtName;
private PonState(String dtName) {
this.dtName = dtName;
}
public String getName(){
return name();
}
@Override
public String getDtName() {
return dtName;
}
}
}
/**
* 獲取 枚舉類數據
* @return
*/
public static Map<String, List<DTEntity>> enumMap() {
Map<String, List<DTEntity>> cache = new HashMap<String, List<DTEntity>>();
Class[] enumArgs = DTEnum.class.getClasses();
for (Class enumArg : enumArgs) {
if (enumArg.isEnum()) {
String clazzName = enumArg.getSimpleName();
List<DTEntity> entryList = new ArrayList<DTEntity>();
DT[] enums = (DT[]) enumArg.getEnumConstants();
for (DT T : enums) {
DTEntity entry = new DTEntity(T.getDtName(), T.getDtName());
entryList.add(entry);
}
cache.put(clazzName, entryList);
}
}
return cache;
}
/**
* 獲取枚舉類值列表
* @param enumArgs
* @return
*/
public static List<DTEntity> enumList(DT enumArgs[]){
List<DTEntity> entyList=new ArrayList<DTEntity>();
for(DT t:enumArgs){
DTEntity enty=new DTEntity(t.getDtName(), t.getDtName());
entyList.add(enty);
}
return entyList;
}
JAVA發送手機短信,流傳有幾種方法:(1)使用webservice接口發送手機短信,這個可使用sina提供的webservice進行發送,可是須要進行註冊;(2)使用短信mao的方式進行短信的發送,這種方式應該是比較的經常使用,前提是須要購買硬件設備,呵呵(3)使用中國網建提供的SMS短信平臺(申請帳號地址:http://sms.webchinese.cn/default.shtml)
本程序主要是運用了中國網建提供的SMS短信平臺,這個短信平臺基於java提供個專門的接口
三個jar包:
commons-codec-1.4
commons-httpclient-3.1
commons-logging-1.1.1
請自行下載,呵呵
GBK編碼發送接口地址:
http://gbk.sms.webchinese.cn/?Uid=本站用戶名&Key=接口安全密碼&smsMob=手機號碼&smsText=短信內容
UTF-8編碼發送接口地址:
http://utf8.sms.webchinese.cn/?Uid=本站用戶名&Key=接口安全密碼&smsMob=手機號碼&smsText=短信內容
獲取短信數量接口地址(UTF8):
http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站用戶名&Key=接口安全密碼
獲取短信數量接口地址(GBK):
http://sms.webchinese.cn/web_api/SMS/GBK/?Action=SMS_Num&Uid=本站用戶名&Key=接口安全密碼
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class SendMsg_webchinese {
public static void main(String[] args)throws Exception
{
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在頭文件中設置轉碼
NameValuePair[] data ={ new NameValuePair("Uid", "本站用戶名"),new NameValuePair("Key", "接口安全密碼"),new NameValuePair("smsMob","手機號碼"),new NameValuePair("smsText","短信內容")};
post.setRequestBody(data);
client.executeMethod(post);
Header[] headers = post.getResponseHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:"+statusCode);
for(Header h : headers)
{
System.out.println(h.toString());
}
String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
System.out.println(result);
post.releaseConnection();
}
}
title.setText("箱體信息 ");
JSONObject jsonObject = new JSONObject(result);
String s1 = "<font>箱體編號:"+jsonObject.getString("boxCode")+"</font><br><br>"
+"<font>箱體名稱:"+jsonObject.getString("boxName")+"</font><br><br>"
+"<font>箱體類型:"+jsonObject.getString("boxType")+"</font><br><br>"
+"<font>箱體芯數:"+jsonObject.getString("capacity")+"</font><br><br>";
info.setText(Html.fromHtml(s1));
info.setMovementMethod(LinkMovementMethod.getInstance());
$(".MINAB").keyup(function(){
if(MINB.val().length!=0&&MINA.val().length!=0){
discount.val(toDecimal(MINA.val()/MINB.val()));
YINA.val(MINA.val()*12)
}
});
function toDecimal(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return false;
}
var f = Math.round(x*100)/100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
rs = s.length;
s += '.';
}
while (s.length <= rs + 2) {
s += '0';
}
return s;
}
for(var i=1;i<7;i++){
var Presale=$("input[name='data[Presale"+i+"]']");
Presale.attr("class","Presale form-item-text");
}
var Presale7=$("input[name='data[Presale7]']");
var total=0;
$(".Presale").keyup(function(){
total=0;
$(".Presale").each(function(i, ele) {
var val=$(ele).val();
if(val.length!=0){
total=parseFloat(total)+parseFloat(val);
}
});
Presale7.val(total)
});
D:\workspace_luna\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Tomcat加內存set JAVA_OPTS=-Xmx1024M -XX:MaxPermSize=1024M
-server -Xms800m -Xmx800m -XX:PermSize=64M -XX:MaxNewSize=256m
-XX:MaxPermSize=128m -Djava.awt.headless=true
編程題
判斷是否爲質數
public static boolean isPrime(int num) {
boolean prime = true;
int limit = (int) Math.sqrt(num);
for (int i = 2; i <= limit; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
return prime;
}
select * from table where date_column between '2011-07' and DATE_ADD('2011-07',INTERVAL 1 MONTH)
查詢一天: select * from table where to_days(column_time) = to_days(now()); select * from table where date(column_time) = curdate(); 查詢一週: select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time); 查詢一個月: select * from table where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(column_time);
Js定時器
1.倒計定時器:timename=setTimeout("function();",delaytime);
2..循環定時器:timename=setInterval("function();",delaytime);
3.用clearTimeout(timename) 來關閉倒計時定時器,而用clearInterval(timename)來關閉循環定時器。
4.圖形報表統計http://www.hcharts.cn/demo/index.php
<script src="<@path/>/js/highcharts/highcharts.js"></script>
<script src="<@path/>/js/highcharts/modules/drilldown.js"></script>
5. <script <a href="mailto:src=\" <@path="">/js/highcharts/modules/data.js\">" >src="<@path/>/js/highcharts/modules/data.js"></script>
6.Double)(objs[1])).floatValue())/10000
使用高性能的服務器、高性能的數據庫、高效率的編程語言、還有高性能的Web容器。
小成本方法:
一、HTML靜態化
1. 將部份內容進行後臺更新的時候進行靜態化,這樣避免了大量的數據庫訪問請求。當咱們每次更新了數據庫中的相應信息之後,咱們即可以從新執行這個方法,將這個頁面從新靜態化,當咱們每次訪問這個網頁的時候便不會每一次都去數據庫中查詢數據了,而是訪問的一個已經一次性生成了的靜態頁面,這也就達到了提升網站運行速度的目標。 //防止瀏覽器緩存,用於從新生成新的html
2. UUID uuid = UUID.randomUUID();
3. Writer out = new OutputStreamWriter(new FileOutputStream(dirPath+"/"+uuid+indexFileName),"UTF-8");
4. ProcessClient.processBody(out);
5. response.sendRedirect("templates/html/"+uuid+"index.html");
二、圖片服務器分離
三、數據庫集羣和庫表散列
負載均衡 1:如何實現多應用服務器間的session共享:(一臺服務器崩潰,另一臺服務器能夠繼續支持)
2:如何分發請求到各個應用服務器實現壓力分解:(這裏的解決方案是用apache作 web服務器)
tomcat內存的設置:1.4GBJVM+256MB的池
[java] view plain copy
1. set JAVA_HOME=C:\JAVA\JDK15
2. set CATALINA_OPTS=-server -Xms 1400m -Xmx1400m -XX:PermSize=256m -XX:MaxPermSize=256m
tomcat線程的設置:初始產生1000線程數最大支持2000線程
[java] view plain copy
1. <Connector port="80" maxHttpHeaderSize="8192"
2. maxThreads="4000" minSpareThreads="1000" maxSpareThreads="2000"
3. enableLookups="false" redirectPort="8443" acceptCount="2000"
4. connectionTimeout="20000" disableUploadTimeout="true" />
Java泛型中的標記符含義:
E - Element (在集合中使用,由於集合中存放的是元素)
T - Type(Java 類)
K - Key(鍵)
V - Value(值)
N - Number(數值類型)
? - 表示不肯定的java類型
S、U、V -2nd、3rd、4th types
爲java配置本地環境變量,並測試java環境是否配置成功。
#vi /etc/profile
JAVA_HOME=/usr/local/java
JRE_HOME=/usr/local/java/jre
CLASSPATH=$JAVA_HOME/lib:$JAVA_HOME/jre/lib
PATH=$JAVA_HOME/bin:$PATH
export PATH CLASSPATH JAVA_HOME
#source /etc/profile
#java -version
2011-07-04 11:19 175461人閱讀 評論(9) 收藏 舉報
分類:
中間件(24)
版權聲明:本文爲博主原創文章,未經博主容許不得轉載。
Linux下Tomcat的安裝配置
一.下載安裝對應的jdk,並配置Java環境。
官網下載地址:
http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u26-download-400750.html
下載將jdk加壓後放到/usr/local目錄下:
[root@master ~]#chmod 755 jdk-6u5-linux-x64.bin
[root@master ~]# ./jdk-6u5-linux-x64.bin
[root@master ~]#mv jdk1.6.0_05 /usr/local
創建/usr/local/下的jdk軟鏈接方便之後版本升級 :
[root@master ~]# ln -s /usr/local/jdk1.6.0_05/ /usr/local/jdk
配置環境變量:
在 /etc/profile 中加入如下內容:
JAVA_HOME=/usr/local/jdk1.6.0_05
JAVA_BIN=/usr/local/jdk1.6.0_05/bin
PATH=$PATH:$JAVA_BIN
CLASSPATH=$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export JAVA_HOME JAVA_BIN PATH CLASSPATH
保存退出
[root@master ~]source /etc/profile
查看java環境變量是否生效
[root@master ~]# java -version
java version "1.6.0_05"
Java(TM) SE Runtime Environment (build 1.6.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 10.0-b19, mixed mode)
測試成功
二.下載安裝tomcat(http://tomcat.apache.org/)
[root@master ~]# unzip apache-tomcat-6.0.30.zip
[root@master ~]# mv apache-tomcat-6.0.30/ /usr/local/
[root@master ~]cd /usr/local/
[root@master local]# ln -s /usr/local/apache-tomcat-6.0.30/ /usr/local/tomcat
[root@master local]# cd tomcat/bin/
[root@master bin]#ls
[root@master bin]#vim catalina.sh
添加如下內容:
CATALINA_HOME=/usr/local/apache-tomcat-6.0.30/
[root@master local]#chmod +x *.sh
三.啓動tomcat服務器
[root@master tomcat]# /usr/local/tomcat /bin/catalina.sh start
Using CATALINA_BASE: /usr/local/apache-tomcat-6.0.30/
Using CATALINA_HOME: /usr/local/apache-tomcat-6.0.30/
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-6.0.30//temp
Using JRE_HOME: /usr/local/jdk1.6.0_05
Using CLASSPATH: /usr/local/apache-tomcat-6.0.30//bin/bootstrap.jar
[root@master logs]# cd /usr/local/tomcat/logs/
[root@master logs]# tail -f catalina.out
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jul 4, 2011 11:06:57 AM org.apache.coyote.http11.Http11Protocol pause
INFO: Pausing Coyote HTTP/1.1 on http-8080
Jul 4, 2011 11:06:58 AM org.apache.catalina.core.StandardService stop
INFO: Stopping service Catalina
Jul 4, 2011 11:06:58 AM org.apache.coyote.http11.Http11Protocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8080
四.在瀏覽器中輸入
http://localhost:8080/(若是不是本機,則輸入對應的ip地址)
測試出現tomcat頁面則測試成功
ps:須要說明的是tomcat的默認測試頁面是放在webapps下面,這個實際上是在server.xml文件中配置的,以下所示:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
[root@SOR_SYS apache-tomcat-6.0.30]# ls
LICENSE NOTICE RELEASE-NOTES RUNNING.txt bin conf lib logs temp webapps work
1)webapps文件夾主要用於web應用程序部署,好比你能夠把你的應用程序包,如war文件拷到該目錄下,容器會自動部署。
2)conf文件夾下主要是放置tomcat的服務器的相關配置文件
五。添加應用,再次進行測試
在webapps目錄下放測試包(注意:webaapps目錄下面主要是放應用包的.war在tomcat重啓訪問後會自動解壓)
[root@master webapps]# pwd
/usr/local/tomcat/webapps
[root@master webapps]# tar -zxvf moni2.tar.gz
[root@master webapps]# ls
docs examples host-manager manager moni2 moni2.tar.gz ROOT
[root@master webapps]# /usr/local/tomcat/bin/catalina.sh start(重啓tomcat)
Using CATALINA_BASE: /usr/local/apache-tomcat-6.0.30/
Using CATALINA_HOME: /usr/local/apache-tomcat-6.0.30/
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-6.0.30//temp
Using JRE_HOME: /usr/local/jdk1.6.0_05
Using CLASSPATH: /usr/local/apache-tomcat-6.0.30//bin/bootstrap.jar
在瀏覽器中輸入以下地址:
http://192.168.55.229:8080/moni2/
六。修改tomcat的監聽端口
[root@master ~]# cd /usr/local/tomcat/conf
[root@master ~]# ls
[root@master ~]# vim server.xml
<Server port="8005" shutdown="SHUTDOWN">【中止tomcat時的端口】
<Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" /> 【tomcat默認的監聽端口是8080,如今改爲8081】
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />【apache+tomcat模式時訪問tomcat的端口】
如今重啓tomcat。訪問http://192.168.55.229:8081/moni2/【注意:這時就須要修改端口了,嘿嘿。。。】
(1)load(InputStream inStream)
這個方法能夠從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。以下面的代碼:
Properties pro = new Properties();FileInputStream in = new FileInputStream("a.properties");pro.load(in);in.close();
(2)store(OutputStream out, String comments)
這個方法將Properties類對象的屬性列表保存到輸出流中。以下面的代碼:
FileOutputStream oFile = new FileOutputStream(file, "a.properties");pro.store(oFile, "Comment");oFile.close();
public static Properties loadProperty(String propFileName) {
InputStream inputStream = PropertiesUtil.class.getResourceAsStream("/"
+ propFileName);
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return properties;
}
Java GC:修改eclipse.ini文件參數。
Eclipse dropins文件夾放插件。
使用自定義標籤函數<%@ taglib prefix="fns" uri="/WEB-INF/tlds/fns.tld" %>
<function>
<description>獲取當前用戶的菜單對象列表</description>
<name>getMenuList</name>
<function-class>com.yida.modules.sys.utils.UserUtils</function-class>
<function-signature>java.util.List getMenuList()</function-signature>
<example>${fns:getMenuList()}</example>
</function>
使用SHIRO的步驟: 1,導入jar 2,配置web.xml 3,創建dbRelm 4,在Spring中配置
@Service @Transactional public class MyShiro extends AuthorizingRealm{ @Inject private UserService userService; /** * 權限認證 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //獲取登陸時輸入的用戶名 String loginName=(String) principalCollection.fromRealm(getName()).iterator().next(); //到數據庫查是否有此對象 User user=userService.findByName(loginName); if(user!=null){ //權限信息對象info,用來存放查出的用戶的全部的角色(role)及權限(permission) SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //用戶的角色集合 info.setRoles(user.getRolesName()); //用戶的角色對應的全部權限,若是隻使用角色定義訪問權限,下面的四行能夠不要 List<Role> roleList=user.getRoleList(); for (Role role : roleList) { info.addStringPermissions(role.getPermissionsName()); } return info; } return null; } /** * 登陸認證; */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authenticationToken) throws AuthenticationException { //UsernamePasswordToken對象用來存放提交的登陸信息 UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken; //查出是否有此用戶 User user=userService.findByName(token.getUsername()); if(user!=null){ //若存在,將此用戶存放到登陸認證info中 return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); } return null;
一、使用註解@AspectJ定義切面
applicationcontext.xml里加入
AOP的XML命名空間和聲明相關schema
命名空間:
xmlns:aop="http://www.springframework.org/schema/aop"
schema聲明:
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
加入<aop:aspectj-autoproxy />標籤
@Aspect
@Service
@Order(1)
public class HttpAspect {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(HttpAspect.class);
public static final String Http_RequestIdentifier = "requestIdentifier";
//用於累加週期
private static long start = 0L;
private static long end = 0L; //控制時鐘週期
private static final long invet = 1000L*60*60L;
private static int callTimes = 0;
/**
* 請求響應頭初始參數設置
*/
@Before("execution(* com.newsoft.http.controller.*Controller.*(..))")//com.newsoft.http.controller包下的*Controller下的全部方法
public void init(JoinPoint pjp)throws Throwable{
if (logger.isDebugEnabled()) {
logger.debug("initParams1 Execute method <"+ pjp.getSignature().getName()+">");
}
javax.servlet.http.HttpServletRequest request = null;
java.io.PrintWriter writer = null;
javax.servlet.http.HttpServletResponse response = null;
Object[] signatureArgs = pjp.getArgs();//從JoinPoint中能夠獲取參數
for (Object signatureArg : signatureArgs) {
if (signatureArg instanceof javax.servlet.http.HttpServletRequest) {
request = (javax.servlet.http.HttpServletRequest) signatureArg;
}
if (signatureArg instanceof java.io.PrintWriter) {
writer = (java.io.PrintWriter) signatureArg;
}
if (signatureArg instanceof javax.servlet.http.HttpServletResponse) {
response = (javax.servlet.http.HttpServletResponse) signatureArg;
}
}
if(null!=response){
response.setContentType("text/html;charset=UTF-8");
}
}
@Around("execution(* com.newsoft.http.controller.*Controller.*(..))"
)
public void checkSign(ProceedingJoinPoint pjp)throws Throwable{
if(logger.isDebugEnabled()){
logger.debug("MobileAspect.checkSign() run target method {}() "+pjp.getSignature().getName());
}
javax.servlet.http.HttpServletRequest request=null;
javax.servlet.http.HttpServletResponse response = null;
java.io.PrintWriter writer=null;
Object[] signatureArgs = pjp.getArgs();
for (Object signatureArg: signatureArgs) {
if (signatureArg instanceof javax.servlet.http.HttpServletRequest) {
request = (javax.servlet.http.HttpServletRequest) signatureArg;
}
if(signatureArg instanceof org.springframework.web.multipart.MultipartHttpServletRequest){
request = (org.springframework.web.multipart.MultipartHttpServletRequest)signatureArg;
}
if (signatureArg instanceof java.io.PrintWriter) {
writer = (java.io.PrintWriter) signatureArg;
}
if (signatureArg instanceof javax.servlet.http.HttpServletResponse) {
response = (javax.servlet.http.HttpServletResponse) signatureArg;
}
}
if(writer==null&&response!=null){
writer = response.getWriter();
}
if(request!=null&&writer!=null){
if(!isSignCorrect(request)){
writer.write(ResultUtil.writePageResult403("Sign is not correct, check your signature,timestamp,items value."));
return;
}
if(action()){
callTimes=0;
}
callTimes++;
if(callTimes>120){
writer.write(ResultUtil.writePageResult403("訪問頻率超過限制."));
return;
}
}
else{
writer.write(ResultUtil.writePageResult403("javax.servlet.http.HttpServletRequest is null error."));
return;
}
try{
pjp.proceed();
}catch(Exception e){
writer.write(ResultUtil.writePageResult500(e));
logger.warn(pjp.getSignature().getName()+ "throw exception: {}",e);
}
}
/**
* 檢查請求是否合法
*/
protected boolean isSignCorrect(HttpServletRequest request) {
boolean result;
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("items");
SignUtil.setToken("payinfo");
result=SignUtil.checkSignature(signature, timestamp, nonce);
if(!result){
logger.info("http請求驗證失敗, 請求驗證,驗證失敗.驗證碼:signature=" + signature+";timestamp="+timestamp+";nonce="+nonce);
}
return result;
}
private boolean action() {
start = System.currentTimeMillis();
if (start > end){
end = start + invet;
return true;
}else{
return false;
}
}
}
java中的==是用來判斷對象所使用的內存地址是否是同一個,進而判斷是否是同一個對象。例如 objA == objB 注意這裏是同一個對象纔會是true,若是不是同一個對象,哪怕兩個對象全部屬性都相同也會返回false。 而equals則是一個方法,你能夠爲本身的類編寫equals方法來判斷是否是相等。這裏String類就提供了equals方法來判斷兩個String對象是否是相同,而不是去判斷兩個String對象是否是同一個對象,由於咱們通常使用中,只關心兩個字符串內容相同與否,而不會關心是否是同一個對象。 出口流水查詢:services/http/getPayInfoLaneexlist?timestamp=1472789678890&signature=2E4353402DC178521B92256D4668FE3EB8592BA9&items={"starttime":"2016-03-28 00:00:00","endtime":"2016-04-01 00:00:00"} 出口流水擴展查詢:services/http/getPayInfoLaneexlistext?timestamp=1472789678890&signature=2E4353402DC178521B92256D4668FE3EB8592BA9&items={"starttime":"2016-03-28 00:00:00","endtime":"2016-04-01 00:00:00"} 獲取路段列表url:services/http/getRoad?timestamp=1472789678890&signature=F975EE6528E455ED5055F345D81D75069AAE81B7 獲取站列表url:services/http/getStation?timestamp=1472789678890&signature=F975EE6528E455ED5055F345D81D75069AAE81B7 HttpClient client = new HttpClient();///建立HttpClient實例 HttpMethod method = new GetMethod(url);//建立請求鏈接方法的實例 method.setRequestHeader( "Content-Type", "text/html;charset=utf-8" ); client.executeMethod( method );//用HttpClient實例的execute方法來執行第二步中建立好的 method 實例 System.out.println( method.getStatusLine() );// 打印服務器返回的狀態 取得目標地址的內容有三種方法: 第一種,getResponseBody,該方法返回的是目標的二進制的byte流; 第二種,getResponseBodyAsString,這個方法返回的是String類型,值得注意的是該方法返回的String的編碼是根據系統默認的編碼方式,因此返回的String值可能編碼類型有誤,在本文的"字符編碼"部分中將對此作詳細介紹; 第三種,getResponseBodyAsStream,這個方法對於目標地址中有大量數據須要傳輸是最佳的。在這裏咱們使用了最簡單的 InputStream inputStream=method.getResponseBodyAsStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = inputStream.read(buffer))) { output.write(buffer, 0, n); } byte[] body = output.toByteArray(); // 打印返回的信息 String aString=new String(body, "utf-8" ); //返回數據 System.out.println("接口返回信息:"+aString); JSONObject jobj =JSONObject.fromObject(aString); //查詢成功 String success=jobj.optString("success"); //返回狀態碼 String msg=jobj.optString("msg"); //異常信息 String errInfo=jobj.optString("errInfo"); //數據壓縮字符串 String data=jobj.optString("data"); //解壓數據 String dataGunzip=ZipUtils.gunzip(data); //System.out.println(dataGunzip); JSONObject jsonobj =JSONObject.fromObject(dataGunzip); method.releaseConnection();// 釋放鏈接 /** * * 使用gzip進行壓縮 */ public static String gzip(String primStr) { if (primStr == null || primStr.length() == 0) { return primStr; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(out); gzip.write(primStr.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (gzip != null) { try { gzip.close(); } catch (IOException e) { e.printStackTrace(); } } } return new sun.misc.BASE64Encoder().encode(out.toByteArray()); } /** * * <p> * Description:使用gzip進行解壓縮 * </p> * * @param compressedStr * @return */ public static String gunzip(String compressedStr) { if (compressedStr == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = null; GZIPInputStream ginzip = null; byte[] compressed = null; String decompressed = null; try { compressed = new sun.misc.BASE64Decoder() .decodeBuffer(compressedStr); in = new ByteArrayInputStream(compressed); ginzip = new GZIPInputStream(in); byte[] buffer = new byte[1024]; int offset = -1; while ((offset = ginzip.read(buffer)) != -1) { out.write(buffer, 0, offset); } decompressed = out.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (ginzip != null) { try { ginzip.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return decompressed; } /** * 使用zip進行壓縮 * * @param str * 壓縮前的文本 * @return 返回壓縮後的文本 */ public static final String zip(String str) { if (str == null) return null; byte[] compressed; ByteArrayOutputStream out = null; ZipOutputStream zout = null; String compressedStr = null; try { out = new ByteArrayOutputStream(); zout = new ZipOutputStream(out); zout.putNextEntry(new ZipEntry("0")); zout.write(str.getBytes()); zout.closeEntry(); compressed = out.toByteArray(); compressedStr = new sun.misc.BASE64Encoder() .encodeBuffer(compressed); } catch (IOException e) { compressed = null; } finally { if (zout != null) { try { zout.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return compressedStr; } /** * 使用zip進行解壓縮 * * @param compressed * 壓縮後的文本 * @return 解壓後的字符串 */ public static final String unzip(String compressedStr) { if (compressedStr == null) { return null; } ByteArrayOutputStream out = null; ByteArrayInputStream in = null; ZipInputStream zin = null; String decompressed = null; try { byte[] compressed = new sun.misc.BASE64Decoder() .decodeBuffer(compressedStr); out = new ByteArrayOutputStream(); in = new ByteArrayInputStream(compressed); zin = new ZipInputStream(in); zin.getNextEntry(); byte[] buffer = new byte[1024]; int offset = -1; while ((offset = zin.read(buffer)) != -1) { out.write(buffer, 0, offset); } decompressed = out.toString(); } catch (IOException e) { decompressed = null; } finally { if (zin != null) { try { zin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return decompressed; } JavaScript encodeURI() 函數可把字符串做爲 URI 進行編碼 JavaScript decodeURI() 函數對 encodeURI() 函數編碼過的 URI 進行解碼。 要進行兩次轉碼纔不會出現亂碼(默認爲UTF-8) encodeURI(encodeURI(http://localhost/qq/index.jsp?title=專業)); java接收參數代碼: String title = request.getParameter("title"); title = URLDecoder.decode(title, "UTF-8");