struts2实现word文件上传和在线阅读

1. 新建工程后,先引入struts2的jar包:右击项目---myeclipse---add struts capabilities,引入后,web.xml中会生成对应的filter:

  1. <filter> 
  2.     <filter-name>struts2</filter-name> 
  3.     <filter-class> 
  4.         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 
  5.     </filter-class> 
  6.   </filter> 
  7.   <filter-mapping> 
  8.     <filter-name>struts2</filter-name> 
  9.     <url-pattern>*.action</url-pattern> 
  10.   </filter-mapping> 

一个filter对应一个filter-mapping.也可以写自己的filter,比如写一个过滤器用来设置编码的,这样,就可以在web.xml中配置写好的action.

2. struts2的配置:

  1. <package namespace="/" name="default" extends="struts-default"> 
  2.     <action name="UploadAction"  
  3.             class="com.up.action.UploadAction" > 
  4.      <!-- 将savePath设置为"根目录下的upload文件夹" --> 
  5.      <param name="savePath">/upload</param> 
  6.      <result name="show">/showc.jsp</result> 
  7.      <result name="error">/index.jsp</result> 
  8.      </action> 
  9.    </package> 


首先是package,之后是action,action中对应一个或者多个result,如果有其他需要,再进行其他的设置,比如上面的param是用来上传文件的.

3. 编写对应的action,并在jsp页面中进行请求:

编写action要按照配置的struts.xml文件进行编写,action要继承ActionSupport类,并override public String execute(){} 方法

4. 最后,页面和action的传递工作可以由get和set方法实现.

哇,现在才发现,struts2真的很方便呢~

接下来记录今天写的功能啦!

首先用struts2自带的文件上传功能进行文件的上传,之后是读取上传的word文档.读取word文档用到了一个jar包:tm-extractors-0.4,在网上有下的.

具体代码如下:

index.jsp:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  2. <%@ taglib uri="/struts-tags" prefix="s"%> 
  3. <
  4. String path = request.getContextPath(); 
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
  6. %> 
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  9. <html> 
  10.   <head> 
  11.     <base href="<%=basePath%>"> 
  12.      
  13.     <title>Demo of upload files</title> 
  14.     <script type="text/javascript"> 
  15.     function checkup(){ 
  16.     //提示信息 
  17. var div=document.getElementById("uploadname"); 
  18. if(document.form1.gljueyi.value.length==0){ 
  19.                 div.innerHTML="请选择要上传的文件"
  20.                 document.form1.gljueyi.focus(); 
  21.                 return false; 
  22. return  true;    
  23. </script> 
  24.     <meta http-equiv="pragma" content="no-cache"> 
  25.     <meta http-equiv="cache-control" content="no-cache"> 
  26.     <meta http-equiv="expires" content="0">     
  27.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  28.     <meta http-equiv="description" content="This is my page"> 
  29.     <!--
  30.     <link rel="stylesheet" type="text/css" href="styles.css">
  31.     --> 
  32.     <style> 
  33. *{ font-size:14px;} 
  34. </style> 
  35.   </head> 
  36.    
  37. <body> 
  38. <form action="UploadAction.action" name="form1" method="post" enctype="multipart/form-data"> 
  39. <table> 
  40.   <tr> 
  41. <td > </td> 
  42.       <td ><span id="message" style="font-size:16px;color:red;" > 
  43.        
  44.       </span></td> 
  45. </tr> 
  46.   <tr> 
  47. <td style="line-height:30px;">选择上传的文件:</td> 
  48. <td> <input type="file" id="uploadname" name="upload"></td> 
  49. </tr> 
  50. <tr> 
  51. <td style="line-height:30px;"><input type="submit" name="button" id="button" value="提交" onClick="return checkup();"></td> 
  52. <td><input type="reset" name="button2" id="button2" value="重置"></td> 
  53. </tr> 
  54.  
  55. </table> 
  56. </form> 
  57. </body> 
  58. </html> 

struts.xml文件:

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 
  3. <struts> 
  4. <package namespace="/" name="default" extends="struts-default"> 
  5.     <action name="UploadAction"  
  6.             class="com.up.action.UploadAction" > 
  7.             <!-- 将savePath设置为"/upload" --> 
  8.             <param name="savePath">/upload</param> 
  9.      <result name="show">/showc.jsp</result> 
  10.      <result name="error">/index.jsp</result> 
  11.      </action> 
  12.    </package> 
  13. </struts>     

UploadAction.java:

  1. package com.up.action; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileInputStream; 
  5. import java.io.FileOutputStream; 
  6. import java.text.SimpleDateFormat; 
  7. import java.util.Date; 
  8.  
  9. import org.apache.struts2.ServletActionContext; 
  10. import org.textmining.text.extraction.WordExtractor; 
  11.  
  12. import com.opensymphony.xwork2.ActionSupport; 
  13.  
  14. public class UploadAction extends ActionSupport { 
  15.     File upload; 
  16.     String uploadContentType; 
  17.     String uploadFileName; 
  18.      
  19.     String str; 
  20.      
  21.      
  22.     private String savePath; 
  23.  
  24.     public String execute() throws Exception{ 
  25. //      System.out.println("开始上传单个文件-----------------------"); 
  26. //        System.out.println(getSavePath()); 
  27. //        System.out.println("==========" + getUploadFileName()); 
  28. //        System.out.println("==========" + getUploadContentType()); 
  29. //        System.out.println("==========" + getUpload()); 
  30. //        以服务器的文件保存地址和原文件名建立上传文件输出流 
  31.         /*
  32.          * 文件上传工作
  33.          */ 
  34.         String doc = getFilename(getUploadFileName()); 
  35.         String filename =getTime() + "." + doc; 
  36.          
  37.         //文件上传 
  38.         //getSavepath()是获取struts.xml中传过来的值 
  39.         FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + filename); 
  40.         FileInputStream fis = new FileInputStream(getUpload()); 
  41.         byte[] buffer = new byte[1024]; 
  42.         int len = 0
  43.         while ((len = fis.read(buffer)) > 0
  44.          { 
  45.             fos.write(buffer , 0 , len); 
  46.         } 
  47.          
  48.         int ch = 0
  49.         String path = ServletActionContext.getServletContext().getRealPath("/upload"); 
  50.         try
  51.             FileInputStream in = new FileInputStream (path + "\\" + filename); 
  52.             WordExtractor extractor = new WordExtractor();   //这里用tm-extractors-0.4.jar实现对word的读取操作.  
  53.             str = extractor.extractText(in);  
  54.             System.out.println(str);  
  55.                 }catch(Exception e){ 
  56.                 e.printStackTrace(); 
  57.             } 
  58.  
  59.         return "show"
  60.     } 
  61.      
  62.    String getTime(){ 
  63.        /**
  64.         * 获取时间来定义文件名称
  65.         * @return String as the name of the file
  66.         */ 
  67.         SimpleDateFormat formatter_f = new SimpleDateFormat("yyyyMMddHHmmss"); 
  68.         Date now = new Date(); 
  69.         String time = formatter_f.format(now); 
  70.         return time; 
  71.    } 
  72.    String getTrueTime(){ 
  73.        /**
  74.         * 获取当前时间
  75.         * @return String time
  76.         */ 
  77.         SimpleDateFormat formatter_f = new SimpleDateFormat("yyyy-MM-dd"); 
  78.         Date now = new Date(); 
  79.         String time = formatter_f.format(now); 
  80.         return time; 
  81.    } 
  82.     
  83.    String getFilename(String name){ 
  84.         
  85.        /**
  86.         * 获取文件名的后缀
  87.         * @return String
  88.         */ 
  89.        int i = name.lastIndexOf(".")+1
  90.         return name.substring(i,name.length()); 
  91.    } 
  92.    //接受依赖注入的方法 
  93.    public void setSavePath(String value) 
  94.     { 
  95.        this.savePath = value; 
  96.    } 
  97.  
  98.    @SuppressWarnings("deprecation"
  99.     private String getSavePath() throws Exception  
  100.     { 
  101.        return ServletActionContext.getRequest().getRealPath(savePath); 
  102.    } 
  103.     
  104.  
  105.    public void setUpload(File upload)  { 
  106.        this.upload = upload;  
  107.    } 
  108.  
  109.    public void setUploadContentType(String uploadContentType)  { 
  110.        this.uploadContentType = uploadContentType;  
  111.    } 
  112.  
  113.    public void setUploadFileName(String uploadFileName)  { 
  114.        this.uploadFileName = uploadFileName;  
  115.    } 
  116.  
  117.    public File getUpload()  { 
  118.        return (this.upload);  
  119.    } 
  120.  
  121.    public String getUploadContentType()  { 
  122.        return (this.uploadContentType);  
  123.    } 
  124.  
  125.    public String getUploadFileName()  { 
  126.        return (this.uploadFileName);  
  127.    } 
  128.  
  129. public String getStr() { 
  130.     return str; 
  131.  
  132. public void setStr(String str) { 
  133.     this.str = str; 
  134.     

最后显示,showc.jsp:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  2. <%@ taglib uri="/struts-tags" prefix="s"%> 
  3. <
  4. String path = request.getContextPath(); 
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
  6. %> 
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  9. <html> 
  10.   <head> 
  11.     <base href="<%=basePath%>"> 
  12.      
  13.     <title>Demo of upload files</title> 
  14.     <meta http-equiv="pragma" content="no-cache"> 
  15.     <meta http-equiv="cache-control" content="no-cache"> 
  16.     <meta http-equiv="expires" content="0">     
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  18.     <meta http-equiv="description" content="This is my page"> 
  19.     <!--
  20.     <link rel="stylesheet" type="text/css" href="styles.css">
  21.     --> 
  22.     <style> 
  23. *{ font-size:14px;} 
  24. </style> 
  25.   </head> 
  26.    
  27. <body> 
  28. <s:property value="str"/> 
  29. </body> 
  30. </html> 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值