杂项
1.@media在IE8不兼容,使用bootstrap的栅格布局,布局都错乱,引入respond.js文件立竿见影。
2.webSocket在IE10有时候会失效.
判断版本:
if(navigator.appName == "Microsoft Internet Explorer"&&navigator.appVersion.match(/10./i)=='10.'){
window.setInterval(loopGetToast, 3000);
}
3.音乐播放
<audio id='music' src=""></audio> <script> // 检查是否正在播放 var isPlaying = false; function play() { var player = document.querySelector('#music'); if (isPlaying) { // 如果正在播放, 停止播放并停止读取此音乐文件 player.pause(); player.src = ''; } else { player.src = '${path}/static/88150832580.mp3'; player.play(); } } </script>
4. var title = $("#title").val().replace(/^\s*|\s*$/g, ""); //标题 replace方法用来替换trim()方法,trim方法不兼容IE8
5. 静态方法中使用非静态变量
/** * 静态方法中使用非静态变量 */ @Component public class AsyncTask { @Autowired protected RedisTemplate redisTemplate; protected static AsyncTask asyncTask; @PostConstruct public void init() { asyncTask = this; asyncTask.redisTemplate = this.redisTemplate; } private static synchronized void send(){ RedisTemplate redisTemplate = asyncTask.redisTemplate; } }
6.springBoot中在方法或者类上加@Async注解,表示是异步类或者方法
7.list去重 new ArrayList(new HashSet(list));
8.线程池正取姿势:
#线程池基本线程数
corePoolSize=10
#线程池最大线程数
maximumPoolSize=100
#线程没有任务后多久回收内存(毫秒)
keepAliveTime=2000
#线程缓冲容量
capacity=200
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(capacity));
9.post请求:
String post_result = CallingInterface.post(jb, login_url + "getUsers"); JSONObject object = (JSONObject) JSONArray.parse(post_result); JSONObject dataJson = object.getJSONObject("data"); JSONArray userList = dataJson.getJSONArray("userList");
import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class CallingInterface { public static String post(JSONObject json,String URL) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic YWRtaW46"); String result = ""; try { StringEntity s = new StringEntity(JSONObject.toJSONString(json), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 发送请求 HttpResponse httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); result = strber.toString(); System.out.println(result); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { System.out.println("请求服务器成功,做相应处理"); } else { System.out.println("请求服务端失败"); } } catch (Exception e) { System.out.println("请求异常"); throw new RuntimeException(e); } return result; } }
10.消息通知轮询,在redis中存放、取出消息
list右侧插入消息: ListOperations lo = redisTemplate.opsForList(); lo.rightPush(Constants.RedisListForLowVersionIE + user_id, str + address); list左侧弹出消费: //获取list操作类 ListOperations lo = redisTemplate.opsForList(); //循环获取redis中list的第一个值,并进行拼接,如果为null证明没有,设置b为false退出循环 String s = (String) lo.leftPop(Constants.RedisListForLowVersionIE + user_id);
11.接口获取入参:
string = securityOutService.analyzeRequestParameter(request); JSONObject data = JSONObject.parseObject(string, JSONObject.class); token = data.getString("token");//用于根据用户id获取用户详细信息
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; @Service @Transactional(readOnly = true) public class SecurityOutService implements InitializingBean { @Autowired private RedisTemplate redisTemplate; public String getTokenByRedis(String key){ BoundValueOperations<String, String> boundValueOps = redisTemplate.boundValueOps(key); return boundValueOps.get(); } /** * 获取post请求中的参数 * @param request * @return * @ */ public String analyzeRequestParameter(HttpServletRequest request) throws IOException{ String string =""; //String data=request.getParameter("data"); String data=null; if(StringUtils.isNotBlank(data)){ string=data; }else{ InputStream inputStream = request.getInputStream(); ByteArrayOutputStream reqDataByteArrayOutputStream = new ByteArrayOutputStream(); // 1、请求数据的获取 int length = request.getContentLength(); System.out.println("length:"+length); if (length == 0) { throw new RuntimeException(); } byte[] b = new byte[1024]; int tempLength = -1; while ((tempLength = inputStream.read(b)) != -1) { reqDataByteArrayOutputStream.write(b, 0, tempLength); } if (reqDataByteArrayOutputStream.size() != request.getContentLength()) {// 读取失败 // throw new RuntimeException(); } string = reqDataByteArrayOutputStream.toString(); } System.err.println("string:\n"+string); return string; } public void responseJsonResult(HttpServletResponse response, Object o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseJsonResult(HttpServletResponse response, List o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseJsonResult(HttpServletResponse response, Map o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseStringResult(HttpServletResponse response, String result) { try { response.getWriter().write(StringUtils.isNotBlank(result)?result:""); }catch (IOException e){ e.printStackTrace(); } } @Override public void afterPropertiesSet() throws Exception { } }
12.返回对象
ReturnObjMap returnObj = new ReturnObjMap(); returnObj.setRespCode(Constant.okCode); returnObj.setMessage(Constant.okMessage); returnObj.setTimeStamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); securityOutService.responseJsonResult(response, returnObj);
import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class ReturnObjMap { private int respCode=-1; private String message=""; private String timeStamp=""; private Map<String,Serializable> data=new HashMap<String, Serializable>(); public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public int getRespCode() { return respCode; } public void setRespCode(int respCode) { this.respCode = respCode; } public Map<String, Serializable> getData() { return data; } public void setData(Map<String, Serializable> data) { this.data = data; } }
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; @Service @Transactional(readOnly = true) public class SecurityOutService implements InitializingBean { @Autowired private RedisTemplate redisTemplate; public String getTokenByRedis(String key){ BoundValueOperations<String, String> boundValueOps = redisTemplate.boundValueOps(key); return boundValueOps.get(); } /** * 获取post请求中的参数 * @param request * @return * @ */ public String analyzeRequestParameter(HttpServletRequest request) throws IOException{ String string =""; //String data=request.getParameter("data"); String data=null; if(StringUtils.isNotBlank(data)){ string=data; }else{ InputStream inputStream = request.getInputStream(); ByteArrayOutputStream reqDataByteArrayOutputStream = new ByteArrayOutputStream(); // 1、请求数据的获取 int length = request.getContentLength(); System.out.println("length:"+length); if (length == 0) { throw new RuntimeException(); } byte[] b = new byte[1024]; int tempLength = -1; while ((tempLength = inputStream.read(b)) != -1) { reqDataByteArrayOutputStream.write(b, 0, tempLength); } if (reqDataByteArrayOutputStream.size() != request.getContentLength()) {// 读取失败 // throw new RuntimeException(); } string = reqDataByteArrayOutputStream.toString(); } System.err.println("string:\n"+string); return string; } public void responseJsonResult(HttpServletResponse response, Object o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseJsonResult(HttpServletResponse response, List o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseJsonResult(HttpServletResponse response, Map o) { try { if(o!=null){ response.getWriter().write(JsonMapper.toJsonString(o)); }else{ response.getWriter().write(""); } }catch (IOException e){ e.printStackTrace(); } } public void responseStringResult(HttpServletResponse response, String result) { try { response.getWriter().write(StringUtils.isNotBlank(result)?result:""); }catch (IOException e){ e.printStackTrace(); } } @Override public void afterPropertiesSet() throws Exception { } }
13.String[] split = url.split("\\(toast\\)");
14.后台路径解码:URLDecoder.decode(task_name,"utf-8");前台:encodeURI(task.task_name) 防止中文路径乱码
15.去除以逗号分隔的字符串中开头和结尾的‘,’和中间的null
private String checkIds(String ids) { boolean isOK=true; if(ids==null){ ids=""; System.err.println("id为null"); } String newStr = ids.trim(); if(newStr.startsWith(",")){ newStr= newStr.substring(1); isOK=false; } if(newStr.endsWith(",")){ newStr=newStr.substring(0,newStr.length()-1); isOK=false; } if(newStr.contains(",null")){ newStr=newStr.replace(",null",""); isOK=false; } if(newStr.contains("null,")){ newStr=newStr.replace("null,",""); isOK=false; } if(isOK){ return newStr; }else{ return checkIds(newStr); } }
15.list去重并保证顺序不变
/** * list去重,并保证顺序不变 * @param persons * @return */ public static List<Serializable> removeDupliByPrassIn(List<TaskObj> persons) { Set set = new HashSet(); List newList = new ArrayList(); for (Iterator iter = persons.iterator(); iter.hasNext(); ) { TaskObj element = (TaskObj) iter.next(); if (set.add(element.getProcInsId())) { newList.add(element); } } return newList; }
16.接口调用 get请求
String param = "{\"procInsId\":\"" + procInsId + "\",\"returnStr\":\"withdrawn\",\"formSign\":\"" + formSign + "\"}";
String result = HttpRequest.sendGet(withdrawnProcess_url_forOffice, "data=" + URLEncoder.encode(param, "utf-8"));
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } }