Java小技巧

来源:互联网 发布:ubuntu新建文件夹 编辑:程序博客网 时间:2024/06/14 23:36

多文件上传

多文件上传实际上也是 单文件上传的 循环(Struts2 获取多文件List 比较方便;使用 apache 组件应该也有获取多个文件的方法吧)

多文件上传有 两种:

1.<input type="file" name="files" multipart />  2.<input type="file" name="file" />  <input type="file" name="file" /><input type="file" name="file" />使用 struts2 时候,最好 name 设置为同一字段(Struts2 为我们封装好了 )

例子

<%@ page language="java" contentType="text/html; charset=GB18030"    pageEncoding="GB18030"%>    <%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"        + request.getServerName() + ":" + request.getServerPort()        + path + "/";   %><html>    <head>        <title>index.html</title>        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">        <meta http-equiv="description" content="this is my page">        <script language="javascript" src="jquery-1.4.2.min.js" type="text/javascript"></script>        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->    </head>    <body>          <form id="uploadform" name="uploadform" method="POST" action="servlet/FileUploadServlet"              ENCTYPE="multipart/form-data">               <table border="1" width="450" cellpadding="4" cellspacing="2"  bordercolor="#9BD7FF">            <tr>                 <td width="100%" colspan="2">                    文件1:<input name="x" size="40" type="file">                 </td>            </tr>                           <tr>                 <td width="100%" colspan="2">                                        文件2:<input name="x" size="40" type="file">                </td>            </tr>             <tr>                 <td width="100%" colspan="2">                    文件3:<input name="x" size="40" type="file">                 </td>            </tr>                       </table>            <br />            <br />                        <table>            <tr>                 <td align="center">                   <input name="upload" type="submit" value="开始上传" />                 </td>            </tr>              </table>        </form>     </body></html>     
public class FileUploadServlet extends HttpServlet {    private File uploadPath;    private File tempPath;    public void doPost(HttpServletRequest req, HttpServletResponse res)            throws ServletException, IOException {        //判断是否是多数据段提交格式        boolean isMultipart = ServletFileUpload.isMultipartContent(req);        if(isMultipart){            DiskFileItemFactory factory = new DiskFileItemFactory();            // 设置文件的下限            factory.setSizeThreshold(4096);            // 设置中转目录            factory.setRepository(tempPath);            ServletFileUpload upload = new ServletFileUpload(factory);            //设置上传文件的上限            upload.setSizeMax(1000000 * 20);            try {                List fileItems = upload.parseRequest(req);                String itemNo = "";                for (Iterator iter = fileItems.iterator(); iter.hasNext();) {                    FileItem item = (FileItem) iter.next();                    //是普通的表单输入域                    if(item.isFormField()) {                        if ("ceshi".equals(item.getFieldName())) {                            itemNo = item.getString();                            System.out.println("这是我的测试-------" + item.getFieldName());                        }                    }                    //是否为input="type"输入域                    if (!item.isFormField()) {                        String fileName = item.getName();                        long size = item.getSize();                        if ((fileName == null || fileName.equals("")) && size == 0) {                            continue;                        }                        //截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());                        item.write(new File(uploadPath, fileName));                    }                }                res.sendRedirect(req.getContextPath() + "/index.jsp");            } catch (Exception e) {                e.printStackTrace();            }        }    }     protected void doGet(HttpServletRequest req, HttpServletResponse res)            throws ServletException, IOException {        doPost(req, res);    }    public void init() throws ServletException {        uploadPath = new File(getServletContext().getRealPath("upload"));        System.out.println("uploadPath=====" + uploadPath);        //如果目录不存在        if (!uploadPath.exists()) {            //创建目录            uploadPath.mkdir();        }        //临时目录        tempPath = new File(getServletContext().getRealPath("temp"));        if (!tempPath.exists()) {            tempPath.mkdir();        }    }}

文件上传方式

先通过ajax上传图片后,把图片的文件名存入session.(单独一个Action处理);
最下面的提交新商品时候:submit()到另一个Action处理; 取出session中文件名(getSession(“imagePath”));
如果为null; (可以提示用户没有上传图片)或者直接保存图片名称就为null;


获取某一ip 访问次数,防止攻击

得到远程客户端IP地址
String remoteAddr=request.getRemoteAddr();
最好在访问时候先判断用户id 是否在黑名单中,直接打回即可 ,不在登录验证等等

另外到数据库中验证时候,先判断session是否已经存在用户(session不为空就不要再次登录验证了 )

另外一种方式,你可以通过s:token防止重复提交,前台页面给他一个友好提示就可以了,人家正常的点击你肯定不能禁止呀!

访问同时加上时间戳, firstAccess lastAccess; 放入session中 ,判断时候取出 相减


Ajax的请求

$.post("Login.action", {            "userid":userid,            "password":password,            "quan":quan        },function(data, status){            data = eval("("+data+")");            if(data == 0){                $("#message").empty();                $("#message").append("账户不存在,请检查后登录");            }            else if(data == 1){                //$("#load").fadeOut("fast");                window.location = "admin.action";            }            else if(data == 2){                //$("#load").fadeOut("fast");                window.location = "teacher.action";            }            else if(data == 3){                //$("#load").fadeOut("fast");                window.location = "student.action";                     }            else if(data == 4){                $("#message").empty();                $("#message").append("账户或密码错误,请重新登录");            }      });  

jdk编译版本

1.用较低版本的编译环境编译源代码,这个时候会限制在开发过程中不能用到 新版本的
新特性 ,低版本的编译,高版本运行是 可以的
2. 用较高版本的运行环境(jre)去 运行高版本编译的文件(jdk) 哦

三元运算符代替c:choose

java中的三元运算符为:条件?条件为true值:条件为false的值
EL也有一样的运算符,用EL的三元运算符有时可以代替c:choose标签,为我们的工作省下很大力气。

比如gender为0显示男,其余显示女,我们可以这么写:

<c:choose><c:when test="${gender eq 0}"></c:when><c:otherwise></c:otherwise></c:choose>

但是不是显得太麻烦了?其实我们这里就可以使用EL表达式中的三元运算符了,上面可以简化为:

${gender eq 0?”男”:”女”}
这样是不是简练了很多?在JSTL和EL处理非A即B的时候,三元运算符简单了许多。

0 0
原创粉丝点击