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");