我的工作日常
1.javabean反射
private User getUser(HttpServletRequest request) { User user =null; try { user = new User(); //获取表单的map集合 Map<String, String[]> map = request.getParameterMap(); for(Map.Entry<String, String[]> m:map.entrySet()){ //获取单个param的name String name = m.getKey(); //获取单个param的value String[] values = m.getValue(); //属性描述器 通过反射机制 PropertyDescriptor pd = new PropertyDescriptor(name, User.class); //获得这个param属性的set方法 Method method = pd.getWriteMethod(); //判断改param名字相同的值的个数是否为一个 if(values.length==1) { //获得该方法的参数类型列表 Class[] types = method.getParameterTypes(); //判断第一个参数的类型是否为数组 if(types[0].isArray()) { //若是则以数组方式存入 method.invoke(user,(Object)new String[]{values[0]}); } else { //若不是则以值方式存入 method.invoke(user, values[0]); } } else { //不为一个就是数组 直接以数组方式存入 method.invoke(user, (Object)values); } } } catch (Exception e) { e.printStackTrace(); } System.out.println(user); return user; }
2.通过ThreadLocal实现sql事务的开启提交和回滚
public class ManagerThreadLocal { private static ThreadLocal<Connection> tl=new ThreadLocal<>();//key value public static Connection getConnection(){ Connection conn = tl.get(); if(conn==null){ conn= C3P0Util.getConnection(); tl.set(conn); } return conn; } //开启事务 public static void startTranscation(){ try { getConnection().setAutoCommit(false);//begin } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //提交事务 public static void commit(){ try { getConnection().commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //回滚事务 public static void rollback(){ try { getConnection().rollback(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //释放资源 public static void close(){ try { getConnection().close();//把连接还回连接池 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.Stl 用法
遍历详细博客:http://www.cppblog.com/biao/archive/2010/12/23/137257.html
</head> <body> <% if(1==1){ out.print("a"); } %> <hr/> <c:if test="${5<=5 }"> aaa </c:if> <hr/> <c:set var="num" value="${2 }"></c:set> <c:choose> <c:when test="${num==1 }">aaa</c:when> <c:when test="${num==2 }">bbb</c:when> <c:when test="${num==3 }">ccc</c:when> <c:otherwise>ddd</c:otherwise> </c:choose> <hr/> <c:forEach var="i" begin="1" end="10" step="2" > ${i }<br/> </c:forEach> <hr/> <% List list=new ArrayList(); list.add("aaa"); list.add("bbb"); list.add("ccc"); list.add("ddd"); list.add("eee"); list.add("fff"); list.add("ooo"); request.setAttribute("list", list); %> <c:forEach items="${list} " var="i" > ${i }<br/> </c:forEach> <hr/> <!-- 重点 --> <table border="1"> <tr> <td>数据</td> <td>索引</td> <td>计数</td> <td>第一个</td> <td>最后一个</td> </tr> <c:forEach items="${list }" var="l" varStatus="vs"> <%-- <tr ${vs.count%2==1?"style='background-color:lime'": "style='background-color:yellow'"}> --%> <tr ${vs.count%2==1?"class='odd'":"class='even'" }> <td>${l}</td> <td>${vs.index }</td> <td>${vs.count }</td> <td>${vs.first }</td> <td>${vs.last }</td> </tr> </c:forEach> </table> </body> </html>
4.表单文件上传
import org.apache.commons.io.*;
import org.apache.commons.fileupload.*;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // String name = request.getParameter("name"); // String phone = request.getParameter("phone"); // System.out.println(name); // System.out.println(phone); //由于表单 上传方式 enctype="multipart/form-data" request.getParameter("name");失效啦 // InputStream is = request.getInputStream(); // int len=0; // byte [] buf=new byte[1024]; // while((len=is.read(buf))!=-1){ // System.out.println(new String(buf,0,len)); // } //要执行文件上传操作 //1.首选判断 表单上传方式时候写的是 enctype="multipart/form-data" boolean ismultipartContent = ServletFileUpload.isMultipartContent(request); if(!ismultipartContent){ throw new RuntimeException(" you form is not multipart/form-data"); } //1.创建DiskFileItemFactory对象 DiskFileItemFactory factory=new DiskFileItemFactory(); //指定临时文件存储的位置 factory.setRepository(new File("d:/aaa")); //2.创建一个ServletFileUpload核心对象 ServletFileUpload sfu=new ServletFileUpload(factory); //解决上传中文名乱码问题 sfu.setHeaderEncoding("UTF-8"); //3.解析request得到表单项集合 try { //限制文件上传大小 //sfu.setFileSizeMax(1024*1024*3);//3M大小 //sfu.setSizeMax(1024*1024*6);//6M List<FileItem> fileItems = sfu.parseRequest(request); //遍历表单项的数据 for(FileItem fileItem:fileItems){ if(fileItem.isFormField()){//普通表单 //处理普通表单 processFormField(fileItem); }else{//上传表单 processUploadField(fileItem); } } }catch(FileUploadBase.FileSizeLimitExceededException e){ throw new RuntimeException("文件过大不能超过3M"); }catch(FileUploadBase.SizeLimitExceededException e){ throw new RuntimeException("总文件过大不能超过6M"); } catch (FileUploadException e) { e.printStackTrace(); } } //处理文件上传 private void processUploadField(FileItem fileItem) { //1上传的文件名 String filename = fileItem.getName();// 文件上传的值 1.jig a.txt D:\1.jpg //2.得到文件输入流 try { // InputStream is = fileItem.getInputStream(); //通过输出流将上传文件保存到磁盘中 String directoryRealPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File storeDirectory=new File(directoryRealPath);//即代表文件 也代表目录 if(!storeDirectory.exists()){ storeDirectory.mkdirs();//创建一个指定目录 } //处理文件名 // filename=filename.substring(filename.lastIndexOf(File.separator)+1); if(filename!=null){ filename = FilenameUtils.getName(filename); } //解决重名为题 filename=UUID.randomUUID()+"_"+filename; //目录打散 //String childDirectory=makChildDirectory(storeDirectory);//2017-08-31 String childDirectory=makChildDirectory(storeDirectory,filename); //构建一个完整路径 //File file=new File(storeDirectory,childDirectory+File.separator+filename);//upload/2017-08-31/1.jpg //创建存储地方 /*FileOutputStream fos=new FileOutputStream(file); int len=0; byte [] buf=new byte[1024]; while((len=is.read(buf))!=-1){ fos.write(buf, 0, len); } fos.close(); is.close();*/ fileItem.write(new File(storeDirectory,childDirectory+File.separator+filename)); fileItem.delete();//清除临时缓存文件 } catch (Exception e) { e.printStackTrace(); } } //优化打散方案 private String makChildDirectory(File storeDirectory, String filename) { int hashCode = filename.hashCode();//字符串转换的32hashCode码 System.out.println(hashCode); String code = Integer.toHexString(hashCode);//将哈希码转换为十六进制 0-9 a-f System.out.println(code); String childDirectory=code.charAt(0)+File.separator+code.charAt(1); //创建指定目录 File file=new File(storeDirectory,childDirectory); if(!file.exists()){ file.mkdirs(); } return childDirectory; } //按照日期打散 private String makChildDirectory(File storeDirectory) { //以日期创建文件夹 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//2017-08-31 String dateDirectory = sdf.format(new Date()); //只管创建目录 File file=new File(storeDirectory,dateDirectory);// /upload/2017-08-31 if(!file.exists()){ file.mkdirs(); } return dateDirectory;//2017-08-31 } //处理普通表单 private void processFormField(FileItem fileItem) { try { String fieldname = fileItem.getFieldName();//name String fieldvalue = fileItem.getString("UTF-8");//如果里面不写utf-8则乱码 // fieldvalue=new String(fieldvalue.getBytes("ISO-8859-1"),"UTF-8"); //解决乱码方法2 //String fieldvalue=fileItem.getString("UTf-8"); System.out.println(fieldname+"\t"+fieldvalue); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5.文件下载
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String filename = "下载订单.csv"; //设置文件名的编码 filename = new String(filename.getBytes("GBK"),"ISO-8859-1"); //告诉浏览器要下载文件 response.setHeader("content-disposition", "attachment;filename="+filename); // response.setHeader("content-type", "image/jpeg");//下载图片 response.setContentType(this.getServletContext().getMimeType(filename));//下载filename类型的文件 //告知服务器使用编码格式 response.setCharacterEncoding("GBK"); //调用业务逻辑 //查询数据库 订单表 //创建输出流 PrintWriter out = response.getWriter(); out.print("牙具,20\n"); out.print("毛巾,210\n"); out.print("牙膏,100\n"); }
6.jquery之ajax
一.邮箱验证
$("#email").blur(function(){ var email = $(this).val(); var params = {"email":email}; var url = "${pageContext.request.contextPath }/servlet/userServlet?method=emailExp"; var regexp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/; if(regexp.test(email)) { $.ajax( { url:url, type:"post", data:params, success:function(d){ if("1"==d) { $("#emailMsg").html("邮箱已被注册"); $("#emailMsg").css("color","red"); $("#btn_active").attr("disabled","disabled"); } else { $("#emailMsg").html("邮箱可以使用"); $("#emailMsg").css("color","green"); $("#btn_active").removeAttr("disabled"); } }, error:function(d){}, dataType:"text" } ); }else { $("#emailMsg").html("邮箱格式不正确"); $("#emailMsg").css("color","red"); $("#btn_active").attr("disabled","disabled"); } });
二.input查询数据回显
$bkmg = $(".searchArticleResultList"); $(".queryString").keyup(function(){ var title = $(this).val(); var params = {"title":title}; var url="${pageContext.request.contextPath }/TopicServlet?method=serchBackMsg"; $.ajax({ url:url, type:"post", data:params, success:function(d){ /*for(var i=0;i<d.length;i++) { var date = d[i]; alert(date.title); } */ $bkmg.css("display","block"); $(d).each(function(){ $bkmg.append("<div onmousedown='mydown(this)' onmouseout='myout(this)' onmousemove='mymove(this)'>"+this.title+"</div>"); }); },error:function(obj){}, dataType: "json" }); }); $(".queryString").blur(function(){ $bkmg.empty(); $bkmg.css("display","none"); }); function mydown(d){ $bkmg.empty(); $bkmg.css("display","none"); $(".queryString").val($(d).text()); } function myout(d){ $(d).css("background","white"); } function mymove(d){ $(d).css("background","gray"); }
7.form表单中input type为submit.button的控件和button控件点击不提交表单的处理方案
即在其onclick事件中添加return false语句即可
(1).<button onclick="history.go(-1);return false;">返回</button> (2).<input type="submit" value="返回" onclick="history.go(-1);return false;"/>