【问题标题】:How to: Select date, Press Button, Create File, Download File in Struts 2如何:在 Struts 2 中选择日期、按下按钮、创建文件、下载文件
【发布时间】:2016-01-14 21:56:10
【问题描述】:

我想要什么:

如果有人访问该页面,可以选择两个日期并单击一个(单个)按钮下载数据 em> 在所选的两个日期之间。

我已经有的工作:

JSP/web 开发对我来说是新的。这是我的场景,使用datepicker 和JSP 有一个页面,该页面对数据库进行查询,返回两个日期之间的某些数据,并使用此数据创建一个.txt 文件以保存本地

创建文件后,可以按下另一个按钮下载文件。

我需要做什么:

我需要只需要一个按钮来完成两个动作,所以一旦文件保存在本地,下载提示就会出现,并且访问者可以下载了。

由于这些词很常见,很难在搜索引擎上找到我需要的内容。

我需要一个按钮。我不想要看起来像按钮的链接或锚点,这对某些人来说可能是一件容易的事,但我已经失去了两天

信息:

Apache Tomcat:8.0.27 && Netbeans 8.1 && Ubuntu 14.04

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="sj" uri="/struts-jquery-tags"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="resources/css/jtable.css" type="text/css">        
        <link rel="stylesheet" href="resources/css/style.css" type="text/css">
        <link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
        <link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> 
        <script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
        <script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
        <script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
        
        <title></title>
        <script>
            $(document).ready(function(){
                $("#datepicker1").datepicker({
                    maxDate: 0
                });
                $("#datepicker2").datepicker({ 
                    maxDate: 0,
                    onSelect: function(selected) {
                       $("#datepicker1").datepicker("option","maxDate", selected);
                    }
                });
            });
        </script>
    </head>
    <body>
    <center>
        <div class="jtable-main-container" style="width: 60%;">
            <div class="jtable-title">
            <div class="jtable-title-text">
                Recuperaci&oacute;n de Datos
            </div>
        </div>
            <div id="LecturasTableContainer" style="position: relative; text-align: center; font-size: 17px; top: 10px;">
           
                Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1"> <span>&nbsp;</span><span>&nbsp;</span>
                Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
                
                <!-- Button who generate the file -->
                
                <button type="submit" id="LoadRecordsButton" onclick="return confirm('Datos Recuperados');">Generar</button>
            </div>
                <br>  
                
                <!-- Button who download the file -->
                
                <s:form action="download" method="POST">
                    <s:submit value="Descargar" type="button"/>
                </s:form>                                    
        </div>
    
    </center>
    </body>
</html>

“通用”按钮的动作类:

package com.raspberry.struts.action;

import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DataRecovery extends ActionSupport implements ServletRequestAware {
    
    public HttpSession session;
    public Connection c;
    public String fechaFin;// = null;
    public String fechaInicio; // = null;
    
    public String goDataRecovery(){
        session.setAttribute("mainopt", "dataRecovery");
        return SUCCESS;
    }
    
    public String doDataRecovery() throws ParseException, FileNotFoundException{  
        DBControl dato = new DBControl();
        
        fechaInicio = getFechaInicio();
        fechaFin = getFechaFin();      
        
        DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");            
        String fecha = df.format(Calendar.getInstance().getTime());
              
        String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
        
        File archivo = new File ("/media/recovery"+fecha+".txt");
        archivo.getParentFile().mkdirs();
        PrintWriter printWriter;
        
        printWriter = new PrintWriter(archivo);
        printWriter.println (lectura);
        printWriter.close ();    

        return SUCCESS;        
    }
    
    public String getFechaFin() {        
        return fechaFin;
    }
    
    public String getFechaInicio() {
        return fechaInicio;
    }
    
    @Override
    public void setServletRequest(HttpServletRequest hsr) {
        session = hsr.getSession();
    }
}

“Descargar”按钮的操作类:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DownloadAction extends ActionSupport{

    private InputStream fileInputStream;      

    public InputStream getFileInputStream() throws Exception {           
            return fileInputStream;
    }

    public String execute() throws Exception {
            
            DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");            
            String fecha = df.format(Calendar.getInstance().getTime());
            
            fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
            
        return SUCCESS;
    }
}

Struts.xml:

<action name="GetDataRecovery" class="com.raspberry.struts.action.DataRecovery" 
        method="doDataRecovery">
    <interceptor-ref name="SessionValidationStack" />
    <result name="success">main.jsp</result>
    <result name="sessionexpired">index.jsp</result>            
</action>

<action name="download" class="com.raspberry.struts.action.DownloadAction">
    <result name="success" type="stream">
      <param name="contentType">application/octet-stream</param>
      <param name="inputName">fileInputStream</param>
      <param name="contentDisposition">attachment;filename="recovery.txt"</param>
      <param name="bufferSize">1024</param>
    </result>
</action>

【问题讨论】:

  • @user3659052 感谢您的评论,我的按钮已经用于在本地创建 .txt 文件。所以你的参考很有帮助,但那部分已经准备好了。
  • 你说的Servlet类不是Servlet(最后代码sn-p)。它是一个 Struts 动作类(ActionActionSupportServletRequestAware 是 Struts 框架的组件)。
  • 要下载,您需要另一个操作,该操作映射到另一个将执行下载的方法。阅读this答案。
  • @ElberCM S1 和 S2 是基于 servlet 技术构建的不同框架。

标签: java jsp download struts2


【解决方案1】:

如果您关注了example,您应该会看到他正在使用两个操作。一个动作映射到 JSP 页面,另一个用于下载。第一个用于返回 actionless 结果(缺少类属性)。需要通过action来访问JSP页面。如果您遵循这种技术——第一个动作,第二个 JSP,那么您可以使用 Struts2。

您还可以在返回此 JSP 作为结果的不同操作之间共享同一个 JSP。如果您想为两个或多个操作共享同一个 JSP,您应该添加一个包含文件名称/路径的结果。

您可以使用操作类属性(不适用于无操作结果)来保存通过 OGNL/JSTL 或 JSP EL 在 JSP 中可访问的操作范围对象的状态。

您应该在表单中使用“提交”类型的元素,否则使用“按钮”类型并使用 javascript 提交表单(虽然它不涉及s:submit 标签)。

DataRecovery 操作类中,您应该为下载链接或一些boolean 创建一个属性,以指示下载已准备好。只需保留操作名称"download"。如果属性有值,则显示下载按钮。

<s:if test="downloadReady">
    <s:form action="download" method="POST">
        <s:submit type="button" cssClass="btn btn-primary" value="Descargar" />
    </s:form>                 
</s:if>

private boolean isDownloadReady = false;
//getters and setters

并在保存文件后设置此变量。

【讨论】:

    【解决方案2】:

    首先,感谢 @user3659052 @BalusC @Tiny 和 @Roman C ,感谢您的 cmets。所有人都非常乐于助人。

    我很困惑,所以在 cmets 启蒙之后,决定先从一些教程开始,昨天让 web 应用程序运行起来。

    修复“下载按钮”的 struts 动作后,我尝试也在 Descargar Action 类中生成文件,但对数据库的查询为空。

    错误是 datepicker 上的 form ID 指向 Genear Action Class,因此 Descargar Action Class 永远无法获取数据。因此,在将指针更改为“正确”操作后,能够获取日期、创建文件(本地)并在一个操作中下载。 (所以删除了通用动作类)

    Struts .xml(片段)

    <action name="DataRecovery" class="com.raspberry.struts.action.DownloadAction" method="goDataRecovery">
        <interceptor-ref name="SessionValidationStack" />
        <result name="success">main.jsp</result>
        <result name="sessionexpired">index.jsp</result>            
    </action>
    
    <action name="GetRecovery" class="com.raspberry.struts.action.DownloadAction">
        <result name="success" type="stream">
          <param name="contentType">application/octet-stream</param>
          <param name="inputName">fileInputStream</param>
          <param name="contentDisposition">attachment;filename="recovery.txt"</param>
          <param name="bufferSize">1024</param>
        </result>
    </action>  
    

    Descargar 动作类

    package com.raspberry.struts.action;
    
    import static com.opensymphony.xwork2.Action.SUCCESS;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import com.opensymphony.xwork2.ActionSupport;
    import com.raspberry.dao.control.DBControl;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import org.apache.struts2.interceptor.ServletRequestAware;
    
    public class DownloadAction extends ActionSupport implements ServletRequestAware {
    
        public InputStream fileInputStream;
            public HttpSession session;
            public Connection c;
            public String fechaFin;// = null;
            public String fechaInicio; // = null;
    
            public String goDataRecovery(){
                session.setAttribute("mainopt", "dataRecovery");
                return SUCCESS;
            }
    
        public InputStream getFileInputStream() throws Exception {           
                return fileInputStream;
        }
    
            public String doDataRecovery() throws ParseException, FileNotFoundException{
                DBControl dato = new DBControl();
    
                fechaInicio = getFechaInicio();
                fechaFin = getFechaFin();
    
                DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");            
                String fecha = df.format(Calendar.getInstance().getTime());
    
                String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
    
                File archivo = new File ("/media/recovery"+fecha+".txt");
                archivo.getParentFile().mkdirs();
                PrintWriter printWriter;
    
                printWriter = new PrintWriter(archivo);
                printWriter.println (lectura);
                printWriter.close();
    
                return SUCCESS;        
            }
    
            public String getFechaFin() {        
                return fechaFin;
            }
    
            public String getFechaInicio() {
                return fechaInicio;
            }
    
        public String execute() throws Exception {
    
                doDataRecovery();
    
                DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");            
                String fecha = df.format(Calendar.getInstance().getTime());
    
                fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
    
            return SUCCESS;
        }
    
            @Override
            public void setServletRequest(HttpServletRequest hsr) {
                session = hsr.getSession();
            }
    }
    

    JSP

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="s" uri="/struts-tags"%>
    <%@taglib prefix="sj" uri="/struts-jquery-tags"%>
    
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <link rel="stylesheet" href="resources/css/jtable.css" type="text/css">        
            <link rel="stylesheet" href="resources/css/style.css" type="text/css">
            <link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
            <link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> 
            <script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
            <script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
            <script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>        
            <title></title>
            <script>
                $(document).ready(function(){
                    $("#datepicker1").datepicker({
                        maxDate: 0
                    });
                    $("#datepicker2").datepicker({ 
                        maxDate: 0,
                        onSelect: function(selected) {
                           $("#datepicker1").datepicker("option","maxDate", selected);
                        }
                    });
                });
            </script>       
        </head>
        <body>
        <center>
            <div class="jtable-main-container" style="width: 60%;">
                <div class="jtable-title">
                    <div class="jtable-title-text">
                        Recuperaci&oacute;n de Datos
                    </div>
                </div>
                <div style="position: relative; text-align: center; font-size: 17px; top: 10px;">
                    <s:form theme="simple" action="GetRecovery" method="POST" id="LecturasTableContainer">          
                        Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1">
                        <span>&nbsp;</span><span>&nbsp;</span>
                        Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
                        <s:submit value="Descargar" id="LoadRecordsButton" type="button"/>
                    </s:form>
                </div>
            </div>      
        </center>
        </body>
    </html>
    

    再次感谢您的帮助。

    【讨论】:

    • 您应该得到对您有帮助的答案或 cmets。
    • 感谢您的提醒(刚刚做了),祝您度过愉快的一周。 @RomanC​​pan>
    猜你喜欢
    • 2021-06-15
    • 2017-07-24
    • 1970-01-01
    • 2017-03-12
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2017-03-05
    相关资源
    最近更新 更多