7.12--SSH学习之Struts上传和下载和Ajax,Json

来源:互联网 发布:家庭网络布线多少米 编辑:程序博客网 时间:2024/06/05 16:30

上传和下载

描述:表单提交上传文件,通过action上传到tomcat下本项目的指定文件夹中;下载时,再从其中罗列出所有文件,进行下载。


1. 上传表单:

<body>    <form action="upfile" method="post" enctype="multipart/form-data">        文件:<input type="file" name="upfile">        <input type="submit" value="上传">    </form>  </body>


2. struts.xml配置文件

<struts>        <!-- 动态方法盗用 -->    <constant name="struts.enable.DynamicMethodInvocation" value="true" />    <constant name="struts.devMode" value="true" />    <package name="default" namespace="/" extends="struts-default">        <action name="upfile" class="com.su.web.action.UpLoadAction">            <result name="success">/success.jsp</result>        </action>        <action name="filelist" class="com.su.web.action.FileListAction">            <result name="success">/downfile.jsp</result>        </action>        <action name="downfile" class="com.su.web.action.DownLoadAction">            <result name="success" type="stream">                <!-- 运行下载的文件的类型:指定为所有二进制文件类型 -->                <param name="contentType">application/octet-stream</param>                <!-- 对应的Action的中流属性 -->                <param name="inputName">currInputStream</param>                <!--  下载头及文件名-->                <param name="contentDisposition">attachment;fileName=${fileName}</param>                <!--  缓冲区大小设置-->                <param name="bufferSize">1024</param>                       </result>        </action>      </package>    </struts>


3. 上传的action

public class UpLoadAction extends ActionSupport {    private File upfile;    private String upfileFileName;    private String upfileContentType;    public File getUpfile() {        return upfile;    }    public void setUpfile(File upfile) {        this.upfile = upfile;    }    public String getUpfileFileName() {        return upfileFileName;    }    public void setUpfileFileName(String upfileFileName) {        this.upfileFileName = upfileFileName;    }    public String getUpfileContentType() {        return upfileContentType;    }    public void setUpfileContentType(String upfileContentType) {        this.upfileContentType = upfileContentType;    }    public String execute() throws Exception{        System.out.println("in UpLoadAction method execute()");        String path = ServletActionContext.getServletContext().getRealPath("/file/"+upfileFileName);        System.out.println(path);        File file = new File(path);        FileUtils.copyFile(upfile, file);        return "success";    }}


4. 上传成功的表单:

<body>    You have uploaded finished!<br>    Now,you can <a href="filelist" style="color: red">download</a>!  </body>


5. 列出文件夹中所有的文件,等待下载,action中的代码如下:

public class FileListAction extends ActionSupport implements RequestAware{    private Map<String,Object> request;    @Override    public void setRequest(Map<String, Object> request) {        // TODO Auto-generated method stub        this.request = request;    }    public String execute() throws Exception{        System.out.println("in FileListAction method execute()");        String path = ServletActionContext.getServletContext().getRealPath("/file");        System.out.println("文件列表路径:"+path);        File file = new File(path);        String[] fileNames = file.list();        request.put("fileNames", fileNames);        return "success";    }}


6. 下载文件的表单:

<body>     <table border="1" cellpadding="0" cellspacing="0" align="center" width="600px">        <tr>            <td>文件序号</td>            <td>文件名</td>            <td colspan="2">操作</td>        </tr>        <s:iterator value="#request.fileNames" var="fileName" status="status">            <tr>                <td><s:property value="#status.count"/></td>                <td><s:property value="#fileName"/></td>                <s:url var="url" value="downfile">                    <s:param name="fileName" value="#fileName"></s:param>                </s:url>                <td><s:a href="%{url}">downLoad1</s:a></td>                <td><a href="downfile?fileName=<s:property value='#fileName'/>">downLoad2</a></td>            </tr>        </s:iterator>        </table>  </body>


7. 下载文件的action

public class DownLoadAction extends ActionSupport {    private String fileName;    private InputStream currInputStream;    public String getFileName() {        try{            fileName = URLEncoder.encode(fileName,"utf-8");        }catch(Exception e){            e.printStackTrace();        }        return fileName;    }    public void setFileName(String fileName) {        try{            fileName = new String(fileName.getBytes("iso-8859-1"),"utf-8");        }catch(Exception e){            e.printStackTrace();        }        this.fileName = fileName;    }    public InputStream getCurrInputStream() {        currInputStream = ServletActionContext.getServletContext().getResourceAsStream("/file/"+fileName);        return currInputStream;    }    public void setCurrInputStream(InputStream currInputStream) {        this.currInputStream = currInputStream;    }    public String execute() throws Exception{        System.out.println("in DownLoadAction method execute()");        System.out.println(fileName);        return "success";    }}



Ajax和Json

  1. Ajax的异步请求:参考http://www.cnblogs.com/simpleZone/p/5113534.html

  2. 示例代码:
<html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->    <script type="text/javascript">    function checkLogin(userName){        var userId = userName.value;        if(userId == ""){            alert("用户名不能为空");            userName.focus();            return ;        }        //获取xmlHttpRequest对象        createXmlHttpRequest();        //拼写访问服务器的url        var url = "servlet/CheckUserExistServlet?userId="+userId;        //xmlHttpRequest对象设置回掉函数        xmlHttpRequest.onreadystatechange=checkUserExistCallBack;        //设置请求参数        xmlHttpRequest.open("GET",url,true);        //发送请求        xmlHttpRequest.send(null);    }    function createXmlHttpRequest(){        if(window.XMLHttpRequest){ //判断当前浏览器是不是支持xmlHttpRequest对象,支持返回true            xmlHttpRequest = new XMLHttpRequest(); //浏览器支持xmlHttpRequest对象,并创建xmlHttpRequest对象        }else{            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");//浏览器不支持xmlHttpRequest对象,并创建代理xmlHttpRequest对象        }    }    function checkUserExistCallBack(){        //请求完成并成功返回,等于4和200        if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){            var result = xmlHttpRequest.responseText;            if(result == "true"){                document.getElementById("userInfo").innerHTML="该用户名已被占用";            }else{                document.getElementById("userInfo").innerHTML="该用户名可以使用";            }        }    }    function clearInfo(){        document.getElementById("userInfo").innerHTML="";    }    </script>  </head>  <body>    <form action="" method="post">        用户名:<input type="text" name="loginId" id="loginId" onblur="checkLogin(this)" onfocus="clearInfo()">        <span id="userInfo" style="color: red;font-size: 12px"></span><br>        密码:<input type="password" id="loginPwd"><br>        <input type="submit" value="注册">        <input type="reset" value="重置">    </form>  </body></html>


3. servlet中,判断用户是否已存在

public class CheckUserExistServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {            doPost(request,response);    }       public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {            System.out.println("in CheckUserExistServlet");            String name = request.getParameter("userId");            PrintWriter pw = response.getWriter();            boolean flag = false;            if(name.equals("Tom")){                flag = true;            }            pw.print(flag);            pw.flush();            pw.close();     }}


运行结果示意:
1. 当输入“Tom”时,表单未提交,通过ajax的异步请求,访问servlet验证用户是否已存在

这里写图片描述

2. 当输入其他用户时,以同样方式访问servlet验证用户是否合理

这里写图片描述


另一个由jquery发起的ajax请求,然后的访问action

<html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>    <script type="text/javascript">        $(function(){    //$(function(){});在页面加载时自动触发            $.ajax({     //$.ajax({});一个由jquery发起的ajax请求                url:"findall",    //action名                type:"POST",      //提交类型                success:function(msg){   //success代表readyState==4&&Status==200,请求完成并成功返回                    for(var i = 0;i< msg.length;i++){                        var newRow = "<tr><td>"+msg[i].stuId+"</td><td>"+msg[i].stuName+"</td><td>"+msg[i].stuGender+"</td><td>"+msg[i].stuAge+"</td><tr>";                        $("#stulist").append(newRow);                    //完成ajax请求需要对页面重新绘制                    }                }            });        });        $(function(){        //$("#searchButton")相当于document.getElementById("searchButton");.bind添加单击事件            $("#searchButton").bind("click",function(){      //,function()匿名函数响应单击事件                var stuName = $("#stuName").val();                var stuGender = $("#stuGender").val();                $.ajax({                    url:"search",                    type:"POST",                    data:{"stuName":stuName,"stuGender":stuGender},                    dataType:"json",                    success:function(msg){                    //清除列表,tr行,eq(0).nextAll(),从第一行往后                        var x = $("#stulist tr").eq(0).nextAll().remove();                        alert(x);                        for(var i = 0;i<msg.length;i++){                            var newRow = "<tr><td>"+msg[i].stuId+"</td><td>"+msg[i].stuName+"</td><td>"+msg[i].stuGender+"</td><td>"+msg[i].stuAge+"</td><tr>";                            $("#stulist").append(newRow);                        }                    }                });            });        });    </script>  </head>  <body>       按姓名检索:<input type="text" name="stuName" id="stuName">&nbsp;&nbsp;       按性别检索: <input type="text" name="stuGender" id="stuGender">&nbsp;&nbsp;       <input type="button" id="searchButton" value="检索"><br>       <table border="1" width="600" id="stulist">        <tr>            <td width="150">ID</td>            <td width="150">姓名</td>            <td width="150">性别</td>            <td width="150">年龄</td>        </tr>       </table>  </body></html>