java开发总结

js代码

  1. 打开 chrome devtools Ctrl + Shift + I
  2. 使用命令 Ctrl + Shift + P
  3. 关键字 >snippet

详情

另外之前用的一个工具 https://runjs.dev
字符串去除:
var str = “衣冠禽兽”;
var removeStr = “衣冠”;
str.replace(removeStr,"");//禽兽

String str = “衣冠禽兽”;
String removeStr = “衣冠”;
System.out.println(str.replace(removeStr,""))//禽兽

查看端口占用情况:

netstat -aon|findstr “8180” --查看端口“8180”被占用的PID
tasklist|findstr “12860” --根据PID查找程序

字符串截取:
s=s.substring(2)//获取下标2以后的
s=s.substring(0,10)//获取前10位
大小写转换:
str.toLowerCase()//将String转换为小写
str.toUpperCase()//将Srtring转换为大写


String转int:
int a = Integer.parseInt(str);
int b = Integer.valueOf(str).intValue()


mapper中的特殊字符转义:
< <= > >= & ’ "
< <= > >= & ’ "

“”,
" AND TEL=#{pidTempCardInfoDO.tel}",
“”,
“”,
“AND DOB like concat(’%’,#{pidTempCardInfoDO.dob},’%’)”,
“”,

//遍历输出
sss = “1,2,3”.split(",")//数据库字段
strs = “1,2,3”.split(",")//实体类字段数组
for(i=0;i console.log(""",")
console.log("“AND “+sss[i]+” = #{RkJwtlryDjDO.”+strs[i]+"}",")
console.log(""",")
}

控制台打印sql语句:

时间比较:

var oDate1 = new Date(date1);
var oDate2 = new Date(date2);
if(oDate1.getTime() > oDate2.getTime()){
console.log(‘第一个大’);
}
//时间转换
var rq1 = $(’#rq’).val();
var rq= new Date(Date.parse(rq1.replace(/-/g, “/”)));

字符串比较
StringUtils.equals(null,“1”)
easyui清空表单内容:
$(’#id’).form(‘clear’);


like查询条件中的特殊字符转换(mysql)

function ConvertSql(sql){
if(sqlnull||sql’’||sql==undefined)
return ‘’;
sql = sql.replace("[", “\[”);
sql = sql.replace("", "\");
sql = sql.replace("%", “\%”);
sql = sql.replace("\","\\");
sql = sql.replace("","\");
return sql;
}


自定义异常
public class PopulationSystemException extends RuntimeException{
private static final long serialVersionUID = 825735813739186162L;

/**
 * Construct this class with detail message of "message".
 */
public PopulationSystemException(String message) {
    this(message, null);
}

/**
 * Construct this class with detail message of "message", as well as the original exception
 */
public PopulationSystemException(String message, Throwable origException) {
    super(message, origException);
}

/**
 * Construct this class with original exception
 */
public PopulationSystemException(Throwable origException) {
    super(origException.getMessage(), origException);
}

}

导出

/**

  • 导出统用方法

  • 秦坤 2019-11-21 19:23:58

  • @param response HttpServletResponse

  • @param mpglList 导出的参数

  • @param fileName 导出文件名

  • @param h1 导出文件表头(数组,需与实体类字段对应)

  • @param dataTitles 表头对应的实体类字段(数组,需与表头字段对应)

  • @throws IOException
    */
    public static void export(HttpServletResponse response,List mpglList,String fileName,String [] h1,String [] dataTitles) throws IOException {
    if(h1!=null&&dataTitles!=null&&h1.length>1&&dataTitles.length>1){
    throw new PopulationSystemException(“数据列与字段不匹配”);
    }
    OutputStream out = null;
    try {
    out = response.getOutputStream();

     fileName = fileName+".xls";
     response.setCharacterEncoding("GBK");
     response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
     List> list=new ArrayList<>();
     Map map =new HashMap<>();
     for (Object o:mpglList) {
         map.clear();
         Map beanMap = new BeanMap(o);
         list.add(beanMap);
     }
    
     map.clear();
     HSSFWorkbook workbook = new HSSFWorkbook();
     HSSFSheet sheet = workbook.createSheet(fileName);
     HSSFFont font = workbook.createFont();
     font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗
     HSSFCellStyle cellStyle = workbook.createCellStyle();
     cellStyle.setFont(font);
     //cellStyle.setWrapText(true);
     cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
     cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
     sheet.setDefaultColumnWidth((short) 10);
     HSSFRow row = sheet.createRow(0);
     row.setHeight((short) 330);
     HSSFRow row1 = sheet.createRow(1);
     row.setHeight((short) 330);
     for (int i = 0; i < h1.length; i++) {
         HSSFCell cell = row.createCell(i);
         cell.setCellStyle(cellStyle);
         cell.setCellValue(h1[i]);
     }
     HSSFCellStyle cellStyle2= workbook.createCellStyle();
     cellStyle2.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
     if (!list.isEmpty()) {
         for (int i = 0; i < list.size(); i++) {
             row = sheet.createRow(i + 1);
             map = list.get(i);
             for (int j = 0; j < dataTitles.length; j++) {
                 HSSFCell cell = row.createCell(j);
                 cell.setCellStyle(cellStyle2);
                 cell.setCellValue(map.get(dataTitles[j])==null?"":map.get(dataTitles[j]).toString());
             }
         }
     }
     workbook.write(out);
    

    }catch (Exception e) {
    e.printStackTrace();
    }finally {
    if(out != null){
    out.flush();
    out.close();
    }
    }
    }

文件操作
https://docs.qq.com/doc/DSEp0ZE5OdXpQYVF1
https://www.cnblogs.com/nmdzwps/p/5898684.html

部分选择(非常实用)
alt+shift+鼠标左键:


class操作:

private void output(Object object){
Class clazz = object.getClass();
// 获取实体类的所有属性信息,返回Field数组
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println(field.getName());//属性名
}

}
System.out.println(field);//属性详细信息
//获取实体类的所有方法,返回Method数组
Method [] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);//方法详细信息
System.out.println(method.getName());//方法名
}
新建一个TestField测试类,读取类中所有属性集合
Class.getDeclaredFields()可以读取出类所有字段数组Field[]
setAccessible(true)设置属性可以方法
Field.get读取属性值
Field.set设置属性值

读取类中的方法,Class.getMethods(),返回方法数组Method[]
method.getName()可以获取方法的名称
method.invoke(obj)可以动态调用方法


Kill all task
例:Taskkill -f -im java.exe
css:

显示:KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲id').attr('styl…(’#id’).attr(‘style’,‘display:none’);

显示:KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲id").css('displ…("#id").css(‘display’,‘none’);

显示:KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲id").show().add…("#id").hide().removeClass(“show”);

$("#id").prop(“readonly”, true);//只读
body{//不可选
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
style=“pointer-events: none;”//不可选


图片上传:

function tpsc(){
var formData = new FormData();
formData.append(‘file’, $(’#file’)[0].files[0]); //添加图片信息的参数
formData.append(‘sizeid’,123); //添加其他参数
$.ajax({
url: ‘http://syrk.hubei.gov.cn/api/ldrk/tpsc’,
type: ‘POST’,
cache: false, //上传文件不需要缓存
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (data) {
if(data.code==1){
alert(“成功”)
}else{
alert(“失败”)
}
},
error: function (data) {
tipTopShow(“上传失败”);
}
})
}

@PostMapping("/tpsc")

public Map tpsc(MultipartFile file) throws IOException {
Map map =new HashMap();
//获取项目根路径
// File f = new File(this.getClass().getResource("/").getPath());
//如果文件夹不存在,则创建文件夹 f + “\resources\jpg”
File dirPath = new File( “F:\临时文件\2019-5-17”);
if(!dirPath.exists()){
dirPath.mkdir();
}
String fileName = file.getOriginalFilename();
String format =Utils.getUUID()+fileName.substring(fileName.lastIndexOf("."));
File uploadFile = new File(dirPath +"/"+format );
try {
FileCopyUtils.copy(file.getBytes(), uploadFile);
map.put(“code”,“1”);
} catch (IOException e) {
e.printStackTrace();
map.put(“code”,“0”);
}
return map;
}


常见正则:

var 身份证 = /(\d{15}$)|(^\d{18}$)|(\d{17}(\d|X|x)KaTeX parse error: Can't use function '\u' in math mode at position 18: …; var 中文名 = /^[\̲u̲4E00-\u9FA5]{2,…/;
var 手机号 = /(^1[3|4|5|7|8|9]\d{9}KaTeX parse error: Undefined control sequence: \d at position 7: )|(^09\̲d̲{8})/;
var 日期 =
/^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;

var namereg = /1+(·[\u4E00-\u9FA5A-Za-z]+)*$/;

页面延时:

1 function doSomething() {
2   alert(“hello world”);
3 }
4 var setTime = setTimeout(function () {
5 doSomething()
6 }, 3000);

获取随机数:

//取x-y之间的随机整数
页面: var result=Math.floor(Math.random()(y+1-x)+x);
数据库获取0-10: FLOOR(RAND() * 10)
数据库获取2000-5000: select floor(RAND()
(5000+1-2000)+2000);
数据库获取随机一条数据:
select * from T_ORG where NORG_NO > 1956 ORDER BY rand() LIMIT 1
数据库获取随机时间(1990-2004):
select
CONCAT(FLOOR(1990+(RAND()*25)),’-’,LPAD(FLOOR(1+(RAND()*12)),2,0),’-’,LPAD(FLOOR(3+(RAND()*8)),2,0))

SELECT ywlsh,count(ywlsh) num FROM T_DZ_JLX_XQ_DJ GROUP BY ywlsh HAVING num>1

select cxbjdm from T_QUXCUN where length(cxbjdm) < 3

SELECT count(cxbjdm) a,(select count(1) from t_quxcun where cxbjdm is null) b,sum(a,b) c FROM T_QUXCUN WHERE 1=1 AND cxbjdm is not null
java 时间格式转换:

//Date转String
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String dateString = formatter.format(currentTime);

//String转Date
DateFormat format1 = new SimpleDateFormat(“yyyy-MM-dd”);
DateFormat format 2= new SimpleDateFormat(“yyyy年MM月dd日 HH时mm分ss秒”);
Date date = null;
String str = null;
str = “2007-1-18”;
try {
date = format1.parse(str);
data = format2.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}

文本编辑(换行,去空格等)
http://www.5ixuexiwang.com/str/compress.php

layer弹窗

layer.msg(‘未关联地址和已关联地址修不能同时查询’,{time:5000,icon:1~7});

layer.open({
type: 1 //Layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加
载层)4(tips层),
title: ‘title here’, //标题
area: [‘390px’, ‘330px’], //宽高
shade: 0.4, //遮罩透明度
content: $("#test"),//支持获取DOM元素
btn: [‘确定’, ‘取消’], //按钮组
scrollbar: false ,//屏蔽浏览器滚动条
yes: function(index){//layer.msg(‘yes’); //点击确定回调
layer.close(index);
showToast();
},
btn2: function(){//layer.alert(‘aaa’,{title:‘msg title’}); ////点击取消回调
layer.msg(‘bbb’);//layer.closeAll();
}

跨页面传值的几种方法:
该案例是从a.html向b.html页面传递参数
1.a.html的代码

跳转
2.点击跳转按钮可以将input标签的value值传递到b.html

function jump() { var s = document.getElementsByTagName(‘input’)[0]; location.href=‘7.获取参数.html?’+‘txt=’ + encodeURI(s.value);}
1.b.html中的代码

var loc = location.href;var n1 = loc.length;var n2 = loc.indexOf('=');var txt = decodeURI(loc.substr(n2+1,n1-n2));var box = document.getElementById('box');box.innerHTML = txt; 2. ajax获取另一个页面的数据

$.ajax({ url:“2.html”, type:“get”,     data:“aa” success:function (data) { $("#a").html(data); } })
3. 本地存储sessionStorage 或 localStorage (两者用法一样)
添加 3种方法

localStorage.infos=“aaaa”;localStorage[“infos”]=“aaaa”;localStorage.setItem(“infos”,“aaaa”);// console.log(localStorage.infos);
获取

localStorage.infos;localStorage[“infos”];localStorage.getItem(“infos”);
删除 2种方法

localStorage.removeItem(“infos”);localStorage.clear(“infos”);
4.cookie
创建cookie
如果要多次创建 cookie ,重复使用这个方法即可。
document.cookie=‘key=val’;
访问cookie
document.cookie


js页面 时间格式转换:
js将时间转换成时间戳
1.js获取当前时间戳的方法

var timestamp1 = Date.parse(new Date());

var timestamp2 = (new Date()).valueOf();

var timestamp3 = new Date().getTime();
第一种:获取的时间戳是把毫秒改成000显示,第二种和第三种是获取了当前毫秒的时间戳。
2.js获取制定时间戳的方法

var oldTime = (new Date(“2015/06/23 08:00:20”)).getTime()/1000;
getTime()返回数值的单位是毫秒。
演示
二.js把时间戳转为为普通日期格式
1.Date toLocaleString方法

function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}KaTeX parse error: Double superscript at position 5: /,' '̲); } parseInt()…/,’ ')验证替换以:开始有一位或二位数字的结束字符串,就是秒;替换为空
演示
所以我们可以利用正则表达式改变我们想要的日期格式。
2.Date 属性方法

function add0(m){return m<10?‘0’+m:m }
function format(shijianchuo)
{
//shijianchuo是整数,否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+’-’+add0(m)+’-’+add0(d)+’ ‘+add0(h)+’:’+add0(mm)+’:’+add0(s);
}

演示
三.封装的时间格式器

/**

  • 时间戳格式化函数
  • @param {string} format 格式
  • @param {int} timestamp 要格式化的时间 默认为当前时间
  • @return {string} 格式化的时间字符串
    /
    function date(format, timestamp){
    var a, jsdate=((timestamp) ? new Date(timestamp
    1000) : new Date());
    var pad = function(n, c){
    if((n = n + “”).length < c){
    return new Array(++c - n.length).join(“0”) + n;
    } else {
    return n;
    }
    };
    var txt_weekdays = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”];
    var txt_ordin = {1:“st”, 2:“nd”, 3:“rd”, 21:“st”, 22:“nd”, 23:“rd”, 31:“st”};
    var txt_months = ["", “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”];
    var f = {
    // Day
    d: function(){return pad(f.j(), 2)},
    D: function(){return f.l().substr(0,3)},
    j: function(){return jsdate.getDate()},
    l: function(){return txt_weekdays[f.w()]},
    N: function(){return f.w() + 1},
    S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : ‘th’},
    w: function(){return jsdate.getDay()},
    z: function(){return (jsdate - new Date(jsdate.getFullYear() + “/1/1”)) / 864e5 >> 0},

// Week
W: function(){
var a = f.z(), b = 364 + f.L() - a;
var nd2, nd = (new Date(jsdate.getFullYear() + “/1/1”).getDay() || 7) - 1;
if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
return 1;
} else{
if(a <= 2 && nd >= 4 && a >= (6 - nd)){
nd2 = new Date(jsdate.getFullYear() - 1 + “/12/31”);
return date(“W”, Math.round(nd2.getTime()/1000));
} else{
return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
}
}
},

// Month
F: function(){return txt_months[f.n()]},
m: function(){return pad(f.n(), 2)},
M: function(){return f.F().substr(0,3)},
n: function(){return jsdate.getMonth() + 1},
t: function(){
var n;
if( (n = jsdate.getMonth() + 1) == 2 ){
return 28 + f.L();
} else{
if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
return 31;
} else{
return 30;
}
}
},

// Year
L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
//o not supported yet
Y: function(){return jsdate.getFullYear()},
y: function(){return (jsdate.getFullYear() + “”).slice(2)},

// Time
a: function(){return jsdate.getHours() > 11 ? “pm” : “am”},
A: function(){return f.a().toUpperCase()},
B: function(){
// peter paul koch:
var off = (jsdate.getTimezoneOffset() + 60)*60;
var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
var beat = Math.floor(theSeconds/86.4);
if (beat > 1000) beat -= 1000;
if (beat < 0) beat += 1000;
if ((String(beat)).length == 1) beat = “00”+beat;
if ((String(beat)).length == 2) beat = “0”+beat;
return beat;
},
g: function(){return jsdate.getHours() % 12 || 12},
G: function(){return jsdate.getHours()},
h: function(){return pad(f.g(), 2)},
H: function(){return pad(jsdate.getHours(), 2)},
i: function(){return pad(jsdate.getMinutes(), 2)},
s: function(){return pad(jsdate.getSeconds(), 2)},
//u not supported yet

// Timezone
//e not supported yet
//I not supported yet
O: function(){
var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
if (jsdate.getTimezoneOffset() > 0) t = “-” + t; else t = “+” + t;
return t;
},
P: function(){var O = f.O();return (O.substr(0, 3) + “:” + O.substr(3, 2))},
//T not supported yet
//Z not supported yet

// Full Date/Time
c: function(){return f.Y() + “-” + f.m() + “-” + f.d() + “T” + f.h() + “:” + f.i() + “:” + f.s() + f.P()},
//r not supported yet
U: function(){return Math.round(jsdate.getTime()/1000)}
};

return format.replace(/[]?([a-zA-Z])/g, function(t, s){
if( t!=s ){
// escaped
ret = s;
} else if( f[s] ){
// a date function exists
ret = fs;
} else{
// nothing special
ret = s;
}
return ret;
});
}


JAVA新特性:
1.Arrays

List list = Arrays.asList( “a”, “b”, “d”,“z”,“g”,“7”,"{" ).sort( (e1, e2 ) -> e1.compareTo( e2 ) );
List list = Arrays.asList(“a”,“b”,“c”);
list.forEach(e->{
System.out.println(e);
});
Arrays.asList(“1”,“2”,“3”).forEach(e->{
System.out.println(e);
});

StringUtils中 isNotEmpty 和isNotBlank的区别
isNotEmpty :
判断某字符串是否非空
StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty("") = false
StringUtils.isNotEmpty(" ") = true
StringUtils.isNotEmpty(“bob”) = true

isNotBlank:
判断某字符串是否不为空且长度不为0且不由空白符(whitespace)构成,
下面是示例:
StringUtils.isNotBlank(null) = false
StringUtils.isNotBlank("") = false
StringUtils.isNotBlank(" “) = false
StringUtils.isNotBlank(”\t \n \f \r") = false

数据库方法转义:
Oracle Mysql 解释
nvl(a,‘1’) ifnull(a,‘1’) a为空则为1,不为空则为a的值
dyh||‘单元’ concat(dyh,‘单元’) 多字符串拼接
rownum <= 2 或者 rownum between 0 and 2 LIMIT 0,2 分页查询
to_number(‘11’) //整型
select cast(11 as unsigned int)
//浮点型
select cast(11 as decimal(10,2)) 将字段转换类型
点击查看更多
更多

UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
SQL UNION 语法
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。
SQL UNION ALL 语法
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
另外,UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。

Json转get请求

//json转get请求参数
function json_to_get(data) {
for (var key in data){
if(data[key] === ‘’ || data[key] == null){
delete data[key]
}
}
data = JSON.stringify(data)
data= data.replace(/\t/g,"")
data=data.replace(/"/g,"").replace("{","").replace("}","")
data=data.replace(",","&").replace(":","=")
data = data.replace(/"/g,"").replace(/{/g,"").replace(/}/g,"")
data = data.replace(/,/g,"&").replace(/:/g,"=")
return data;
}

function open_exportLRRK(url,date) {
var num = Math.floor(Math.random()*7)
layer.open({
type:1,
title:‘人口信息引用’,
area:[‘320px’,‘185px’],
shade:0.4,
shift:num,
btn:[‘导出’,‘取消’],
content:’

’ +
‘导出总数量:条’ +

        '
', yes:function (index) { // var page = $("#start").val(); var rows = $("#end").val(); if(rows<1)rows=50; if(rows>60000){ layer.msg("系统只支持六万数据内导出!") return } var data = json_to_get(date); $.fileDownload(window.parent.domain+url+'?page='+1+"&rows="+rows+'&'+data, {}).done(function () { }).fail(function () { }); layer.close(index); } })

}


  1. \u4E00-\u9FA5A-Za-z\s ↩︎

你可能感兴趣的:(java)