Saving JSP output to a file

I need to be able to save what a user sees on his browser, to a local file (where the web app runs).
The content is dynamic. It is being created using a JSP.
One way to write it to a local file would be to move the content creation from a JSP to a servlet and write to the HTTP response as well as to a file in the servlet.
That's going to make it look messy.
Any thoughts on how I could make this happen while continuing to use a JSP?

OK, so now I've tried it, it's essentially what is described in the J2EE tutorial:
/* File 1 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
* passes on a subclass of HttpServletResponseWrapper
* in order to replace the output writer.
public class OutReplacementFilter implements Filter {
  public void init(FilterConfig filterConfig) throws ServletException {  }
  public void destroy() {  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
    //wrap the original response
    HttpServletResponse newResponse = new ReplacementHttpServletResponse((HttpServletResponse) response);
    //pass it to the resource
    chain.doFilter(request, newResponse);
    //get what the resource wrote
    String output = newResponse.toString();
    //put it to the output stream
    PrintWriter out = response.getWriter();
    out.write(output);
    out.close();
    //and then put it where ever else you like
    System.out.println(output);
/* File 2 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
* returns specialized writer to capture jsp output
public class ReplacementHttpServletResponse extends HttpServletResponseWrapper {
  private CharArrayWriter replacementWriter;
  public ReplacementHttpServletResponse (HttpServletResponse response) {
    super(response);
    replacementWriter = new CharArrayWriter();
  public PrintWriter getWriter() throws IOException {
    return new PrintWriter(replacementWriter);
  public String toString() {
    return replacementWriter.toString();
}This way is easy and few keystrokes, but buffers all the output until the filter chain returns.

Similar Messages

  • Saving report output to a file on the server.

    Hi,
    We are using BI Publisher Standalone version 10.1.3.3.1.
    Is it possible to schedule a report to output to a file on the server?
    I want the whole report to be saved as a file on the server.
    This is somewhat similar to bursting to a file system, but, I don't want to split the output.
    Any help is appreciated.
    Thanks,
    Nanda

    Yes, use the scheduler and schedule the report,
    do the bursting into FTP or
    schedule the report to run and run it into FTP as a single FILE.
    First option, you need to provide the query , with FTP server name, username, password etcccc.

  • Saving RMAN output to os file..

    Dear Rman Gurus!
    I'd like to save an RMAN output to os file.. for example this would be terrific:
    RMAN> list backup; > /home/oralce/os_user/list.txt ???
    is this possible? how do you have this solved in your env? I cannot find the right solution..
    I am using version 8 and 9.. so spool log is not quite good as it doesn't work with v. 9..
    Many thanks for your suggestions!
    agat81

    RMAN v. 8Are you talking about 8i or 8.0?
    The LOG option is available in 8i, but I don't believe the SPOOL LOG option is available. I have no idea about 8.0.

  • Saving an output in a file

    Hi all, i am having problems with an assignment that i have. I have to prompt the user for a dna sequence and a description of that sequence and then save it to a file., but when i go to look at the file that i created, it give me the memory address of that sequence and then the description always returns null like i never set it. Can anyone help.
    Sequence.java(you shouldn't need this but in case you do)
    public class Sequence
        // instance variables - replace the example below with your own
        public String sequence;
        public String description;
        public double energy;
        public int number;
        public int temp;
        public double boltzman;
        public final double gasConstant = 1.9872;
         * Constructor for objects of class sequence
        public Sequence()
            // initialise instance variables
            sequence = " not set";
            description = "  not set";
            energy = 0;
            number = 0;
            temp = 0;
            boltzman = 0;
         /**initialize variables
         public Sequence(String aSequence, String aDescription)
             sequence = aSequence;
             description = aDescription;
         /** Sets the sequence
         public void setSequence(String aSequence){
             sequence = aSequence;
         /** Returns the sequence
         public String getSequence(){
             return this.sequence;
         /** Sets the description
         public void setDescription(String aDescription){
             description = aDescription;
         /** Returns the description
         public String getDescription(){
             return this.description;
         /** sets the energy
         public void setEnergy(double aEnergy){
             energy = aEnergy;
         /** returns the energy
         public double getEnergy(){
             return this.energy;
         /** sets number
         public void setNumber(int aNumber){
             number = aNumber;
         /** returns that number
         public double getNumber(){
             return this.number;
         /** sets temp
         public void setTemp(int aTemp){
             temp = aTemp;
         /** returns temp
         public int getTemp(){
             return this.temp;
          /** calculates the number of A's and T's
        public int countATs(){
            int count = 0;
            String at = "AT";
            for (int i=0; i < sequence.length(); i++)
                char ch = Character.toUpperCase(sequence.charAt(i));
                if(at.indexOf(ch) >= 0)
                count++;
            return count;
      /** calculates the number of C's and G's
        public int countCGs(){
            sequence = this.sequence;
            int count = 0;
            String cg = "CG";
            for (int i= 0; i < sequence.length(); i++)
                char ch = Character.toUpperCase(sequence.charAt(i));
                if(cg.indexOf(ch) >= 0)
                count++;
            return count;
         /** calculates boltzmann factor
         public double calculateBoltzman(){
            boltzman = Math.exp(-(energy)/(gasConstant*temp));
            return boltzman;
        /** calculates number-- number overflows when the integer exceeds 32-bits...(i.e. 4^200000000000)
        public int calculateNumber(){
            number = (int)Math.pow(sequence.length(),4);
            return number;
         * ToString method that returns the sequence.
         public String toString(){
             return super.toString()+" The Sequence is  "+ "\n"+this.sequence+"\n"+" The Description is "+"\n"+ this.description+"\n";
    }SequenceTest.java <---where my problem is
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.*;
    * A Class to Sequence.
    * @author (Corbin Blake)
    * @version (10/20/04)
    public class SequenceTest
    public static String desc;  
    public static String[] b;   
         public static void main(String[] args) throws IOException
          while (true)
              System.out.println("Welcome to my program!");
              try
                  System.out.println();
                  System.out.println("Enter d to enter a new DNA sequence, s to save the entered sequence to a file, and x to exit:  ");
                  BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                  String input = console.readLine();
                  Sequence aSequence = new Sequence();
                  String[] sequenceArray = new String[10];
                  if (input.equalsIgnoreCase("d"))
                    //keeps track of exactly how many elements are being used in the array
                    int sequenceSize = 0;
                    // asks the user for an input
                    System.out.println("Enter a DNA Sequence: ");
                    // gets the input string from the user
                    String input0 = console.readLine();
                    //stores that input as an array
                    sequenceArray = new String[input0.length()];
                    String[] b = sequenceArray;
                    //checks to see if arraysize needs to be doubled and doubles it if necessary
                    if(sequenceSize >= sequenceArray.length)
                        MyUtilities.myarraycopy(sequenceArray);
                    //enters a description
                    System.out.println("Enter a Description of the Sequence: ");
                    //gets input from the user
                    String input1 = console.readLine();
                    String desc = input1;
                  else if (input.equalsIgnoreCase("s"))
                       //asks to save information
                       System.out.println("Enter the name of the file( as a .txt file):");
                       String input2 = console.readLine();
                       //saves the information to the filename of the users chosing.
                       FileOutputStream out;//declares a fileoutput object
                       //declares a printstream object
                       PrintStream p;
                       String [] x = sequenceArray;
                       try
                           //creates a new file output stream connected to the user input
                           out = new FileOutputStream(input2);
                           //connect the printstream to the output stream
                           p = new PrintStream(out);
                           p.println("The saved DNA sequence is: " + b +"/n"+ "The Description is: "+ desc);
                           // exit
                           p.close();
                        catch (Exception e)
                            System.err.println ("Error writing to file");
                  else if (input.equalsIgnoreCase("x"))
                      break;
                  else
                      System.out.println("You have entered an invalid letter, please try again");
                      continue;
        catch (IOException e)
                      break;
              System.out.println("Thank you for using the application");
    }

    I guess we are discussing this line:
    p.println("The saved DNA sequence is: " + b +"/n"+ "The Description is: "+ desc);b is a String[] and arrays don't have overridden toString(). You can use Arrays.asList(b) to get a better String representation or make your own method that lists array to String.
    As far as the null desctiption is concerned - is is possible that there is no more input and readLine returns null?
    HTH
    Mike

  • AppleScript: Saving text output to a file

    Hi all,
    I am trying to save some output to a text file from AppleScript. Based on some postings I've found, I've been trying variations on this where theSubjects has some formatted text in it.:
         tell application "TextEdit"
              activate
              make new document
              set text of document 1 to theSubjects
              save document 1 in file (("/Users/karl/Desktop/") & "ListSubjects.rtf")
         end tell
    The text makes it into TextEdit as I intended, but when the script tries to save the file, I'm getting "The document "Untitled" could not be saved as "/Users/karl/Desktop/ListSubjects.rtf". You don't have permission."
    This error is consistent across all output directories that I have tried. I cannot find any sign that there are actual permissions issues.
    Any suggestions would be appreciated.
    Thank you.

    Yes, use the scheduler and schedule the report,
    do the bursting into FTP or
    schedule the report to run and run it into FTP as a single FILE.
    First option, you need to provide the query , with FTP server name, username, password etcccc.

  • Saving List Output to a file

    Hi all,
    I have developed one classical report in that user is saving the report output to a text file from menu list->Save/Send>File> Unconverted
    there every time user has to enter path and file name and he replace the existing file by replace option.
    Is there any way to pass this info. (path,file name) dynamically?
    I want that when user finish with parameter form then automatically the out put is stored in the file with predifine name.
    Thanks in advance.
    Deval Bhatt
    Message was edited by:
            Deval Bhatt

    Hi,
    Use fm
    Create Application Button using your PF status as "Download List" and use the following function module to download
      sy-lsind = sy-lsind - 1.
      call function 'LIST_DOWNLOAD'
           exporting
                list_index = sy-lsind
                method     = 'RTF'
           exceptions
                others     = 1.
    aRs

  • Problem while saving list output as local file.

    Hi Gurus!
    i want to save the list output of classical report into excel but complete data is not coming into excel file.
    [SYSTEM - > LIST ->SAVE ->  LOCAL ->SPREADSHEET ]
    when same output is transfer to unconverted file [notepad ] then completed data is coming.
    please help me ,
    points sure!
    Rahul
    Message was edited by:
            rahul deshmukh

    Yes Rahul, I know that and you have to do the formating. This is how you can do.
    Open the unconverted file in Excel format.
    Select the first column and then goto Data - Text to Columns , a pop up will come.
    Select Delimited, then press next.
    Then selct the delimeter that is used in the unconverted file to seperate two columns. Say for example if ' | ' is used then in others write ' | ' and press next.
    IN the data preview section select all the columns and then select text radio button on top and press finish finally.
    Now u will get the proper format of the file. Delete all the empty rows and columns that u don't want.
    Reward if you find it useful.
    Regards.
    Akhil.

  • Adding numbers in a file a and saving the output in another file.!

    can any one pls tell me how to add numbers from a textfile and save the output in another textfile. i'm new with java so pls help out..

    Hi Friend,
    your statement is not clear, it's bit confuse
    this is my unserstanding,
    you want to open a file and read the values then add numbers,
    latter save the sum in a new file.let me know if this is the thing, I can help u
    with Cheers
    Prasanna

  • Saving JSP source to a file

    Hi, im having some problems finding out how to write the source of a jsp file to another file. In other words i want to save the source to a file instead of just writing it to the browser. JspWriter (out)dont seem to have a method for this. Does anybody know how this could be done? I would be very grateful for your help!
    Thanks in advance!
    regards,
    claus jensen

    I cant find any methods in the Filter, FilterChain or ServletResponse to actually get the content of the file. Do you have an example for this, or maybe some urls to resources where i can find more info on it?
    Thank you.
    Claus

  • Save the JSP output to a file

    Hello,
    Is there any way to save the JSP result (HTML) to a file ? The reason for this is that I want to enable caching in the middle tier.
    Thanks in advance
    Leonard Schleien
    [email protected]

    By the way, I am using JSP 1.0 and Servlet 2.1 with Websphere Application Server 3.02

  • Saving JSP report output as a file on the application server

    I am trying to determine if it is possible to save a web based JSP report to the file system in the same way you can with a report generated via the rwservlet command. I am specifying DESTYPE=HTML and DESNAME=/home/mydirectory/abc.htm on the command line, but it seems to be ignored. The directory has 777 permissions on it.
    1. Is it possible to save the JSP output onto the file system just like paper based reports?
    2. Where, if any, is documentation addressing this issue? The reports deployment guide appendix lists all the URL parameters that are available to the various rw commands, but nowhere is discussed what params are relavent to JSP reports.
    3. If it is not possible to do this via the URL, does anyone know if I can somehow fetch out the inner HTML from the generated page at the bottom pf the JSP and then write it to the file system using JAVA? I know how to do it via JavaScript, but the reports are run on UNIX. Is there someway I can access the DOM inside the JSP?
    4. Why hasn't Oracle explained this better?
    Thanks,
    matt

    Thanks for getting back to me. But the documentation link below takes me to running rwservlet requests. This was not what I needed. The good news is my most excellent DBA, Manoj Gandhi, found an old TAR in Metalink that emphatically states that what I am trying to do is not possible. See Note:272401.1
    Well, sort of not possible...
    As it turns out it is possible, but you must schedule the report for immediate execution using the rwservlet's scheduling facility. Again, this came to me via my DBA. The TAR for this piece is Note:295420.1. Ignore the rwservlet urlparameter= part as best I can tell it's gibberish. Below is what I did. Substitute your info for the stuff in UPPER CASE and put it all on one contiguous line of course:
    http://SERVER:PORT/PATH/rwservlet
    ?server=REPORT_SERVER_NAME
    &destype=file
    &desname=A_PATH_AND_FILE_FILE_NAME_WITH_EXTENSION
    &jobtype=rwurl
    &schedule=
    &urlparameter=http://SERVER:PORT/PATH/JSP_NAME?userid=USERID&OTHER_PARAMETERS...
    I am not sure why cmdkey= fails when passed in the urlparameter= but I am working on a solution!

  • Saving ALV Grid to Local File issue - Missing half of the report

    Hi Experts, Good Day.
    I have developed an ALV Grid report using class CL_SALV_TABLE which displays 200 Columns and 100+ rows/records. It is displaying well, but when I am saving the output into local file (any type) there only 98 columns are downloading and remaining all the columns are missing.
    I would like to know whether there is any restriction for number of columns or what might the problem for it. How can I download all the columns into local file.
    Thanks in Adv.
    Vijay

    Hi,
    Thanks for your response. Even though there are multiple ways to send data to local file I believe all three are same. And even I am facing same issue all the ways. Only 98 Columns data is getting downloaded into Files (it might be .txt, .xls, etc.).
    After downloading first 98 Columns, I am hiding the downloaded columns and again I am downloading remaining columns. Then I am merging in the Excel file. This is very complicated for the End-User. So, please help me out.
    I have used only following methods for displaying ALV.
    For initial object/instance:
    CL_SALV_TABLE=>FACTORY,
    For ALV functions:
    CL_SAVL_TABLE->GET_FUNCTIONS,
    CL_SALV_FUNCTIONS_LIST->SET_ALL,
    For Column heading and Optimized width:
    CL_SALV_TABLE->GET_COLUMNS,
    CL_SALV_COLUMNS_TABLE->SET_OPTIMIZE,
    CL_SALV_COLUMNS_TABLE->GET_COLUMN,
    CL_SALV_COLUMN->SET_SHORT_TEXT,
    To display grid:
    CL_SALV_TABLE->DISPALY.
    - Thanks
    Vijay

  • Convert ing JSP page to PowerPoint  file

    How can I convert my JSP output to PPT file .The stuff that I would like to convert could be either text or simetimes images also.

    You won't find any answers to that question. I would stand on the other side of the client's screen and ask it from that point of view: where can you get something to convert a set of HTML files into a Powerpoint presentation? That, of course, has nothing to do with Java programming, but I suspect it has an answer if you search the right part of the web.

  • Saving the output of a .sql file in .csv format

    Hi,
    I am saving the output of a .sql file in .csv format. But the problem is , the record of few columns have "new line" character in it, so when it is getting saved in .csv format, those records are coming in multiple rows, but they should come in one single row in single block. Please advise how to overcome this problem.
    Regards,
    Niraj

    Hi Guys,
    I guess, there is a misunderstanding.
    He is talking about the issue caused as a result of the data containing a "CRLF" ( Carriage return Line feed ) .
    That is mainly a data issue.
    The query i presume, must be right.
    I guess you should be able to fix it using some string functions.
    Some thing similar to this
    CREATE TABLE ASH (NAME VARCHAR2(10))
    SELECT REPLACE(NAME, CHR(13)||CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(13), 'ISH') FROM ASH;
    depending on the type of new line whether it is CR or LF. or CRLF.
    Regards
    Ashish/-

  • How to output a postscript file with .ps extension name in jsp?

    Hi,
    I could use a servlet to output a postscript file with .ps file extension name. But I tried to do the same with jsp, for some reason, jsp always outputs a file with .jsp extension name though the content is postscript. Could anyone help me on this? Here is my jsp code:
    <%@page contentType="application/postscript"%>
    <%@page pageEncoding="UTF-8"%>
    <%@page import="java.util.*" %>
    <%@page import="java.io.*" %>
    <jsp:useBean id="corresv" class="oiintranet.CorresVBean" scope="request"/>
    <%
    response.setContentType("application/postscript");
    String corresId = request.getParameter("Id");
    corresv.setCorresId(corresId);
    PrintWriter output = response.getWriter();
    output = corresv.getResult(output);
    output.flush();
    %>
    In the bean corresv:
    public class CorresVBean extends BaseBean {
    private String corresId;
    public void setCorresId(String s) {
    this.corresId = s;
    public PrintWriter getResult(PrintWriter output) {
    //get postscript file content from a socket, one string line each time until reaches "X_END"
    String str;
    while ((str = in.readLine()) != null) {
    if (str.equals("X_END")) break;
    output.println (str);
    output.close();
    }catch(Exception e) {
    e.printStackTrace();
    return output;
    Thank you in advance.
    Geraldine

    Hi
    Every time u want to make a file u need to make its extension. I am talking
    about general scenario like word, excel so even when u make spool file
    so u need to give extension.
    like
    Spool temp.sql
    it will save u r file as sql file.
    hope it will help
    regards

Maybe you are looking for