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

相关文章

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

MySQL 中的 JSON 查询案例详解

《MySQL中的JSON查询案例详解》:本文主要介绍MySQL的JSON查询的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 的 jsON 路径格式基本结构路径组件详解特殊语法元素实际示例简单路径复杂路径简写操作符注意MySQL 的 J

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

Spring Boot中JSON数值溢出问题从报错到优雅解决办法

《SpringBoot中JSON数值溢出问题从报错到优雅解决办法》:本文主要介绍SpringBoot中JSON数值溢出问题从报错到优雅的解决办法,通过修改字段类型为Long、添加全局异常处理和... 目录一、问题背景:为什么我的接口突然报错了?二、为什么会发生这个错误?1. Java 数据类型的“容量”限制

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

CentOS7更改默认SSH端口与配置指南

《CentOS7更改默认SSH端口与配置指南》SSH是Linux服务器远程管理的核心工具,其默认监听端口为22,由于端口22众所周知,这也使得服务器容易受到自动化扫描和暴力破解攻击,本文将系统性地介绍... 目录引言为什么要更改 SSH 默认端口?步骤详解:如何更改 Centos 7 的 SSH 默认端口1

springboot上传zip包并解压至服务器nginx目录方式

《springboot上传zip包并解压至服务器nginx目录方式》:本文主要介绍springboot上传zip包并解压至服务器nginx目录方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录springboot上传zip包并解压至服务器nginx目录1.首先需要引入zip相关jar包2.然

前端下载文件时如何后端返回的文件流一些常见方法

《前端下载文件时如何后端返回的文件流一些常见方法》:本文主要介绍前端下载文件时如何后端返回的文件流一些常见方法,包括使用Blob和URL.createObjectURL创建下载链接,以及处理带有C... 目录1. 使用 Blob 和 URL.createObjectURL 创建下载链接例子:使用 Blob

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2