Solved

JSP; STRUTS; SERVLET; Help forcing a download; Error 500: Server caught unhandled exception from servlet [action]: Cannot forward. Response already committed. (Servlet 2.3, SRV 8.4)

Posted on 2004-10-20
20
2,873 Views
Last Modified: 2008-01-09

Hi all. I am creating a web app using Websphere and Struts framework. I am stuck at an obstacle and don't know what to do about it. The web app allows the user to upload a file. It then reads the file, validates some information, creates a result file, store the new files name in the session so a link appears on the main page so the user can download the file. Every thing is working except the download portion. I came across a great deal of code about forcing the download through the response stream. I found the following code on another thread.

// **************** BEGIN CODE EXCERPT *******************************
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class DownloadServlet extends HttpServlet {
    private static final String basePath = "/doc";

    public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
    {
        String filePath = request.getPathInfo();
        String filename = request.getParameter( "filename" );
     if( filePath == null && filename != null ) filePath = "/" + filename;
     if( filename == null ) filename = filePath;
     if( filename != null ) filename = (new File(filename)).getName();

        if( filePath != null ) {
          InputStream in = null;
          OutputStream out = null;
          try {
                 in = getServletContext().getResourceAsStream(basePath + filePath);
              if( in != null ) {
                        out = new BufferedOutputStream( response.getOutputStream() );
                        in = new BufferedInputStream( in );
                        String contentType = getServletConfig().getServletContext().getMimeType( filename );
                        if( contentType == null ) contentType = "application/unknow";
                        System.out.println( "contentType: " + contentType );
                        response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
                        int c; while( ( c=in.read() ) != -1 ) out.write( c );
                        return;
                 }
          } finally {
               if( in != null ) try { in.close(); } catch( Exception e ) {}
               if( out != null ) try { out.close(); } catch( Exception e ) {}
          }
     }
     response.sendError( HttpServletResponse.SC_NOT_FOUND );
    }
}

// **************** END CODE EXCERPT *******************************

The code above presents a number of issues. I frankly don't know how I am supposed to use the code, but I know what it does and here is how I have tried using it:

I have a jsp page with a form that forwards the <html:file> to the appropriate action page. Inside of the action page I create a DownloadServlet object and call the service method of that object. The problem is the servlet seems to be null as it gives me a null pointer exception if I call
getServletContext() or anything like that.

Furthermore, if I modify the above code to the following:

import java.io.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class DownloadServlet extends HttpServlet {
//    private static final String basePath = "/doc";

    public void service(HttpServletRequest request,
                                HttpServletResponse response)
        throws ServletException, java.io.IOException
    {
          
        String filePath = Constants.RESULTS_CREATION_ROOT;
        String dummy = null;
        String filename = "results_test.txt";
       
        File f = new File(filePath + filename);

            if(f.exists()) System.out.println("File does exist!");
            
        if( filePath != null ) {
          FileInputStream fis = null;
          InputStream in = null;
          OutputStream out = null;
          try {
                      dummy = f.getPath();
                    fis = new FileInputStream(f.getPath());

              if( fis != null ) {
                        out = new BufferedOutputStream( response.getOutputStream() );
                        in = new BufferedInputStream( fis );
                        String contentType = null; //getServletConfig().getServletContext().getMimeType( filename );
                        if( contentType == null ) contentType = "application/unknow";
                        System.out.println( "contentType: " + contentType );
                        response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
                        int c; while( ( c=in.read() ) != -1 ) out.write( c );
                        return ;
                 }
          } catch(Exception e) {
                System.out.println("An Exception of some sort.");
                  System.out.println(e.getMessage());
                
          }      finally {
               if( in != null ) try { in.close(); } catch( Exception e ) {}
               if( out != null ) try { out.close(); } catch( Exception e ) {}
          }
     }
     response.sendError( HttpServletResponse.SC_NOT_FOUND );
    }


The file is shoved through the response and the download dialogue does appear; HOWEVER, the following error is thrown:

Error 500: Server caught unhandled exception from servlet [action]: Cannot forward. Response already committed. &#40;Servlet 2.3, SRV 8.4&#41;

This error text is actually written out to the file (quite inadvertently might I add).

Even if I copy this function, give it a different name, and put it in my action page it doesn't work. I am really stumped here.

My guess is that I have to run this servlet without fowarding the page, but I can't do that inside of the action class because it is required.

Is there a way to set this up so that if I click a link on my jsp page, it will prompt the user with the download dialgue. The file cannot open inside of the browser. I am thinking the link would have to be part of a form and post to the servlet code posted at the very top; the problem then is how do I stay on the same page or go to a different page.

I imagine this is not very clear so please ask if you are confused. I will post code as requested. I don't want to overwhelm the question with code. I just signed up for premium so if this question isn't listed at being 500 points I will increase the value.
0
Comment
Question by:jbaisden
  • 9
  • 5
  • 4
  • +1
20 Comments
 
LVL 1

Expert Comment

by:Celdric
ID: 12361120
Well, in Struts you usually dont implement the service method, rather
the execute one.. If i were you i would read more about struts and forwards inside
an Action. *shrug*
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12361165
For the second code call:
response.setheader(....)

 first before:

  out = new BufferedOutputStream( response.getOutputStream() );

once u get out the output stream u can't forward or modify responce header
 
0
 

Author Comment

by:jbaisden
ID: 12361574
petmagdy, I tried your suggestion, but I got the same error. It came when the code reached the
return (mapping.findForward("success")); in my action page. The error was still written out to the file. Do you have any other ideas?

Celdric, I am just getting started with this, but have been tasked with this assignment. Do you have any reading suggestions, preferably ones that are viewable on the web. I have been jumping around in my learning process, learning the parts of struts and how they work to the extent that the task I am working may get completed. If you could direct me to a more linear approach to learning this framework (any tad bits that would help with my current problem would help, but I won't be picky) I would very much appreciate.

 For the record here is the stack trace to the error I am getting:

[10/20/04 13:32:57:437 CDT] 50955095 WebGroup      E SRVE0026E: [Servlet Error]-[action]: java.lang.IllegalStateException: Cannot forward. Response already committed. (Servlet 2.3, SRV 8.4)
      at java.lang.Throwable.<init>(Throwable.java:54)
      at java.lang.Throwable.<init>(Throwable.java:68)
      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:160)
      at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
      at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
      at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
      at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
      at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
      at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
      at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
      at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
      at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:948)
      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:530)
      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:176)
      at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:79)
      at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:201)
      at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
      at com.ibm.ws.webcontainer.cache.invocation.CacheableInvocationContext.invoke(CacheableInvocationContext.java:114)
      at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:186)
      at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
      at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
      at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:610)
      at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:431)
      at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:593)

0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12361760
Yes because you did forward (findforward) after u manipulated the response object, u are not allowed to set header or get output stream and then forward, do the setheader and out staff on the page u forward to
0
 

Author Comment

by:jbaisden
ID: 12361927

I can't use jsp scriptlets inside of the jsp (as per our coding convention). I am using the logic, html, and bean tag libraries. Is there a way to do this with those? Is there another way to display the download dialogue? I suppose if the file would display in its respective program (aside from I.E.) that would work. This application is dealing strictly with text files. Is there a way to make the file open in notepad or the default text editor aside from I.E.? The reason I am doing all of this is because if I let the user click on a link pointing directly to the file on the server then it opens up in I.E. Suggestions?
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12362028
Ok either to do the whole header & out manipulation in single JSP or do this:

make ur action diplay the dialog with the out object (I know silly) and at the end of the display at the end of ur action execute (or whatever) call

   return null;

instead of:

return forwad;

this will cause that the action display the dialog with itself
0
 
LVL 1

Assisted Solution

by:Celdric
Celdric earned 150 total points
ID: 12362146
These are very good struts tutorials to get you started on STRUTS
http://javaboutique.internet.com/tutorials/Struts/
http://www-106.ibm.com/developerworks/library/j-struts/?dwzone=java
http://www.oracle.com/technology/sample_code/tech/java/j2ee/jintdemo/tutorials/Struts.html

also, if you know ppl with e-books, I recommend looking for
Mastering Jakarta Struts, excellent book.

Good luck
0
 
LVL 2

Assisted Solution

by:siliconeagle
siliconeagle earned 100 total points
ID: 12368545
just make :-
contentType = "application/octet-stream";

you don't need to forward anywhere. as th user just downloads the file.
0
 
LVL 2

Expert Comment

by:siliconeagle
ID: 12368576
maybe i'm missing something here but you dont need to make this a struts action as there is no view assoctiated with the action so I would just keep it as a servlet.
0
 

Author Comment

by:jbaisden
ID: 12369333
Here is my problem. So far I have been using Action Pages (which I think are a sort of STRUTS servlet); however, each action page must return result type of ActionForward.

What I need is to be able to send the filename to a servlet, have the servlet prompt the user for download, but have the page they are on remain the same (and reload that page if possible as I will remove some things from session after the download).

Here is how I am doing things now. Please let me know what I have to change to accomplish this. Remember I can't use scriptlets in my jsp pages. Another way of phrasing this is: how do I execute the servlet to force the download dialog box to appear and keep the user on the current page? I know how to get the download dialogue to appear ( I think ), its really setting up this servlet (so that an ActionForward is not required as a return type because the download dialogue code commits the response ) that I need the most help with. Thank you for your time. Please forigve my redundantness. Please forgive my redundantness.

FileUpload.jsp:
<!-- ****************** FILE UPLOAD JSP  ********************** -->

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>


<html:html>
<HEAD>

<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"
%>


<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">

<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="../theme/Master.css" rel="stylesheet"
      type="text/css">
<TITLE>Submit Example</TITLE>
</HEAD>

<BODY>

<TABLE WIDTH="100%" BORDER="0" cellpadding="0" cellspacing="0">

<TR>
<TD align="left" colspan=5>
      <logic:messagesPresent>
      <BR></BR>
          <bean:message key = "errors.header"/>
          <bean:message key = "errors.subheader"/>
          <ul>
            <html:messages id = "error">
                <li><bean:write name = "error"/></li>
            </html:messages>
          </ul>
          <hr align="left" >
      </logic:messagesPresent>
</TD>      
</TR>
<TR height="130px">
      <TD colspan=1 align="right" valign="center">
            
            Upload a file:
            
      </TD>
      
      <TD colspan=2 align="left" valign="middle">
       <html:form action="/FileUpload.do" enctype="multipart/form-data" >
       <html:file size="50" property="theFile" />
      
      </TD>
</TR>      
<TR>
      <TD colspan=5 align="center">
            <logic:notPresent name="FileName" scope="session" >
                  fn Not Accessible.
                  
            </logic:notPresent>
            
            <logic:notEmpty name="FileName">
            <logic:present name="FileName" scope="session">
                  <font color="blue" size=3>
                  <b>
                  Your file has been successfully processed. Click on the link
                  below to download it.
                  
                  <A href="/myApp/<bean:write name='FileName' property='filename'/>" > Click Me </a>
                  </b>
                  </font>            
            </logic:present>
            </logic:notEmpty>
      </TD>
</TR>
<TR bgcolor="LightGrey">
      <TD align="left" colspan=2>      
            <font size="3"><b>File Upload Form</b></font>      
      </TD>
      <TD colspan=3 align=center valign="middle">
            <html:image property="imgsubmitButton"
                            src="images/icons/submit.gif"
                            value="imgsubmitButton" />
      </TD>
</TR>
            </html:form>
</TABLE>


</BODY>
</html:html>

<!-- *******************FILE UPLOAD ACTION***********************-->

/*
 * Created on Oct 14, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package myorg.ID.Actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import myorg.ID.Util.DownloadServlet;
import myorg.ID.Util.FileOperations;
import myorg.ID.Util.IDValidation;
import com.ibm.jvm.Constants;

import myorg.ID.Entity.FileName;
import myorg.ID.Forms.FileUploadForm;
/**
 * @author jbaisden
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class FileUploadAction extends Action{

      public ActionForward execute( ActionMapping mapping,
                                                        ActionForm form,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response) throws IOException {

                  servlet.log("Inside FileUploadAction");
                  IDValidation IDValidator = new IDValidation();
                  String strForward = null;
                  ArrayList alIDs = new ArrayList();
                  ArrayList goodIDS = new ArrayList();
                  ArrayList badIDS = new ArrayList();
                  FileOperations fileOp = new FileOperations();
                  //DownloadServlet ds = new DownloadServlet();
                  FileUploadForm theForm = (FileUploadForm) form;            
                  FileName fn = new FileName();
                  //retrieve the file representation
                  FormFile file = theForm.gettheFile();
            
                  if(file == null)
                        servlet.log("file is null");
                  else {
                        
                        servlet.log("file is not null");
                  }                        
                  //retrieve the file name
                  String fileName = file.getFileName();
                  
                  //retrieve the file data
                  InputStream stream = null;
                  
                  try {
                           stream = file.getInputStream();                        
                           BufferedReader in = new BufferedReader(new InputStreamReader(stream));
                           String str = "Start";
                           while (str != null) {
                                    str = null;
                                 str = in.readLine();
                                 if(str != null)
                                        alIDs.add(str);
                           }
                        
                          //Validates an Array List of IDs and appends either VALID or
                          //INVALID to the end of the ID string and then returns the modified
                          //array list.
                           alIDs = IDValidator.validateIDS(alIDs);
      
                          //fileOp.generateRandomName() generates a name for the file based
                          //on the server time in miliseconds.      
                          fn.setFilename( fileOp.generateRandomName());
      
                          //fileOp.createResultFile creates a file from the
                          //validated array list and names it according to the 2nd
                          //parameter.
                          fileOp.createResultFile(alIDs,fn.getFilename() );                  
                  
                          request.getSession().setAttribute("FileName", fn);
                        
                          //Forces the contents of the file just created
                          //into the response output stream, which causes
                          //the file download/open dialogue to appear.
                          //Still buggy.
                          forceDownload(request,response);
                        // response.setContentType( "application/unknow" );
                        // ds.service(request,response);
                        
                        // response.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
                        
                        
                         System.out.println( request.getSession().getAttribute("FileName").toString());
                         
                  }// end try
                  
                  catch( IOException e) {
                           System.out.println("IO EXCEPTION IN perform");
                      System.out.println(e.getMessage());
                  }
                  
                  return (mapping.findForward("success"));
      
}


private void forceDownload( HttpServletRequest request,
                                          HttpServletResponse response) throws IOException {
      String filePath = "/ID/";
             String dummy = null;
             String filename = "results_test.txt";//request.getSession().getAttribute("FileName").toString();
       
             File f = new File("C:\\ID\\" + "results_test.txt");
//            if( filePath == null && filename != null ) filePath = "/" + filename;
//            if( filename == null ) filename = filePath;
//            if( filename != null ) filename = (new File(filename)).getName();

             if(f.exists()) System.out.println("File does exist!");
            
             if( filePath != null ) {
               FileInputStream fis = null;
               InputStream in = null;
               OutputStream out = null;
               try {
                         dummy = f.getPath();
                         //dummy = httpServletRequest.getSession();
                         //sc = getServletConfig().getServletContext();
                         //if(sc != null) System.out.println("Servlet Context is not null.");
                         fis = new FileInputStream(f.getPath());
                         //in = getServletContext().getResourceAsStream(f.getPath());//basePath + filePath);
                        // in = null;
                     if( fis != null ) {
                                    response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
                                     out = new BufferedOutputStream( response.getOutputStream() );
                                     in = new BufferedInputStream( fis );
                                     String contentType = null; //getServletConfig().getServletContext().getMimeType( filename );
                                     if( contentType == null ) contentType = "application/unknow";
                                     System.out.println( "contentType: " + contentType );
                                     
                                     int c; while( ( c=in.read() ) != -1 ) out.write( c );
                                     return ;
                          }
               } catch(Exception e) {
                   System.out.println("An Exception of some sort.");
                   System.out.println(e.getMessage());
                
               }      finally {
                        if( in != null ) try { in.close(); } catch( Exception e ) {}
                        if( out != null ) try { out.close(); } catch( Exception e ) {}
               }
        }
        response.sendError( HttpServletResponse.SC_NOT_FOUND );
       }

}

<!-- *******************FILE UPLOAD FORM***********************-->

/*
 * Created on Oct 14, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package myorg.ID.Forms;

/**
 * @author jbaisden
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 *
 *
 *
 */

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

/**
 * Form bean for a Struts application.
 * Users may access 1 field on this form:
 * <ul>
 * <li>theFile - [your comment here]
 * </ul>
 * @version       1.0
 * @author
 */
public class FileUploadForm extends ActionForm {
      
      public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";
      
      private org.apache.struts.upload.FormFile theFile;

      public void reset(ActionMapping mapping, HttpServletRequest request) {

            // Reset values are provided as samples only. Change as appropriate.


      }

      public ActionErrors validate(
            ActionMapping mapping,
            HttpServletRequest request) {

                  servlet.log("Inside FileUploadForm");
                  ActionErrors errors = null;
                  //has the maximum length been exceeded?
                  Boolean maxLengthExceeded = (Boolean) request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
                  
                  if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue()))
                  {
                        errors = new ActionErrors();
                        errors.add(ERROR_PROPERTY_MAX_LENGTH_EXCEEDED, new ActionError("maxLengthExceeded"));
                  }
                  return errors;

      }
      /**
       * @return
       */
      public org.apache.struts.upload.FormFile gettheFile() {
            servlet.log("Inside FileUploadForm");
            return theFile;
      }

      /**
       * @param file
       */
      public void settheFile(org.apache.struts.upload.FormFile file) {
            servlet.log("Inside FileUploadForm");
            theFile = file;
      }

}


<!--******************** MY STRUTS-CONFIG.XML ****************-->
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">



<struts-config>


<form-beans>

      
                    
      <form-bean name="FileUploadForm"
                     type="myorg.ID.Forms.FileUploadForm" >
                  
      </form-bean>      
      
               
</form-beans>

<!-- =========================Action Mapping DEFINITION =================== -->

<action-mappings>
      
      
      <action path="/FileUpload"
                  type="myorg.ID.Actions.FileUploadAction"
                  name="FileUploadForm"
                  input="/FileUpload.jsp"
                  scope="request"
                  validate="false"       >
      <forward name="success" path="/FileUpload.jsp"/>
      <forward name="failure" path="/FileUpload.jsp"/>
      </action>      
      
</action-mappings>

<message-resources parameter="resources.application"/>
 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
          <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                              /WEB-INF/validation.xml"/>
  </plug-in>

</struts-config>

<!-- ************* MY WEB.XML FILE ***************************** -->
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <display-name>Struts Blank Application</display-name>
 
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-nested</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-tiles</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

 <resource-ref id="ResourceRef_1088625022021">
        <description>Oracle Datasource Reference</description>
        <res-ref-name>jdbc/ds11</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>CONTAINER</res-auth>
  </resource-ref>
 
<env-entry>

      <description>oracle datasource</description>

      <env-entry-name>oracle_datasource</env-entry-name>

      <env-entry-value>jdbc/ds11</env-entry-value>

      <env-entry-type>java.lang.String</env-entry-type>

  </env-entry>

</web-app>


0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 13

Accepted Solution

by:
petmagdy earned 250 total points
ID: 12369570
take a look at this:

http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=58&t=000913

if u download the structs from jakarta their is a sample application called appfuse contains a complet file Upload scenario to get appfuse go to:

http://sourceforge.net/projects/struts/

0
 
LVL 1

Expert Comment

by:Celdric
ID: 12369582
In this part of the code:

    <TD colspan=5 align="center">
          <logic:notPresent name="FileName" scope="session" >
               fn Not Accessible.              
          </logic:notPresent>
         
          <logic:notEmpty name="FileName">
          <logic:present name="FileName" scope="session">
               <font color="blue" size=3>
               <b>
               Your file has been successfully processed. Click on the link
               below to download it.
               
               <A href="/myApp/<bean:write name='FileName' property='filename'/>" > Click Me </a>
               </b>
               </font>          
          </logic:present>
          </logic:notEmpty>
     </TD>



What does <bean:write name='FileName' property='filename'/>
return, as a String, and is the file already there, when the user clicks it?
Myabe your link is not working because
a) The file wasnt created yet
b)The file was created but its in a wrong folder (the link cant find the file)
c)Somethings wrong with the link, and the String isnt a http:// thingy.
d)the property filename is null.

*shrug*
0
 

Author Comment

by:jbaisden
ID: 12369702

Celdric:
Well the link does work. I spent some time trouble shooting that part. The problem is the file (being a text file) is opened in the browser. I am trying to get this link to call the download dialogue box so the user can download the file. I am thinking this link will have to change to execute the servlet that calls the download dialgue to appear. The servlet will also remove the FileName object from session so the link to download the file no longer appears.

Petmagdy: I will take a look at the code you are referring to. Thanks for the link.
0
 
LVL 1

Expert Comment

by:Celdric
ID: 12369825
So, basically you want the link to act as a Save Target As, instead of redirecting the user
to the url containing the Text.. hmm..and when the user clicks the link, the url with the
text would be sent to a servlet(Action) and he created a Save target As Dialog, then
reload the original page, am I correct?

0
 

Author Comment

by:jbaisden
ID: 12370114
Thats pretty much the case, yes.
0
 

Author Comment

by:jbaisden
ID: 12371586
Here is where I have gotten so far. I followed Petmagdy's most recent link to the appfuse application. I downloaded and looked through the code. I came across a servlet called RegistrationServlet. I think it has the skeleton of what I need my servlet to look like. I have modified the code to be the following:

<!-- ******************** FORCE DOWNLOAD SERVLET REVISION ************** -->
package myorg.ID.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.mail.MessagingException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;


/**
 * CODE TAKEN FROM RegistrationServlet of appFuse example
 * Implementation of <strong>HttpServlet</strong> that is used
 * to allow users to self-register.
 * <p/>
 * <p><a href="RegistrationServlet.java.html"><i>View Source</i></a></p>
 *
 * @author Matt Raible
 * @version $Revision: 1.21 $ $Date: 2004/02/28 05:59:08 $
 * @web.servlet display-name="Registration Servlet"
 * name="register"
 * load-on-startup="4"
 * @web.servlet-mapping url-pattern="/register/*"
 * @web.servlet-mapping url-pattern="/passwordHint/*"
 */
public final class ForceDownloadServlet extends HttpServlet {
    private Log log = LogFactory.getLog(RegistrationServlet.class);

    /**
     * Route the user to the execute method
     *
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @throws IOException      if an input/output error occurs
     * @throws ServletException if a servlet exception occurs
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
        execute(request, response);
    }

    /**
     * Route the user to the execute method
     *
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @throws IOException      if an input/output error occurs
     * @throws ServletException if a servlet exception occurs
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
        execute(request, response);
    }

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @throws IOException      if an input/output error occurs
     * @throws ServletException if a servlet exception occurs
     */
    public void execute(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {


        String filePath = "/checkDigit/";
                         String dummy = null;
                         String filename = "results_test.txt";//request.getSession().getAttribute("FileName").toString();
                         String strForward = "FileUpload.jsp"
                         File f = new File("C:\\Documents and Settings\\jbaisden\\" +
                                                   "Desktop\\checkDigit\\checkDigit\\WebContent\\" +
                                                   "results_test.txt");

                   if(f.exists()) System.out.println("File does exist!");

                         if( filePath != null ) {
                           FileInputStream fis = null;
                           InputStream in = null;
                           OutputStream out = null;
                           try {
                                     dummy = f.getPath();
                                     fis = new FileInputStream(f.getPath());

                                 if( fis != null ) {
                                                response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
                                                 out = new BufferedOutputStream( response.getOutputStream() );
                                                 in = new BufferedInputStream( fis );
                                                 String contentType = null;
                                                 if( contentType == null ) contentType = "APPLICATION/OCTET-STREAM"; //"application/unknow";
                                                 System.out.println( "contentType: " + contentType );

                                                 int c; while( ( c=in.read() ) != -1 ) out.write( c );
                                                 return ;
                                      }
                           } catch(Exception e) {
                               System.out.println("An Exception of some sort.");
                               System.out.println(e.getMessage());

                           }      finally {
                                    if( in != null ) try { in.close(); } catch( Exception e ) {}
                                    if( out != null ) try { out.close(); } catch( Exception e ) {}
                           }
                    }
                    //response.sendError( HttpServletResponse.SC_NOT_FOUND );
                     //response.sendRedirect(response.encodeRedirectURL(route));
             dispatch(request, response, strForward);
       }

    /**
     * Dispatch request to common JSP
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    public void dispatch(HttpServletRequest request,
                         HttpServletResponse response, String jsp)
    throws IOException, ServletException {
        // forward back to the register.jsp
        RequestDispatcher dispatcher = request.getRequestDispatcher("/" + jsp);
        dispatcher.forward(request, response);
    }
}



I haven't tested this because I don't know what entry to put into my struts-config.xml to use this servlet. I checked the app fuse xml pages but they were pretty confusing. I really couldn't make heads or tales of it. I am not using any tiles in my app either, like appFuse is doing. I think I want to stay clear of that for the time being as this app will be pretty small. Any help would be appreciated.
0
 

Author Comment

by:jbaisden
ID: 12371661
Something I just thought about is that the FileUpload.jsp is already mapped to an action page (FileUploadAction) with that page as the input. Later in the same page I want it to go to a different page (the servlet entirely). Is this even possible. Once more here is my strust-config.xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<!-- =========================FORM BEANS DEFINITION =================== -->
<form-beans>  
      <form-bean name="FileUploadForm"
                     type="gov.wi.state.dpi.checkDigit.Forms.FileUploadForm" >
      </form-bean>      
</form-beans>
<!-- =========================Action Mapping DEFINITION =================== -->
<action-mappings>
      <action path="/FileUpload"
                  type="gov.wi.state.dpi.checkDigit.Actions.FileUploadAction"
                  name="FileUploadForm"
                  input="/FileUpload.jsp"
                  scope="request"
                  validate="false"       >
      <forward name="success" path="/FileUpload.jsp"/>
      <forward name="failure" path="/FileUpload.jsp"/>
      </action>      
</action-mappings>
<message-resources parameter="resources.application"/>
 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
          <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                              /WEB-INF/validation.xml"/>
 </plug-in>
</struts-config>


and here is my web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <display-name>Struts Blank Application</display-name>
 
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-nested</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-tiles</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

 <resource-ref id="ResourceRef_1088625022021">
        <description>Oracle Datasource Reference</description>
        <res-ref-name>jdbc/ds11</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>CONTAINER</res-auth>
  </resource-ref>
 
<env-entry>

      <description>oracle datasource</description>

      <env-entry-name>oracle_datasource</env-entry-name>

      <env-entry-value>jdbc/ds11</env-entry-value>

      <env-entry-type>java.lang.String</env-entry-type>

  </env-entry>

</web-app>
0
 

Author Comment

by:jbaisden
ID: 12372208


WOOT! IT WORKS! Well the whole thing about creating a servlet to do this seems to have worked quite beautifully. Here is what I had to put in my web.xml:

<servlet>
        <servlet-name>ForceDownloadServlet</servlet-name>
        <servlet-class>
              myorg.ID.Actions.ForceDownloadServlet
        </servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
   
    <servlet-mapping>
          <servlet-name>ForceDownloadServlet</servlet-name>
          <url-pattern>ForceDownload</url-pattern>
    </servlet-mapping>

Here is the complete servlet code for ForceDownloadServlet:

/*
 * Created on Oct 21, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package myorg.ID.Actions;

/**
 * @author jbaisden
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * CODE TAKEN FROM RegistrationServlet of appFuse example
 * Implementation of <strong>HttpServlet</strong> that is used
 * to allow users to self-register.
 * <p/>
 * <p><a href="RegistrationServlet.java.html"><i>View Source</i></a></p>
 *
 * @author Matt Raible
 * @version $Revision: 1.21 $ $Date: 2004/02/28 05:59:08 $
 * @web.servlet display-name="Registration Servlet"
 * name="register"
 * load-on-startup="4"
 * @web.servlet-mapping url-pattern="/register/*"
 * @web.servlet-mapping url-pattern="/passwordHint/*"
 */
public final class ForceDownloadServlet extends HttpServlet {
      //private Log log = LogFactory.getLog(RegistrationServlet.class);

    public void init(ServletConfig config) throws ServletException {
          super.init(config);
    }
      /**
       * Route the user to the execute method
       *
       * @param request  The HTTP request we are processing
       * @param response The HTTP response we are creating
       * @throws IOException      if an input/output error occurs
       * @throws ServletException if a servlet exception occurs
       */
      public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
            execute(request, response);
      }

      /**
       * Route the user to the execute method
       *
       * @param request  The HTTP request we are processing
       * @param response The HTTP response we are creating
       * @throws IOException      if an input/output error occurs
       * @throws ServletException if a servlet exception occurs
       */
      public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
            execute(request, response);
      }

      /**
       * Process the specified HTTP request, and create the corresponding HTTP
       * response (or forward to another web component that will create it).
       *
       * @param request  The HTTP request we are processing
       * @param response The HTTP response we are creating
       * @throws IOException      if an input/output error occurs
       * @throws ServletException if a servlet exception occurs
       */
      public void execute(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {


                         String filePath = "/checkDigit/";
                         String dummy = null;
                         String filename = "results_test.txt";//request.getSession().getAttribute("FileName").toString();
                         String strForward = "FileUpload.jsp";
                         File f = new File("C:\\Documents and Settings\\jbaisden\\" +
                                                   "Desktop\\checkDigit\\checkDigit\\WebContent\\" +
                                                   "results_test.txt");

                   if(f.exists()) System.out.println("File does exist!");

                         if( filePath != null ) {
                           FileInputStream fis = null;
                           InputStream in = null;
                           OutputStream out = null;
                           try {
                                     dummy = f.getPath();
                                     fis = new FileInputStream(f.getPath());

                                 if( fis != null ) {
                                                response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
                                                 out = new BufferedOutputStream( response.getOutputStream() );
                                                 in = new BufferedInputStream( fis );
                                                 String contentType = null;
                                                 if( contentType == null ) contentType = "APPLICATION/OCTET-STREAM"; //"application/unknow";
                                                 System.out.println( "contentType: " + contentType );

                                                 int c; while( ( c=in.read() ) != -1 ) out.write( c );
                                                 return ;
                                      }
                           } catch(Exception e) {
                               System.out.println("An Exception of some sort.");
                               System.out.println(e.getMessage());

                           }      finally {
                                    if( in != null ) try { in.close(); } catch( Exception e ) {}
                                    if( out != null ) try { out.close(); } catch( Exception e ) {}
                           }
                    }
                    //response.sendError( HttpServletResponse.SC_NOT_FOUND );
                    //response.sendRedirect(response.encodeRedirectURL(route));
                   dispatch(request, response, strForward);
       }

      /**
       * Dispatch request to common JSP
       *
       * @param request
       * @param response
       * @throws IOException
       * @throws ServletException
       */
      public void dispatch(HttpServletRequest request,
                                     HttpServletResponse response, String jsp)
      throws IOException, ServletException {
            // forward back to the register.jsp
            RequestDispatcher dispatcher = request.getRequestDispatcher("/" + jsp);
            dispatcher.forward(request, response);
      }
}


and to call this bad boy I just did a simple link in my upload page:

<A HREF="ForceDownload"> Goto ForceDownload </A>

I would have bet money as I was coding this that it wasn't going to work. You guys have been a grand help. Once again, non solution on a golden platter, but just enough to push me along. That's the way I like it. I will review this thread later and distribute points at that time. Thank you all so much for your help!

I bet EE hates people like me who paste their code over and over and over....wonder how much space that takes...any how...thanks again!
0
 
LVL 1

Expert Comment

by:Celdric
ID: 12377005
Kick @$$! Congratz! I was at a blank (didnt have time to work with a copy of the proyect
on my comp) and Im very glad it worked for you! :D

*tips hat off to you*

0
 

Author Comment

by:jbaisden
ID: 12402434
Thanks for everyones help in this question. The key for me in solving this was the registration Servlet in the appFuse application. I pulled the configuration for the servlet from it and found out how to use servlets in general (I.E. that are not STRUTS specific). It really wasn't just this, so all of you got points. It is conglumeration of all of your input. Thank you all for helping me through this.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

HOW TO: Connect to the VMware vSphere Hypervisor 6.5 (ESXi 6.5) using the vSphere (HTML5 Web) Host Client 6.5, and perform a simple configuration task of adding a new VMFS 6 datastore.
In this article, I will show you HOW TO: Create your first Windows Virtual Machine on a VMware vSphere Hypervisor 6.5 (ESXi 6.5) Host Server, the Windows OS we will install is Windows Server 2016.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now