Sending resourceStream on a response object

Hi all,
i need to attach a resource stream to a servlet response in a
chain.doFilter(httpRequest,response);
ie i want to return this
this.getClass().getClassLoader().getResourceAsStream(ParameterSource);
the resource will always be an image or a style sheet so is there any need to specify mime type in the response header?
Can anybody help me with the lcode to add the resourceStream to the response?
Thanks in advance
Alex

solved the above proble and narrowed the first down to 2 solutions
1)
make the inputstream into an array of bytes and feed into outputstream for the response
2)
use request =dispatcher to forward resource needed
requestdispatcher rd = request.getrequestdispatcher(RESOURCE);
rd.forward(RESOURCE);
i'm not sure if the second option will work because the resorce may be located in a .jar file?
Has anybody else any comments or suggestions?
Alex.

Similar Messages

  • How to send an object thru "response" object

    I need to send an object to a servlet thru my jsp page.
    When I created an ObjectOutputStream passing response.getOutStream as parameter, I am getting an IllegalStateException. I have checked that the response object is not being used anywhere else.
    Please help me out.
    Thanks a ton

    Try this and let me know
    try {
    ObjectOutputStream p = new                          ObjectOutputStream(
         response.getOutputStream() );
    p.writeObject("what ever object");
    p.flush();
    p.close();
    }catch (Exception e) {
    e.printStackTrace();
    I use this in my code and it works perfectly. If it still does not work, send me the entire code that you have written and I shall try to look into it and see whats going wrong.
    --ramsci                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Response object in JSP Dyn page

    Hi SAP EP Gurus,
    I want to use response.setStatus() mehtod in jspdynpage but it is not working as expected. I am able to use other methods of response object like response.write().
    As per my knowledge if i set response.setStatus(200) is should send error to client but it is not seding error.
    It is working as same for both response.setStatus(200) and response.setStatus(500).
    Is there any special way to use response.setStatus() in portal? It is working as expected in normal jsp application.

    I tried but had no luck. Below is my JSPDYNPAGE code...
    <%@ page import="javax.servlet.http.HttpServletResponse" %>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentRequest,com.sapportals.portal.prt.component.IPortalComponentResponse"%>
    <HTML>
         <head>
         </head>
         <body>
    <%
    IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
    HttpServletResponse servletResponse = request.getServletResponse(true);esss
    servletResponse.setStatus(500);
    %>
              </body>
         </HTML>
    It is not working showing portal run time error

  • WebService response object in XML - parsing attributes

    Hi- new to Flex and I'm trying to parse out the attributes of the response object. I can get the entire object and see that its working, but I cant get just a single attribute. It pulls weather info for world cities. For example, I just want the location name and temperature.
    Any advice on this? Thanks!
    <?xml version="1.0"?>
    <!-- fds\rpc\RPCResultFaultMXML.mxml -->
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                    xmlns:s="library://ns.adobe.com/flex/spark">
        <mx:Script>
            <![CDATA[
                import mx.rpc.soap.SOAPFault;        
                import mx.rpc.events.ResultEvent;
                import mx.rpc.events.FaultEvent;
                import mx.controls.Alert;
                import mx.utils.ObjectUtil;
                public function showErrorDialog(event:FaultEvent):void {
                    // Handle operation fault.
                    Alert.show(event.fault.faultString, "Error");
                public function defaultFault(event:FaultEvent):void {
                    // Handle service fault.
                    if (event.fault is SOAPFault) {
                        var fault:SOAPFault=event.fault as SOAPFault;
                        var faultElement:XML=fault.element;
                        // You could use E4X to traverse the raw fault element returned in the SOAP envelope.
                    Alert.show(event.fault.faultString, "Error");              
                public function log(event:ResultEvent):void {
                    // Handle result.
                    trace(event.result);
                    //trace(ObjectUtil.toString(event.result));
                    //var len:int;
                    //len = event.result.length;
                    //trace(len);
                    //trace(event.result);
                    //trace(event.result.GetWeatherResponse.Location);
                    //var myXML:XML = new XML(event.result);
                    //trace(myXML.attribute("Location"));
            ]]>
        </mx:Script>
        <mx:WebService id="WeatherService" wsdl="http://www.webservicex.com/globalweather.asmx?wsdl"
                       fault="defaultFault(event)">
            <mx:operation name="GetWeather"
                          fault="showErrorDialog(event)"
                          result="log(event)"
                          resultFormat="xml">
                <mx:request>
                    <CityName>{myCity.text}</CityName>
                    <CountryName>{myCountry.text}</CountryName>
                </mx:request>
            </mx:operation>
        </mx:WebService>
        <mx:TextInput id="myCity" text="Madrid"/>
        <mx:TextInput id="myCountry" text="Spain"/>
        <!-- Call the web service operation with a Button click. -->
        <mx:Button width="60" label="Get Weather"
                  click="WeatherService.GetWeather.send();"/>
        <!-- Display the Weather -->
        <mx:Label text="Weather:"/>
        <mx:TextArea text="{WeatherService.GetWeather.lastResult}" height="200"/>
    </mx:Application>

    The WSDL says GetWeatherResponse is a string, and it appears to be a string of XML, so set <mx:operation resultFormat="object"> as this will unwrap the SOAP response value and leave a string typed value intact. You can then create a new ActionScript 3.0 E4X-based XML instance from the unwrapped string:
        var myXML:XML = new XML(event.result.toString());
    You can then travese the XML document using E4X syntax, a simple example is included below:
        trace(myXML..Location);
        trace(myXML..Temperature);

  • URGENT! Can response object contain text as well as binary data

    hi all,
    My test scneario is like this..
    a) User is having a button "Download File" i will call this as download.jsp
    b) After hitting the download button i will be sending the file to user by writting into the ServletOutputSream.
    c) Whatever option user chooses (i.e. Save / Open / Cancel) I want to do some updations on the existing user screen.
    Maybe presenting him the download status e.g. "File Downloaded"
    The problems i am facing are
    1. SInce i am using ServletOutputSream once i flush the stream i loose the control on response object.
    2. After user's operation (i.e. Save / Open / Cancel) unless user again hits
    something on UI my server has to look at him with dumb eyes. :(
    3.The download operation that i am performing expects some attributes from the request ..
    they are Object attributes and not string attribute so i cant user URL rewritting.
    If anybody has encountered this type of problem in there projects please share the workaround you used.
    Thanx a lot
    --Bhupendra Mahajan

    Here in order to send the file to Client i must use Stream ... and in prder to
    update the status i.e. HTML i must use Printwritter.... That is the reason
    i need both ... If you have some OutputStream available deep down somewhere you can use
    both; it just takes a bit of discipline:OutputStream ros; // available from somewhere
    // use the following stream for your binary output:
    BufferedOutputStream bos= new BufferedOutputStream(ros);
    // and use this one for your PrintWriter:
    PrintWriter pw= new PrintWriter(bos);Everytime before you want to print some binary data, flush the pw, and everytime
    before you want to print some text data, flush the bos.
    kind regards,
    Jos

  • Clearing Request / Response Objects

    Hi,
    I have a File Upload Screen where I have validated for the File Content Length to be within 3 MB. Now I call the MultiPartRequest Reusable Object provided by Jason Hunter from a Servlet. Now as long as the file (which I am uploading) size is less than 3 MB, the Screen seems to be very fast. The Problem that I face is as follows:
    I am trying to upload a file of 5 MB file size. Since my validation is in the Reusable MultiPartRequest Object, an Exception is thrown out of this Object and caught in the Servlet.
    Scenerio 1:
    Now from the Servlet I was using RequestDispatcher to forward to the Error Page. Since when I forward like this, the same request Object is send back to the Client which increases the response time. For me the Screen crashes due to Browser Time out.
    Scenerio 2:
    Now from the Servlet I tried using response.sendRedirect to the Error Page. Still the response time is more but comparatively less than the Scenerio 1.
    My Question:
    1. Is there a way to clear the contents of the Request and Response Object so that the response time to the client is reduced?
    2. I think what I am asking is not possible. But still taking a chance is not a mistake. Is there a way to create a new Request or Response Object? I believe we (as an application developer) have no control over this as the Application Server will have control over this.
    Any help or tips would be appreciated.
    Thanks and regards,
    Pazhanikanthan. P

    Hi,
    Thanks for your response. I do agree it is not the problem with the Multipart Classes.
    Kindly see the following URL for the differences between RequestDispatcher.forward () and response.sendRedirect ().
    http://www.theserverside.com/discussion/thread.jsp?thread_id=742
    Here they say that "the request and response objects remain the same both from where the forward call was made and the resource which was called." Is this wrong?
    More over I found that MultipartParser doesnt improve the performance very drastically over the MultipartRequestObject ...
    Please find attached the time I have calculated in between the time I forward / redirect in Servlet to the time when the response is painted in the Screen.
    Using Send Redirect Method (in Seconds)
    =======================================
    MultipartParser.java
    170.156
    MultipartRequestObject.java
    172.422
    Using requestDispatcher.forward () (in seconds)
    ==============================================
    MultipartParser.java
    Browser Times out
    MultipartRequestObject.java
    Browser Times out
    Here is my code:
    public void doPost(HttpServletRequest request,HttpServletResponse response)
         throws ServletException, IOException
         HttpSession objSession = request.getSession(true);
         String strFilePath = "D:\\uploads";
         String strFilename = "";
         MultipartRequestObject clsMulti;
         MultipartParser clsMultiParser;
         try
              System.out.println ("Action is :" + request.getParameter ("hdAction"));
              if (request.getParameter ("hdAction") == null)
                   clsMultiParser = new MultipartParser (request, 1*1024*1024);
                   Part objPart = clsMultiParser.readNextPart ();
                   if (objPart != null)
                        FilePart objFilePart = (FilePart) objPart;
                        System.out.println ("The File Name is : " +objFilePart.getFileName ());
                        objFilePart.writeTo (new File (strFilePath + File.separatorChar + objFilePart.getFileName ()));
                   clsMulti = new MultipartRequestObject (request, strFilePath, 1*1024*1024);
                   Enumeration enumFiles=clsMulti.getFileNames();
                   while(enumFiles.hasMoreElements())
                        String strName=(String)enumFiles.nextElement();
                        strFilename = clsMulti.getFilesystemName(strName);
         catch(Exception expGeneral)
              System.out.println ("" + new java.util.Date () + "----" + expGeneral.getMessage ());
              objSession.setAttribute ("MESSAGE", expGeneral.getMessage ());
         try
              System.out.println (1);
              RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/Upload.jsp");
              System.out.println (2);
              java.util.Date dt1 = new java.util.Date ();
              System.out.println (dt1.getTime ());
              dispatcher.forward(request, response);
              System.out.println (3);
              java.util.Date dt1 = new java.util.Date ();
              System.out.println (1);
              System.out.println (dt1.getTime ());
              response.reset ();
              System.out.println (2);
              response.sendRedirect ("Upload.jsp");
              System.out.println (3);
              return;
         catch (Exception e)
              e.printStackTrace ();
    For testing pupose I have commented some part of the code.
    Thanks and regards,
    Pazhanikanthan. P

  • AMS NetStream Response Object

    I am creating a NetStream object in Adobe Media Server application, and getting the following error:
    Sending error message: Response object not found (_result:0).
    I have defined a handler for the onStatus message, which is working fine, but it doesn't catch this error. And I can't find any information on this error message anywhere. Indeed, the documentation on server-side error messages is very limited.
    The code causing this error is:
      var ns = null;
        try
        ns = new NetStream(application.nc);
        catch (e)
         trace("____NetStream error" + e.name + " " + e.message);
         return;
        ns.onStatus = netStreamStatusHandler;
    I am getting NetStream.Connect.Success though. And I was wondering if the NetStream constructor calls a method initStream() on the other server?
    thanks, Paul

    I highly recommend you read either the Sun Servlet tutorial or one on the web. But this should at least get you started:
    HttpServletRequest
    Used to retrieve HTML form parameters submitted to the Servlet
    Maintains a reference to the user's HTTP web session
    Used to inspect any HTTP headers sent by the client browser
    Used to retrieve any HTTP message body data (say, XML submitted to the server or form parameters, as above)
    Used to retrieve references to other objects descriping the Servlet configuration, intialization parameters, and container informationHttpServletResponse
    Used to send HTTP headers back to the client browser (content-type, content-length, etc.)
    Used to send HTTP message body data back to the client browser (HTML content, PDF content, etc.)The reason you passed the response object to sendPage2() is so the content type could be set (in this case, 'text/html' indicating an HTML web page) and so that a Writer reference could be obtained to output the actual HTML content back to the browser.
    - Saish

  • Two response objects within one servlet...

    Heya guys, quite new to java and got stuck for the whole day on this.
    I need to combine two responses inside one servlet. One response retrieves picture from the database and it works fine. Another one retrieves text from database also works fine on its own. Second i try to use both end up with hundreds of exceptions.
    Any idea what to do, not how...but what???
    Thanks

    Compiling 1 source file to F:\gopal\weba\WebApplication6\build\web\WEB-INF\classes
    F:\gopal\weba\WebApplication6\src\java\NewServlet.java:48:
    processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,javax.servlet.http.HttpServletResponse) in NewServlet cannot be applied to (javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    processRequest(request, response);
    F:\gopal\weba\WebApplication6\src\java\NewServlet.java:57: processRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,javax.servlet.http.HttpServletResponse) in NewServlet cannot be applied to (javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    processRequest(request, response);
    2 errors
    F:\gopal\weba\WebApplication6\nbproject\build-impl.xml:295: The following error occurred while executing this line:
    F:\gopal\weba\WebApplication6\nbproject\build-impl.xml:149: Compile failed; see the compiler error output for details.
    BUILD FAILED (total time: 2 seconds)
    You cannot use two response object.

  • Error with response object in Portal Application Module

    Hi,
    i have a portal application project in NWDS, with a JspDynpage component. I have a jsp that contains this code:
    OutputStream os = componentResponse.getServletResponse().getOutputStream();
    response.addHeader("Content-Disposition", "attachment;filename=" + sTITLE +".pdf");
    response.setContentType("application/pdf");
    os.write(contenido);
    os.close();
    this code open a pdf in new window. In web module project that app runs correctly but in portal application no, it fails in object response. the log (in default trace) doesn´t help me nothing, only sais:
    Jun 6, 2011 3:19:55 PM     com.sap.portal.prt.runtime.servlet_jsp [SAPEngine_Application_Thread[impl:3]_13] Error: >>> JSPCompiler >>> ERROR in Compiling :JSPFileInfo :314221189
    JSP File : /usr/sap/DP4/DVEBMGS40/j2ee/cluster/server0/apps/sap.com/irj/servlet_jsp/irj/root/web-inf/portal/portalapps/appl.factdist.efact.por/pagelet/inicio.jsp
    Class Name: sapportalsjspInicio
    Java File : /usr/sap/DP4/DVEBMGS40/j2ee/cluster/server0/apps/sap.com/irj/servlet_jsp/irj/root/web-inf/portal/portalapps/appl.factdist.efact.por/work/pagelet/_sapportalsjsp_inicio.java
    Package Name : pagelet
    Class File : /usr/sap/DP4/DVEBMGS40/j2ee/cluster/server0/apps/sap.com/irj/servlet_jsp/irj/root/web-inf/portal/portalapps/appl.factdist.efact.por/work/pagelet/_sapportalsjsp_inicio.class
    Is out dated : false [email protected]bbc2b
    In addition, i can use the request object perfectly
    somebody knows what's happening??
    Thank you,
    Fernando

    Hi,
    You shouldn't use the response object directly
    Instead, create a new HttpServletResponse reference from the componentRequest object.
    Try using the following:
    long length = file.length(); // where 'file' is a File() object of your sTITLE +".pdf" file
    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    //The most important part:
    HttpServletResponse res = componentRequest.getServletResponse(true);
    res.setContentType("application/pdf");
    res.addHeader("Content-Disposition", "attachment;filename=" + sTITLE +".pdf");
    res.getOutputStream().write(bytes);

  • How to send data to bam data object through java code

    how to send data to bam data object through java code

    I've made a suggestion in other thread: https://forums.oracle.com/thread/2560276
    You can invoke BAM Webservices (Using Oracle BAM Web Services) or use JMS integration using Enterprise Message Sources (http://docs.oracle.com/cd/E17904_01/integration.1111/e10224/bam_ent_msg_sources.htm)
    Regards
    Luis Fernando Heckler

  • HTTP request/response object not thread safe.

    According to the serlvet spec. Http Request/Response
    are not thread safe. Quoting from the Spec:
    " Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread. References to the request and response objects must not be given to objects executing in other threads as the resulting behavior may be nondeterministic."
    This has prompt me to ask the following question.
    For Example I have a servlet which does the following
    request.setAttribute("myVar","Hello");
    The request and response is dispatched(using RequestDispatch.include(request,response)) to another
    servlet which retrieve this attribute i.e request.getAttribute("myVar");
    Is this safe?
    The Spec only said "The Container Provider must ensure that the dispatch of the request to a target
    servlet occurs in the same thread of the same VM as the original request." I take this meaning that the targeting servlet does not have to run in the same thread(only dispatch), otherwise it would be safe.

    To put it another way, you can only have onle thing working on a request at a time. For instance, the ServletContext is available to all servlets running on a server. If you tried to save a particular request to the ServletContext, it would potentially be available to many concurrently running servlets. They could all change whatever in it at the same time. Each servlet is in its own running thread. Hope that helps some.

  • Web service response object contains no values

    Hi,
    Using Netweaver, I've created an EJB-based web service that contains a single method. The method takes two input parameters and returns as a response, a data transfer object (DTO) containing several boolean values.  When I test this web service with the Web Service Navigator however, the response object contains a flat DTO-- meaning the contents of the DTO are missing. For example, this is what happens now when I call the web
    service...
    Incoming parameters:
    ...userID (String) = some user ID
    ...systemID (String) = some system ID
    Outgoing parameters:
    ...response
    ......(nothing contained within response--
    ...... there should be boolean values here)
    But this is what I should see when I call the web service...
    Incoming parameters:
    ...userID (String) = some user ID
    ...systemID (String) = some system ID
    Outgoing parameters:
    ...response
    ......booleanValue1
    ......booleanValue2
    ......booleanValue3
    Documentation doesn't seem to address this problem. Does anyone know how to correct this?
    Thanks,
    Amy

    Hi
    Have you found the workaround?
    Sorry for refreshing topic. Flag mustUnderstand ='1' in response is unussual thing.
    BR

  • Does any one implemented solution for httpservlet request/response object in IWSDLInterceptor implemented class?

    I am trying to handle Producer not available situation in which I am using Interceptor IWSDLInterceptor in WLP 10.3.4. I am able to retrieve exception using onWSDLException but from here if I have to forward my pageURL object I need httpservlet request and response. I tried my own filter class to have its own customize request and also tried it out all other Interceptor to see if any one can handle IOException. I did manage to throw my own Customize exception but  that also did not work out as Page does not have any backing file or any supportive Controller class.
    Does any one implemented solution for httpservlet request/response object in IWSDLInterceptor implemented class? or do we have any specific documentation in regards to this? As I am not able to find much martial on IWSDLInterceptor except Java API from Oracle and article defining Two way SSL handshake Producer.
    Any kind of help is appreciated.
    Thanks
    PT

    Thanks Emmanuel for your response but render behavior is not available for IWSDLRequestContext/IWDSLResponseContext object which IWSDLInterceptor uses for implementation.
    Let me put my question in little simpler manner. May be my approach to the problem is not proper.
    Problem : Handle Producer Not available (no application exists on server) on consumer side.
    So far tried approach : Producer is not running then I am able to handle that TransportException at IInitCookieInterceptor/IHandleEventInterceptor onFault behaviour but in the case of Producer not even exists Consumer try to get WSDL fetch operation and failed with FileNotFoundException.
    To handle this exception, I used IWSDLInterceptor which is available under IWSDLInterceptor.OnWSDLException (Oracle Fusion Middleware Java API for Oracle WebLogic Portal)
    I am able to catch the exception but problem arise when application needs to forward at specific page/render portlet for this situation. For that it required request/response object but IWSDLInterceptor does not give any kind of instances to redirect request as there is no direct access to HTTPServlet request/response object.
    I tried my custom request object to use there. I tried out custom filter object of IWSDLrequestContext. nothing works.
    One approach works is to put producer WSDL file at consumer level. But in that, you need to handle different producer files for different environment. Which I don't think its a good approach.
    eAny one Let me know if my approach to the problem/scenario is wrong. Or if I am missing out any other supporting interface which also required to handle this scenario. or I am using wrong interface for this scenario.
    Thanks for your help in advance.
    PT.

  • Sending attachment in soap response

    Hi,
    I want to send attachment in soap response on pi7.4. I am new to pi and this seems to be tough task ,
    I would be thankfull for help.
    7Z

    Hi,
    Can you please elobarate your scenario? Please refer the below blog for attachment scenario in SAP PI 7.31.
    Handle SOAP with Attachment in SAP PI 7.31
    regards,
    Harish

  • When I send a text the response goes to my husband's iPad.  Why?

    when I send a text the response goes to my husband's iPad.  Why?

    I assume you are sharing one?
    You can share an Apple ID for purchases but you both should have separate Apple ID for iCloud, iMessage, & FaceTime.
    Settings > Messages > Send & Receive > Apple ID: > Sign out as you and in as him

Maybe you are looking for