一些别人写的代码,只是觉得写得可以自己可以以后拿来使用的
1、关于反射的,如何通过一个只用调用一个方法就可以接接收不同的对象并调用其实例方法:这些类必须实现或者继承同一个父类,然后用里氏替换原则(想想为什么)。
/**
*<strong>这些类必须实现或者继承同一个父类,然后用里氏替换原则</strong>
*/
public class Test {
public static final String packagePrefix = "com.hiiio.box.detection.checkitem.";
public static void main(String[] args) {
try {
App app = new App();
app.setDecodeDir("D:\\app\\abc");
app.setMD5("DDEA34ADDD7A2FD0A7B272E7397F0756");
CheckParam checkParam = new CheckParam(app,true);
Collection<File> list = FileUtils.listFiles(new File("E:\\secubox\\SecurityToolsBox_server\\src\\main\\java\\com\\aspire\\box\\detection\\checkitem"), new String[]{"java"}, true);
int count = 0;
for(File file:list){
//System.out.println(file.getName());
String className = packagePrefix + StringUtils.removeEnd(file.getName(),".java");
if(className.equals("com.aspire.box.detection.checkitem.DefalutCheck")){
continue;
}
count ++;
System.out.println(className);
Class clazz = Class.forName(className);
DefalutCheck check = (DefalutCheck) clazz.newInstance();
CheckResult result = check.check(checkParam);
System.out.println(result + "\n\n");
}
System.out.println("共测试检测项数量 :" + count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* 不同的地方应该使用不同的日志级别
*/
private static Logger logger = LoggerFactory.getLogger(LinkServiceWebSocket.class);
try {
session.disconnect();
} catch (IOException e) {
logger.error("异常:" + e.getMessage(), e);
}
//DEBUG 为程序的调试信息
logger.debug(message);
//INFO 为一般要显示的信息,比如登录登出
logger.info(message);
//WARN 为一般警告,比如session丢失
logger.warn(message);
//ERROR 为严重错误 主要是程序的错误
logger.error(message);
//FATAL 每个严重的错误事件将会导致应用程序的退出
logger.fatal(message);
//ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。
//下面是该接口的原型定义
// java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Device device = DeviceManager.getDeviceModel();
JSONObject json = new JSONObject();
json.put("type", "link");
json.put("data", JSONObject.fromObject(device).toString());
send(json.toString());
logger.info(json.toString());
}
}, 1, 2, TimeUnit.SECONDS);
public class ConfHelper {
//文件路径分割符,适配windows和linux系统
public static String file_separator = System.getProperty("file.separator");
private static String classpath=StringUtils.removeStart(ConfHelper.class.getResource("/").getPath(),"/");
//项目根路径
//public static String user_dir = System.getProperty("user.dir").concat(file_separator).concat("src").concat(file_separator).concat("main").concat(file_separator).concat("resources");
public static String user_dir = StringUtils.removeEnd(classpath, "/");
//**************************************************************************************
//系统配置文件的基本路径
public static final String config_base = user_dir +file_separator + "config" +file_separator;
//系统配置文件的路径
public static final String systemFileName = config_base + "system.properties";
//日志配置文件的路径properties
public static final String log4jFileName = config_base+ "log4j.properties";
//日志配置文件的路径xml格式
public static final String log4jFileName_xml = config_base + "log4j.xml";
//日志配置logback文件
public static final String logback_xml = config_base + "logback.xml";}
var time = new Date().pattern('yyyy-MM-dd HH:mm:ss');
/*----Date的扩展-----*/
/** * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
*/
Date.prototype.pattern = function(fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
"H+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
var week = {
"0": "/u65e5",
"1": "/u4e00",
"2": "/u4e8c",
"3": "/u4e09",
"4": "/u56db",
"5": "/u4e94",
"6": "/u516d"
};
if(/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if(/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
}
for(var k in o) {
if(new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
6、spring中如何在一个静态工具类中注入一个属性(静态属性是不能注入的)
//导入必要的包
import org.springframework.web.context.support.WebApplicationContextUtils;
//万能的实例工厂(华海乐盈)
ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextEvent.getServletContext());
A3ParamDictService a3ParamDictService = (A3ParamDictService)applicationContext.getBean("a3ParamDictService");
//获取所有有效系统参数
List<A3ParamDict> list = a3ParamDictService.getAllValidParamDicts();
7、在Java代码中发送一个HTTP请求
//http连接
HttpURLConnection conn = null;
BufferedReader br = null;
//请求后返回的html内容
StringBuffer resultHtml = new StringBuffer();
//HTTP输出流
PrintWriter out = null;
try{
logger.info("开始向URL地址为【"+consoleUrl+"】发送HTTP请求...........");
URL url = new URL(consoleUrl);
conn = (HttpURLConnection) url.openConnection();
//设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,
//因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
//设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
//POST 请求不能使用缓存
conn.setUseCaches(false);
conn.setRequestProperty("Accept-Charset", "utf-8");
//设置内容请求编码
conn.setRequestProperty("contentType", "utf-8");
//设定请求的方法为"POST",默认是GET
conn.setRequestMethod("POST");
//连接主机的超时时间 单位:毫秒
conn.setConnectTimeout(this.connectTimeout);
//设置从主机读取数据超时 单位:毫秒
conn.setReadTimeout(this.readTimeout);
conn.connect();
//返回状态码
int statusCode = conn.getResponseCode();
8、动态产生的html元素绑定事件,有固定方法$(document).on("click",".checkInfo",function(){}
//下载报告
$(document).on("click",".checkInfo",function(){
var myWebsocket1 = $websocket('ws://localhost/proofread');
//获取id
var id=$(this).parent().parent().find('td:first').text();
//获取报告名称
var reportCheck=$(this).parent().parent().find('td').eq(6).find(".checkInfo").text().trim();
//获取下载链接
var $down=$(this).next();
myWebsocket1.onOpen(function() {
console.log("ProofreadController socketLink success");
myWebsocket1.send("{'actType':'downCheckInfo','priKey':'"+id+"','reportCheck':'"+reportCheck+"'}");
});
myWebsocket1.onMessage(function(msg) {
var jsonStr=msg;
console.log(msg.data);
if(msg.data=="success"){
swal("提示", "报告下载成功!", "success");
$down.show();
}else{
swal("提示", "报告下载失败!", "error");
}
//关闭socket
myWebsocket1.close();
});
});
9、<input type='file'> 标签不能获取到真实的value值,故可以用this
var filepath =this.files[0].path; //就是找到file值
10、关于一些下载
比如当前页面下载 window.open(Url, '_self');
比如 a标签 <a style='display:none;' href='"+reportPath+"' download=''></a>
11、注册数据库驱动,注意类加载器的使用Classloader()和properity类的使用
static{
try {
ClassLoader cl = JdbcUtil.class.getClassLoader();
InputStream in = cl.getResourceAsStream("dbcfg.properties");
Properties props = new Properties();
props.load(in);
driverClass = props.getProperty("driverClass");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
in.close();
} catch (IOException e) {
throw new ExceptionInInitializerError("获取数据库配置文件信息失败");
}
try {
Class.forName(driverClass);//数据库驱动里面实现了静态加载
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("加载驱动失败");
}
}
12、处理并发一个思路
可以把请求存在数据库中,然后起一个线程池去数据库里面处理每个请求
if ("S902B001".equals(routeLog.getSid())) {
// 获取检测项基本信息
CheckItemService checkItemService = (CheckItemService) BeanLocator
.getInstance().getApplicationContext()
.getBean("S902B001");
xmlRstString = checkItemService.getCheckItemXml(routeLog);
} else if ("S900B001".equals(routeLog.getSid())) {
S900B001_POOL_SIZE = Integer.parseInt(ConfigUtil.getInstance().getStringConfig(ConfigUtil.PLATFORM_PROPERTIES, "s900b001_poolSize"));
// 样本基本信息提取
synchronized (Lock.LOCK) {
if (S900B001_ACTIVE >= S900B001_POOL_SIZE) {
logger.error("样本基本信息提取模块繁忙");
throw new SystemBusyException("样本基本信息提取模块繁忙");
}
S900B001_ACTIVE++;
}
try {
SampleProcessSynchService sampleProcessCommon = (SampleProcessSynchService) BeanLocator
.getInstance().getApplicationContext()
.getBean("S900B001");
xmlRstString = sampleProcessCommon
.getSampleBaseInfoSynch(body);
} finally {
S900B001_ACTIVE--;
}
} else if ("S900B002".equals(routeLog.getSid())) {
// 样本基本信息、权限、证书 (三合一接口)
// SampleProcessSynchService sampleProcessCommon
13、protect 修饰符多用在模板模式中,因为protect 修饰的方法只能是在子类和本类中使用,Father f =new Child 多态的使用
14、在泛型中有个小技巧
正如我们上面提到的,Java泛型很大程度上只能提供静态类型检查,然后类型的信息就会被擦除,所以像下面这样利用类型参数创建实例的做法编译器不会通过:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
但是如果某些场景我们想要需要利用类型参数创建实例,我们应该怎么做呢?可以利用反射解决这个问题:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
我们可以像下面这样调用:
List<String> ls = new ArrayList<>();
append(ls, String.class);
15、注意这里是锁this还是锁class的字节码,看这个对象是static修饰的还是实例对象(注意这里是static修饰的)
public class BeanLocator {
private static BeanLocator instance = null;
private ApplicationContext applicationContext = null;
private BeanLocator() {
}
public static BeanLocator getInstance() {
if (instance == null) {
synchronized (BeanLocator.class) {
if (instance == null) {
instance = new BeanLocator();
}
}
}
return instance;
}