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

2024-02-09 15:18

本文主要是介绍7.12--SSH学习之Struts上传和下载和Ajax,Json,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上传和下载

描述:表单提交上传文件,通过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;@Overridepublic void setRequest(Map<String, Object> request) {// TODO Auto-generated method stubthis.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();//拼写访问服务器的urlvar url = "servlet/CheckUserExistServlet?userId="+userId;//xmlHttpRequest对象设置回掉函数xmlHttpRequest.onreadystatechange=checkUserExistCallBack;//设置请求参数xmlHttpRequest.open("GET",url,true);//发送请求xmlHttpRequest.send(null);}function createXmlHttpRequest(){if(window.XMLHttpRequest){ //判断当前浏览器是不是支持xmlHttpRequest对象,支持返回truexmlHttpRequest = new XMLHttpRequest(); //浏览器支持xmlHttpRequest对象,并创建xmlHttpRequest对象}else{xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");//浏览器不支持xmlHttpRequest对象,并创建代理xmlHttpRequest对象}}function checkUserExistCallBack(){//请求完成并成功返回,等于4和200if(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>

这篇关于7.12--SSH学习之Struts上传和下载和Ajax,Json的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/694564

相关文章

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素

解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题

《解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘问题》:本文主要介绍解决未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4... 目录未解析的依赖项:‘net.sf.json-lib:json-lib:jar:2.4‘打开pom.XM

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Springboot3+将ID转为JSON字符串的详细配置方案

《Springboot3+将ID转为JSON字符串的详细配置方案》:本文主要介绍纯后端实现Long/BigIntegerID转为JSON字符串的详细配置方案,s基于SpringBoot3+和Spr... 目录1. 添加依赖2. 全局 Jackson 配置3. 精准控制(可选)4. OpenAPI (Spri

MySQL JSON 查询中的对象与数组技巧及查询示例

《MySQLJSON查询中的对象与数组技巧及查询示例》MySQL中JSON对象和JSON数组查询的详细介绍及带有WHERE条件的查询示例,本文给大家介绍的非常详细,mysqljson查询示例相关知... 目录jsON 对象查询1. JSON_CONTAINS2. JSON_EXTRACT3. JSON_TA