jbaisden
asked on
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)
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.ServletExcep
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
public final class DownloadServlet extends HttpServlet {
private static final String basePath = "/doc";
public void service(HttpServletRequest
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().getRes
if( in != null ) {
out = new BufferedOutputStream( response.getOutputStream()
in = new BufferedInputStream( in );
String contentType = getServletConfig().getServ
if( contentType == null ) contentType = "application/unknow";
System.out.println( "contentType: " + contentType );
response.setHeader("Conten
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
}
}
// **************** 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.ServletConfi
import javax.servlet.ServletConte
import javax.servlet.ServletExcep
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
public final class DownloadServlet extends HttpServlet {
// private static final String basePath = "/doc";
public void service(HttpServletRequest
HttpServletResponse response)
throws ServletException, java.io.IOException
{
String filePath = Constants.RESULTS_CREATION
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().getSe
if( contentType == null ) contentType = "application/unknow";
System.out.println( "contentType: " + contentType );
response.setHeader("Conten
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.getMe
} finally {
if( in != null ) try { in.close(); } catch( Exception e ) {}
if( out != null ) try { out.close(); } catch( Exception e ) {}
}
}
response.sendError( HttpServletResponse.SC_NOT
}
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. (Servlet 2.3, SRV 8.4)
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.
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
response.setheader(....)
first before:
out = new BufferedOutputStream( response.getOutputStream()
once u get out the output stream u can't forward or modify responce header
ASKER
petmagdy, I tried your suggestion, but I got the same error. It came when the code reached the
return (mapping.findForward("succ ess")); 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.IllegalStateExce ption: 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.we bapp.WebAp pRequestDi spatcher.f orward(Web AppRequest Dispatcher .java:160)
at org.apache.struts.action.R equestProc essor.doFo rward(Requ estProcess or.java:10 69)
at org.apache.struts.action.R equestProc essor.proc essForward Config(Req uestProces sor.java:4 55)
at org.apache.struts.action.R equestProc essor.proc ess(Reques tProcessor .java:279)
at org.apache.struts.action.A ctionServl et.process (ActionSer vlet.java: 1482)
at org.apache.struts.action.A ctionServl et.doPost( ActionServ let.java:5 25)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 760)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 853)
at com.ibm.ws.webcontainer.se rvlet.Stri ctServletI nstance.do Service(St rictServle tInstance. java:110)
at com.ibm.ws.webcontainer.se rvlet.Stri ctLifecycl eServlet._ service(St rictLifecy cleServlet .java:174)
at com.ibm.ws.webcontainer.se rvlet.Idle ServletSta te.service (StrictLif ecycleServ let.java:3 13)
at com.ibm.ws.webcontainer.se rvlet.Stri ctLifecycl eServlet.s ervice(Str ictLifecyc leServlet. java:116)
at com.ibm.ws.webcontainer.se rvlet.Serv letInstanc e.service( ServletIns tance.java :283)
at com.ibm.ws.webcontainer.se rvlet.Vali dServletRe ferenceSta te.dispatc h(ValidSer vletRefere nceState.j ava:42)
at com.ibm.ws.webcontainer.se rvlet.Serv letInstanc eReference .dispatch( ServletIns tanceRefer ence.java: 40)
at com.ibm.ws.webcontainer.we bapp.WebAp pRequestDi spatcher.h andleWebAp pDispatch( WebAppRequ estDispatc her.java:9 48)
at com.ibm.ws.webcontainer.we bapp.WebAp pRequestDi spatcher.d ispatch(We bAppReques tDispatche r.java:530 )
at com.ibm.ws.webcontainer.we bapp.WebAp pRequestDi spatcher.f orward(Web AppRequest Dispatcher .java:176)
at com.ibm.ws.webcontainer.sr t.WebAppIn voker.doFo rward(WebA ppInvoker. java:79)
at com.ibm.ws.webcontainer.sr t.WebAppIn voker.hand leInvocati onHook(Web AppInvoker .java:201)
at com.ibm.ws.webcontainer.ca che.invoca tion.Cache dInvocatio n.handleIn vocation(C achedInvoc ation.java :71)
at com.ibm.ws.webcontainer.ca che.invoca tion.Cache ableInvoca tionContex t.invoke(C acheableIn vocationCo ntext.java :114)
at com.ibm.ws.webcontainer.sr p.ServletR equestProc essor.disp atchByURI( ServletReq uestProces sor.java:1 86)
at com.ibm.ws.webcontainer.os elistener. OSEListene rDispatche r.service( OSEListene r.java:334 )
at com.ibm.ws.webcontainer.ht tp.HttpCon nection.ha ndleReques t(HttpConn ection.jav a:56)
at com.ibm.ws.http.HttpConnec tion.readA ndHandleRe quest(Http Connection .java:610)
at com.ibm.ws.http.HttpConnec tion.run(H ttpConnect ion.java:4 31)
at com.ibm.ws.util.ThreadPool $Worker.ru n(ThreadPo ol.java:59 3)
return (mapping.findForward("succ
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.IllegalStateExce
at java.lang.Throwable.<init>
at java.lang.Throwable.<init>
at com.ibm.ws.webcontainer.we
at org.apache.struts.action.R
at org.apache.struts.action.R
at org.apache.struts.action.R
at org.apache.struts.action.A
at org.apache.struts.action.A
at javax.servlet.http.HttpSer
at javax.servlet.http.HttpSer
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.se
at com.ibm.ws.webcontainer.we
at com.ibm.ws.webcontainer.we
at com.ibm.ws.webcontainer.we
at com.ibm.ws.webcontainer.sr
at com.ibm.ws.webcontainer.sr
at com.ibm.ws.webcontainer.ca
at com.ibm.ws.webcontainer.ca
at com.ibm.ws.webcontainer.sr
at com.ibm.ws.webcontainer.os
at com.ibm.ws.webcontainer.ht
at com.ibm.ws.http.HttpConnec
at com.ibm.ws.http.HttpConnec
at com.ibm.ws.util.ThreadPool
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
ASKER
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?
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
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
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
ASKER
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-da ta" >
<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.g if"
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>Preferences>J ava>Cod e Generation>Code and Comments
*/
package myorg.ID.Actions;
import java.io.BufferedInputStrea m;
import java.io.BufferedOutputStre am;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundExcept ion;
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.ServletExcep tion;
import javax.servlet.http.HttpSer vletReques t;
import javax.servlet.http.HttpSer vletRespon se;
import org.apache.struts.action.A ction;
import org.apache.struts.action.A ctionForm;
import org.apache.struts.action.A ctionForwa rd;
import org.apache.struts.action.A ctionMappi ng;
import org.apache.struts.upload.F ormFile;
import myorg.ID.Util.DownloadServ let;
import myorg.ID.Util.FileOperatio ns;
import myorg.ID.Util.IDValidation ;
import com.ibm.jvm.Constants;
import myorg.ID.Entity.FileName;
import myorg.ID.Forms.FileUploadF orm;
/**
* @author jbaisden
*
* To change the template for this generated type comment go to
* Window>Preferences>J ava>Cod e Generation>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(al IDs);
//fileOp.generateRandomNam e() 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(al IDs,fn.get Filename() );
request.getSession().setAt tribute("F ileName", 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,resp onse);
// response.setContentType( "application/unknow" );
// ds.service(request,respons e);
// response.setHeader("Conten t-Disposit ion","atta chment; filename=\"" + fileName + "\"");
System.out.println( request.getSession().getAt tribute("F ileName"). toString() );
}// end try
catch( IOException e) {
System.out.println("IO EXCEPTION IN perform");
System.out.println(e.getMe ssage());
}
return (mapping.findForward("succ ess"));
}
private void forceDownload( HttpServletRequest request,
HttpServletResponse response) throws IOException {
String filePath = "/ID/";
String dummy = null;
String filename = "results_test.txt";//reque st.getSess ion().getA ttribute(" 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.getSess ion();
//sc = getServletConfig().getServ letContext ();
//if(sc != null) System.out.println("Servle t Context is not null.");
fis = new FileInputStream(f.getPath( ));
//in = getServletContext().getRes ourceAsStr eam(f.getP ath());//b asePath + filePath);
// in = null;
if( fis != null ) {
response.setHeader("Conten t-Disposit ion","atta chment; filename=\"" + filename + "\"");
out = new BufferedOutputStream( response.getOutputStream() );
in = new BufferedInputStream( fis );
String contentType = null; //getServletConfig().getSe rvletConte xt().getMi meType( 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.getMe ssage());
} 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>Preferences>J ava>Cod e Generation>Code and Comments
*/
package myorg.ID.Forms;
/**
* @author jbaisden
*
* To change the template for this generated type comment go to
* Window>Preferences>J ava>Cod e Generation>Code and Comments
*
*
*
*/
import javax.servlet.http.HttpSer vletReques t;
import org.apache.struts.action.A ctionError ;
import org.apache.struts.action.A ctionError s;
import org.apache.struts.action.A ctionForm;
import org.apache.struts.action.A ctionMappi ng;
import org.apache.struts.upload.F ormFile;
import org.apache.struts.upload.M ultipartRe questHandl er;
/**
* 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.Max LengthExce eded";
private org.apache.struts.upload.F ormFile 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(Multi partReques tHandler.A TTRIBUTE_M AX_LENGTH_ EXCEEDED);
if ((maxLengthExceeded != null) && (maxLengthExceeded.boolean Value()))
{
errors = new ActionErrors();
errors.add(ERROR_PROPERTY_ MAX_LENGTH _EXCEEDED, new ActionError("maxLengthExce eded"));
}
return errors;
}
/**
* @return
*/
public org.apache.struts.upload.F ormFile gettheFile() {
servlet.log("Inside FileUploadForm");
return theFile;
}
/**
* @param file
*/
public void settheFile(org.apache.stru ts.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.FileU ploadForm" >
</form-bean>
</form-beans>
<!-- =========================A ction Mapping DEFINITION =================== -->
<action-mappings>
<action path="/FileUpload"
type="myorg.ID.Actions.Fil eUploadAct ion"
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.appli cation"/>
<plug-in className="org.apache.stru ts.validat or.Validat orPlugIn">
<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</serv let-name>
<servlet-class>org.apache. struts.act ion.Action Servlet</s ervlet-cla ss>
<init-param>
<param-name>config</param- name>
<param-value>/WEB-INF/stru ts-config. xml</param -value>
</init-param>
<init-param>
<param-name>debug</param-n ame>
<param-value>2</param-valu e>
</init-param>
<init-param>
<param-name>detail</param- name>
<param-value>2</param-valu e>
</init-param>
<load-on-startup>2</load-o n-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</serv let-name>
<url-pattern>*.do</url-pat tern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</w elcome-fil e>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-b ean</tagli b-uri>
<taglib-location>/WEB-INF/ struts-bea n.tld</tag lib-locati on>
</taglib>
<taglib>
<taglib-uri>/tags/struts-h tml</tagli b-uri>
<taglib-location>/WEB-INF/ struts-htm l.tld</tag lib-locati on>
</taglib>
<taglib>
<taglib-uri>/tags/struts-l ogic</tagl ib-uri>
<taglib-location>/WEB-INF/ struts-log ic.tld</ta glib-locat ion>
</taglib>
<taglib>
<taglib-uri>/tags/struts-n ested</tag lib-uri>
<taglib-location>/WEB-INF/ struts-nes ted.tld</t aglib-loca tion>
</taglib>
<taglib>
<taglib-uri>/tags/struts-t iles</tagl ib-uri>
<taglib-location>/WEB-INF/ struts-til es.tld</ta glib-locat ion>
</taglib>
<resource-ref id="ResourceRef_1088625022 021">
<description>Oracle Datasource Reference</description>
<res-ref-name>jdbc/ds11</r es-ref-nam e>
<res-type>javax.sql.DataSo urce</res- type>
<res-auth>CONTAINER</res-a uth>
</resource-ref>
<env-entry>
<description>oracle datasource</description>
<env-entry-name>oracle_dat asource</e nv-entry-n ame>
<env-entry-value>jdbc/ds11 </env-entr y-value>
<env-entry-type>java.lang. String</en v-entry-ty pe>
</env-entry>
</web-app>
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-
<LINK href="../theme/Master.css"
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-da
<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.g
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>Preferences>J
*/
package myorg.ID.Actions;
import java.io.BufferedInputStrea
import java.io.BufferedOutputStre
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundExcept
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.ServletExcep
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.upload.F
import myorg.ID.Util.DownloadServ
import myorg.ID.Util.FileOperatio
import myorg.ID.Util.IDValidation
import com.ibm.jvm.Constants;
import myorg.ID.Entity.FileName;
import myorg.ID.Forms.FileUploadF
/**
* @author jbaisden
*
* To change the template for this generated type comment go to
* Window>Preferences>J
*/
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(al
//fileOp.generateRandomNam
//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(al
request.getSession().setAt
//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,resp
// response.setContentType( "application/unknow" );
// ds.service(request,respons
// response.setHeader("Conten
System.out.println( request.getSession().getAt
}// end try
catch( IOException e) {
System.out.println("IO EXCEPTION IN perform");
System.out.println(e.getMe
}
return (mapping.findForward("succ
}
private void forceDownload( HttpServletRequest request,
HttpServletResponse response) throws IOException {
String filePath = "/ID/";
String dummy = null;
String filename = "results_test.txt";//reque
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.getSess
//sc = getServletConfig().getServ
//if(sc != null) System.out.println("Servle
fis = new FileInputStream(f.getPath(
//in = getServletContext().getRes
// in = null;
if( fis != null ) {
response.setHeader("Conten
out = new BufferedOutputStream( response.getOutputStream()
in = new BufferedInputStream( fis );
String contentType = null; //getServletConfig().getSe
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.getMe
} finally {
if( in != null ) try { in.close(); } catch( Exception e ) {}
if( out != null ) try { out.close(); } catch( Exception e ) {}
}
}
response.sendError( HttpServletResponse.SC_NOT
}
}
<!-- *******************FILE UPLOAD FORM**********************
/*
* Created on Oct 14, 2004
*
* To change the template for this generated file go to
* Window>Preferences>J
*/
package myorg.ID.Forms;
/**
* @author jbaisden
*
* To change the template for this generated type comment go to
* Window>Preferences>J
*
*
*
*/
import javax.servlet.http.HttpSer
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.upload.F
import org.apache.struts.upload.M
/**
* 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_
private org.apache.struts.upload.F
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(Multi
if ((maxLengthExceeded != null) && (maxLengthExceeded.boolean
{
errors = new ActionErrors();
errors.add(ERROR_PROPERTY_
}
return errors;
}
/**
* @return
*/
public org.apache.struts.upload.F
servlet.log("Inside FileUploadForm");
return theFile;
}
/**
* @param file
*/
public void settheFile(org.apache.stru
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.FileU
</form-bean>
</form-beans>
<!-- =========================A
<action-mappings>
<action path="/FileUpload"
type="myorg.ID.Actions.Fil
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.appli
<plug-in className="org.apache.stru
<set-property property="pathnames" value="/WEB-INF/validator-
/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</serv
<servlet-class>org.apache.
<init-param>
<param-name>config</param-
<param-value>/WEB-INF/stru
</init-param>
<init-param>
<param-name>debug</param-n
<param-value>2</param-valu
</init-param>
<init-param>
<param-name>detail</param-
<param-value>2</param-valu
</init-param>
<load-on-startup>2</load-o
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</serv
<url-pattern>*.do</url-pat
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</w
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-b
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-h
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-l
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-n
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-t
<taglib-location>/WEB-INF/
</taglib>
<resource-ref id="ResourceRef_1088625022
<description>Oracle Datasource Reference</description>
<res-ref-name>jdbc/ds11</r
<res-type>javax.sql.DataSo
<res-auth>CONTAINER</res-a
</resource-ref>
<env-entry>
<description>oracle datasource</description>
<env-entry-name>oracle_dat
<env-entry-value>jdbc/ds11
<env-entry-type>java.lang.
</env-entry>
</web-app>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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*
<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*
ASKER
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.
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?
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?
ASKER
Thats pretty much the case, yes.
ASKER
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.RequestDispa tcher;
import javax.servlet.ServletExcep tion;
import javax.servlet.http.HttpSer vlet;
import javax.servlet.http.HttpSer vletReques t;
import javax.servlet.http.HttpSer vletRespon se;
import javax.servlet.http.HttpSes sion;
import javax.mail.MessagingExcept ion;
import org.apache.commons.beanuti ls.BeanUti ls;
import org.apache.commons.lang.St ringUtils;
import org.apache.commons.logging .Log;
import org.apache.commons.logging .LogFactor y;
import org.apache.struts.Globals;
import org.apache.struts.action.A ctionError s;
import org.apache.struts.action.A ctionMessa ge;
import org.apache.struts.action.A ctionMessa ges;
import org.apache.struts.util.Mes sageResour ces;
import org.apache.struts.util.Req uestUtils;
/**
* CODE TAKEN FROM RegistrationServlet of appFuse example
* Implementation of <strong>HttpServlet</stron g> 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(Registra tionServle t.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";//reque st.getSess ion().getA ttribute(" FileName") .toString( );
String strForward = "FileUpload.jsp"
File f = new File("C:\\Documents and Settings\\jbaisden\\" +
"Desktop\\checkDigit\\chec kDigit\\We bContent\\ " +
"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("Conten t-Disposit ion","atta chment; 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.getMe ssage());
} 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(re sponse.enc odeRedirec tURL(route ));
dispatch(request, response, strForward);
}
/**
* Dispatch request to common JSP
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
public void dispatch(HttpServletReques t request,
HttpServletResponse response, String jsp)
throws IOException, ServletException {
// forward back to the register.jsp
RequestDispatcher dispatcher = request.getRequestDispatch er("/" + 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.
<!-- ******************** FORCE DOWNLOAD SERVLET REVISION ************** -->
package myorg.ID.action;
import java.io.IOException;
import javax.servlet.RequestDispa
import javax.servlet.ServletExcep
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSes
import javax.mail.MessagingExcept
import org.apache.commons.beanuti
import org.apache.commons.lang.St
import org.apache.commons.logging
import org.apache.commons.logging
import org.apache.struts.Globals;
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.action.A
import org.apache.struts.util.Mes
import org.apache.struts.util.Req
/**
* CODE TAKEN FROM RegistrationServlet of appFuse example
* Implementation of <strong>HttpServlet</stron
* to allow users to self-register.
* <p/>
* <p><a href="RegistrationServlet.
*
* @author Matt Raible
* @version $Revision: 1.21 $ $Date: 2004/02/28 05:59:08 $
* @web.servlet display-name="Registration
* 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(Registra
/**
* 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
throws IOException, ServletException {
String filePath = "/checkDigit/";
String dummy = null;
String filename = "results_test.txt";//reque
String strForward = "FileUpload.jsp"
File f = new File("C:\\Documents and Settings\\jbaisden\\" +
"Desktop\\checkDigit\\chec
"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("Conten
out = new BufferedOutputStream( response.getOutputStream()
in = new BufferedInputStream( fis );
String contentType = null;
if( contentType == null ) contentType = "APPLICATION/OCTET-STREAM"
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.getMe
} finally {
if( in != null ) try { in.close(); } catch( Exception e ) {}
if( out != null ) try { out.close(); } catch( Exception e ) {}
}
}
//response.sendError( HttpServletResponse.SC_NOT
//response.sendRedirect(re
dispatch(request, response, strForward);
}
/**
* Dispatch request to common JSP
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
public void dispatch(HttpServletReques
HttpServletResponse response, String jsp)
throws IOException, ServletException {
// forward back to the register.jsp
RequestDispatcher dispatcher = request.getRequestDispatch
dispatcher.forward(request
}
}
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.
ASKER
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>
<!-- =========================F ORM BEANS DEFINITION =================== -->
<form-beans>
<form-bean name="FileUploadForm"
type="gov.wi.state.dpi.che ckDigit.Fo rms.FileUp loadForm" >
</form-bean>
</form-beans>
<!-- =========================A ction Mapping DEFINITION =================== -->
<action-mappings>
<action path="/FileUpload"
type="gov.wi.state.dpi.che ckDigit.Ac tions.File UploadActi on"
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.appli cation"/>
<plug-in className="org.apache.stru ts.validat or.Validat orPlugIn">
<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</serv let-name>
<servlet-class>org.apache. struts.act ion.Action Servlet</s ervlet-cla ss>
<init-param>
<param-name>config</param- name>
<param-value>/WEB-INF/stru ts-config. xml</param -value>
</init-param>
<init-param>
<param-name>debug</param-n ame>
<param-value>2</param-valu e>
</init-param>
<init-param>
<param-name>detail</param- name>
<param-value>2</param-valu e>
</init-param>
<load-on-startup>2</load-o n-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</serv let-name>
<url-pattern>*.do</url-pat tern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</w elcome-fil e>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-b ean</tagli b-uri>
<taglib-location>/WEB-INF/ struts-bea n.tld</tag lib-locati on>
</taglib>
<taglib>
<taglib-uri>/tags/struts-h tml</tagli b-uri>
<taglib-location>/WEB-INF/ struts-htm l.tld</tag lib-locati on>
</taglib>
<taglib>
<taglib-uri>/tags/struts-l ogic</tagl ib-uri>
<taglib-location>/WEB-INF/ struts-log ic.tld</ta glib-locat ion>
</taglib>
<taglib>
<taglib-uri>/tags/struts-n ested</tag lib-uri>
<taglib-location>/WEB-INF/ struts-nes ted.tld</t aglib-loca tion>
</taglib>
<taglib>
<taglib-uri>/tags/struts-t iles</tagl ib-uri>
<taglib-location>/WEB-INF/ struts-til es.tld</ta glib-locat ion>
</taglib>
<resource-ref id="ResourceRef_1088625022 021">
<description>Oracle Datasource Reference</description>
<res-ref-name>jdbc/ds11</r es-ref-nam e>
<res-type>javax.sql.DataSo urce</res- type>
<res-auth>CONTAINER</res-a uth>
</resource-ref>
<env-entry>
<description>oracle datasource</description>
<env-entry-name>oracle_dat asource</e nv-entry-n ame>
<env-entry-value>jdbc/ds11 </env-entr y-value>
<env-entry-type>java.lang. String</en v-entry-ty pe>
</env-entry>
</web-app>
<?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>
<!-- =========================F
<form-beans>
<form-bean name="FileUploadForm"
type="gov.wi.state.dpi.che
</form-bean>
</form-beans>
<!-- =========================A
<action-mappings>
<action path="/FileUpload"
type="gov.wi.state.dpi.che
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.appli
<plug-in className="org.apache.stru
<set-property property="pathnames" value="/WEB-INF/validator-
/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</serv
<servlet-class>org.apache.
<init-param>
<param-name>config</param-
<param-value>/WEB-INF/stru
</init-param>
<init-param>
<param-name>debug</param-n
<param-value>2</param-valu
</init-param>
<init-param>
<param-name>detail</param-
<param-value>2</param-valu
</init-param>
<load-on-startup>2</load-o
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</serv
<url-pattern>*.do</url-pat
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</w
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-b
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-h
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-l
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-n
<taglib-location>/WEB-INF/
</taglib>
<taglib>
<taglib-uri>/tags/struts-t
<taglib-location>/WEB-INF/
</taglib>
<resource-ref id="ResourceRef_1088625022
<description>Oracle Datasource Reference</description>
<res-ref-name>jdbc/ds11</r
<res-type>javax.sql.DataSo
<res-auth>CONTAINER</res-a
</resource-ref>
<env-entry>
<description>oracle datasource</description>
<env-entry-name>oracle_dat
<env-entry-value>jdbc/ds11
<env-entry-type>java.lang.
</env-entry>
</web-app>
ASKER
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>ForceDownloa
<servlet-class>
myorg.ID.Actions.ForceDown
</servlet-class>
<load-on-startup>0</load-o
</servlet>
<servlet-mapping>
<servlet-name>ForceDownloa
<url-pattern>ForceDownload
</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>Preferences>J
*/
package myorg.ID.Actions;
/**
* @author jbaisden
*
* To change the template for this generated type comment go to
* Window>Preferences>J
*/
import java.io.BufferedInputStrea
import java.io.BufferedOutputStre
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.RequestDispa
import javax.servlet.ServletConfi
import javax.servlet.ServletExcep
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
import javax.servlet.http.HttpSer
/**
* CODE TAKEN FROM RegistrationServlet of appFuse example
* Implementation of <strong>HttpServlet</stron
* to allow users to self-register.
* <p/>
* <p><a href="RegistrationServlet.
*
* @author Matt Raible
* @version $Revision: 1.21 $ $Date: 2004/02/28 05:59:08 $
* @web.servlet display-name="Registration
* 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(Registra
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
throws IOException, ServletException {
String filePath = "/checkDigit/";
String dummy = null;
String filename = "results_test.txt";//reque
String strForward = "FileUpload.jsp";
File f = new File("C:\\Documents and Settings\\jbaisden\\" +
"Desktop\\checkDigit\\chec
"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("Conten
out = new BufferedOutputStream( response.getOutputStream()
in = new BufferedInputStream( fis );
String contentType = null;
if( contentType == null ) contentType = "APPLICATION/OCTET-STREAM"
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.getMe
} finally {
if( in != null ) try { in.close(); } catch( Exception e ) {}
if( out != null ) try { out.close(); } catch( Exception e ) {}
}
}
//response.sendError( HttpServletResponse.SC_NOT
//response.sendRedirect(re
dispatch(request, response, strForward);
}
/**
* Dispatch request to common JSP
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
public void dispatch(HttpServletReques
HttpServletResponse response, String jsp)
throws IOException, ServletException {
// forward back to the register.jsp
RequestDispatcher dispatcher = request.getRequestDispatch
dispatcher.forward(request
}
}
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!
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*
on my comp) and Im very glad it worked for you! :D
*tips hat off to you*
ASKER
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.
the execute one.. If i were you i would read more about struts and forwards inside
an Action. *shrug*