FileUploadBean

I'm trying to use this bean I found online at
http://www.onjava.com/onjava/2001/04/05/example/listing1.html
It is some really good code, it takes an HTTPRequest and parses it out. It separates form data and then saves file data. The only problem with this code is in the Upload method it uses a PrintWriter. There's a character encoding issue, it causes a lot of red dots when I try to save image files. So I'm trying to convert to a FileOutputStream, but it still needs to be able to parse through the data.
Does anyone have any suggestions here?

You have two possibilities:
1. Change the code.
2. Use something else.
Without knowing what your goal is, it is difficult for me to choose one of those options.

Similar Messages

  • How is it posible to get the File name, size and type from a File out the H

    How is it posible to get the File name, size and type from a File out the HttpServletRequest. I want to upload a File from a client and save it on a server with the client name. I want to conrole before saving the name, type and size of the file.How is it posible to get the File name, size and type from a File out the HttpServletRequest.
    form JSP
    <form name="form" method="post" action="procesuploading.jsp" ENCTYPE="multipart/form-data">
    File: <input type="file" name="filename"/
    Path: <input type="text" readonly="" name="path" value="c:"/
    Saveas: <input type="text" name="saveas"/>
    <input name="submit" type="submit" value="Upload" />
    </form>
    proces JSP
    <%@ page language="java" %>
    <%@ page import="java.util.*" %>
    <%@ page import="FileUploadBean" %>
    <jsp:useBean id="TheBean" scope="page" class="FileUploadBean" />
    <%
    TheBean.doUpload(request);
    %>
    BEAN
    import java.io.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletInputStream;
    public class FileUploadBean {
    public void doUpload(HttpServletRequest request) throws IOException
              String melding = "";
              String filename = request.getParameter("saveas");
              String path = request.getParameter("path");
              PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("test.java")));
              ServletInputStream in = request.getInputStream();
              int i = in.read();
              System.out.println("filename:"+filename);
              System.out.println("path:"+path);
              while (i != -1)
                   pw.print((char) i);
                   i = in.read();
              pw.close();
    }

    Thanks it works great.
    Here an excample from my code
    import org.apache.commons.fileupload.*;
    public class FileUploadBean extends Object implements java.io.Serializable{
    String foutmelding = "geen";
    String path;
    String filename;
    public boolean doUpload(HttpServletRequest request) throws IOException
         try
         // Create a new file upload handler
         FileUpload upload = new FileUpload();
         // Set upload parameters
         upload.setSizeMax(100000);
         upload.setSizeThreshold(100000000);
         upload.setRepositoryPath("/");
         // Parse the request
         List items = upload.parseRequest(request);
         // Process the uploaded fields
         Iterator iter = items.iterator();
         while (iter.hasNext())
         FileItem item = (FileItem) iter.next();
              if (item.isFormField())
                   String stringitem = item.getString();
         else
              String filename = "";
                   int temp = item.getName().lastIndexOf("\\");
                   filename = item.getName().substring(temp,item.getName().length());
                   File bestand = new File(path+filename);
                   if(item.getSize() > SizeMax && SizeMax != -1){foutmelding = "bestand is te groot.";return false;}
                   if(bestand.exists()){foutmelding ="bestand bestaat al";return false;}
                   FileOutputStream fOut = new FileOutputStream(bestand);     
                   BufferedOutputStream bOut = new BufferedOutputStream(fOut);
                   int bytesRead =0;
                   byte[] data = item.get();
                   bOut.write(data, 0 , data.length);     
                   bOut.close();
         catch(Exception e)
              System.out.println("er is een foutontstaan bij het opslaan de een bestand "+e);
              foutmelding = "Bestand opsturen is fout gegaan";
         return true;
         }

  • Prob with running jsp Bean

    Hi,
    I am trying to run a bean through a jsp but its giving error at useBean tag of jsp:
    The error is :
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: /Quadratic.jsp(7,0) The value for the useBean class attribute com.brainysoftware.Quadratic is invalid.
         org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
         org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
         org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:150)
         org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1227)
         org.apache.jasper.compiler.Node$UseBean.accept(Node.java:1116)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
         org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2213)
         org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2219)
         org.apache.jasper.compiler.Node$Root.accept(Node.java:456)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
         org.apache.jasper.compiler.Generator.generate(Generator.java:3272)
         org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:244)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:470)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    My jsp is:
    <HTML>
    <HEAD>
    <TITLE> JSP BEAN Quadratic Example </TITLE>
    </HEAD>
    <BODY>
    <%@ page language="java" %>
    <jsp:useBean id="quadratic" scope="session" class="com.brainysoftware.Quadratic" />
    <jsp:setProperty name="quadratic" property="ia" param="a" />
    <jsp:setProperty name="quadratic" property="ib" param="b" />
    <jsp:setProperty name="quadratic" property="ic" param="c" />
    X1= <%= quad.getDx1( ) %>
    X2= <%= quad.getDx2( ) %>
    End of program
    </BODY>
    </HTML>my bean is:
    package com.brainysoftware;
    import java.io.*;
    class Quadratic{
    int ia;
    int ib;
    int ic;
    String dx1;
    String dx2;
    public int getIa( ) {
    return ia;
    public void setIa( int ii) {
    ia=ii;
    public int getIb( ) {
    return ib;
    public void setIb(int ii) {
    ib=ii;
    public int getIc( ) {
    return ic;
    public void setIc(int ii) {
    ic=ii;
    public String getDx1( ) {
    double detA;
    double result;
    detA= ib*ib -4*ia*ic;
    if(detA<0.0)
    return "Real Roots not possible";
    else {
    result= -ib - Math.sqrt(detA/(2 * ia));
    Double Dresult=new Double (result);
    return Dresult.toString( );
    public String getDx2( ) {
    double detA;
    double result;
    detA= ib*ib -4*ia*ic;
    if(detA<0.0)
    return "Real Roots not possible";
    else {
    result= -ib + Math.sqrt(detA/(2 * ia));
    Double Dresult=new Double (result);
    return Dresult.toString( );
    my directory structure is given below:
    C:\tomcat-5.0.28\jakarta-tomcat-5.0.28\webapps\jsp-examples\WEB-INF\classes\com\
    brainysoftware>dir
    Volume in drive C has no label.
    Volume Serial Number is 4C50-9542
    Directory of C:\tomcat-5.0.28\jakarta-tomcat-5.0.28\webapps\jsp-examples\WEB-IN
    F\classes\com\brainysoftware
    05/22/2005 11:15 PM <DIR> .
    05/22/2005 11:15 PM <DIR> ..
    05/22/2005 11:18 PM 134 CalculatorBean.java
    05/23/2005 12:12 AM 216 Counter.java
    05/24/2005 10:48 PM 358 SimpleJavaBean.java
    06/14/2005 11:16 PM 1,205 Calculator.java
    06/14/2005 11:16 PM 1,323 Calculator.class
    06/16/2005 06:44 PM 534 CalculatorBean2.java
    06/17/2005 08:53 AM 703 CalculatorBean2.class
    06/16/2005 07:00 PM 352 CalculatorBean2.html
    06/17/2005 08:51 AM 588 CalculatorBean2.jsp
    06/17/2005 04:29 PM 97 UploadBean.java
    06/17/2005 04:43 PM 527 FileUploadBean.java
    06/17/2005 04:43 PM 834 FileUploadBean.class
    06/18/2005 12:21 PM 863 Quadratic.java
    06/18/2005 12:21 PM 1,093 Quadratic.class
    14 File(s) 8,827 bytes
    2 Dir(s) 8,615,821,312 bytes free
    C:\tomcat-5.0.28\jakarta-tomcat-5.0.28\webapps\jsp-examples\WEB-INF\classes\com\
    brainysoftware>
    The above clearly shows the presence of Bean in the reqd directory but still I am getting an error. Can somebody help me:
    Zulfi.

    class QuadraticThe class is not public. It is only visible to other classes in the same package as itself, so the servlet (JSP) trying to instantiate and reference it can't see it.
    Make it public.

  • Upload file - filter problem

    Hi all,
    I have a problem with upload file using JSF RI 1.1 + tomahawk.
    I think that the problem is in the web.inf filter definition because I get these warns:
    17:11:51,875 WARN Digester:127 - [ConverterRule]{faces-config/converter} Merge(null,java.math.BigDecimal)
    17:11:51,890 WARN Digester:127 - [ConverterRule]{faces-config/converter} Merge(null,java.math.BigInteger)
    17:11:52,578 WARN ExtensionsFilter:34 - Please adjust your web.xml to use org.apache.myfaces.webapp.filter.ExtensionsFilter
    And also this error when I click in a button to go to the upload page:
    16:47:47,250 WARN ReducedHTMLParser:468 - Invalid HTML; bare lessthan sign found at line 127
    When I click in the button to go to the upload pages the first time i get this error ad with the second click I get the right page.
    It seems like he go to the filter the first time and then to the faces servlet the second, it is possible?
    this is the code of the web.xml:
    <filter>
            <filter-name>MyFacesExtensionsFilter</filter-name>
            <filter-class>
                org.apache.myfaces.component.html.util.ExtensionsFilter
            </filter-class>
            <init-param>
                <param-name>uploadMaxFileSize</param-name>
                <param-value>10m</param-value>
            </init-param>
            <init-param>
                <param-name>uploadThresholdSize</param-name>
                <param-value>100k</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>MyFacesExtensionsFilter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>
        And this is the code of the page with upload:
    <h:form id="upload" enctype="multipart/form-data" >
                    <h:outputText value="Gimme an image: "/>
                    <t:inputFileUpload id="fileupload"
                    value="#{fileUploadBean.myFile}"
                    storage="file"
                    required="true"/>
                    <h:commandButton value="load it up" action="#{fileUploadBean.upload}" />
                </h:form>Anyone can help?
    Thanx very much!
    Message was edited by:
    -Frizzi-

    I don't have org.apache.myfaces.webapp.filter.ExtensionsFilter in my libraries, I only have org.apache.myfaces.component.html.util.ExtensionsFilter. I also tried to change it, but it still don't work...
    I tried to redo all the process, and now I can't even access the action method in my backing bean....
    I repost the the file that I use:
    This is the error that I get when I try to use the action method:
    16:24:11,203  WARN ReducedHTMLParser:468 - Invalid HTML; bare lessthan sign found at line 135
    16:24:11,203  WARN ReducedHTMLParser:468 - Invalid HTML; bare lessthan sign found at line 180 web.inf snippet:
    <filter>
            <filter-name>extensionsFilter</filter-name>
            <filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
            <init-param>
                <param-name>uploadMaxFileSize</param-name>
                <param-value>100m</param-value>
                <description>Set the size limit for uploaded files.
                    Format: 10 - 10 bytes
                            10k - 10 KB
                            10m - 10 MB
                            1g - 1 GB
                </description>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>extensionsFilter</filter-name>
            <url-pattern>*.shtml</url-pattern>
        </filter-mapping>
        <filter-mapping>
            <filter-name>extensionsFilter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>JSF page:
    <h:form id="upload" enctype="multipart/form-data" >
                    <h:outputText value="Gimme an image: "/>
                    <t:inputFileUpload id="fileupload"
                    value="#{fileUploadBean.myFile}"
                    storage="file"
                    required="true"/>
                    <h:commandButton value="load it up" action="#{fileUploadBean.upload}" />
                </h:form>BackingBean:
    public class FileUploadBean {
        private UploadedFile myFile;
        private static Logger log =Logger.getLogger(FileUploadBean.class);
       public String upload() {
            log.info("FileUploadBean.upload");
            try {
            log.info("fileupload_isfile?"+ getMyFile().getBytes());
            log.info("fileupload_path"+ getMyFile().getSize());
            log.info("fileupload_name" + getMyFile().getName());
            System.out.println("myFilename" +getMyFile().getName());
            catch (Exception e){
                log.info("Errore nell'upload");
            return "ok";
        }Please help... I don't know how to solve it. Coul anyone post me a simple WORKING example?
    Thanx a lot!!

  • Problem with PAI (Process After Input) in JSPDynpage

    Hi All,
    I am implementing a file upload functionality through JSPDynpage. When I browse the excel file and try to upload it, it gives this error :
    com.sapportals.htmlb.page.PageException: Eventhandler- "upload_file" or "onUpload_file" not found!
         at com.sapportals.htmlb.page.DynPage.doProcessCurrentEvent(DynPage.java:168)
         at com.sapportals.htmlb.page.PageProcessor.handleRequest(PageProcessor.java:115)
         at com.sapportals.portal.htmlb.page.PageProcessorComponent.doContent(PageProcessorComponent.java:134)
    This is my component :
    public class FileUploadUtility extends PageProcessorComponent {
      public DynPage getPage(){
        return new FileUploadUtilityDynPage();
      public static class FileUploadUtilityDynPage extends JSPDynPage{
        private fileUpload fileUploadBean = null;
         protected IPortalComponentRequest request;
         protected IPortalComponentResponse response;
         protected IPortalComponentSession session;
         protected IPortalComponentContext context;
         protected IPortalComponentProfile profile;
         protected String userId;
         private final static int INITIAL_STATE = 0;   
         private final static int OUTPUT_STATE = 1;
         private final static int ERROR_STATE = 2; 
         private int state = INITIAL_STATE;
        public void doInitialization(){
              request = (IPortalComponentRequest) this.getRequest();
              session = ((IPortalComponentRequest)getRequest()).getComponentSession();
              context = request.getComponentContext();
              profile = context.getProfile();
              IUserContext userContext = request.getUser();
              userId = userContext.getUserId();
              System.err.println("berry + Getting userID " + userId);               
              fileUploadBean = new fileUpload();
              session.putValue("fileUploadBean", fileUploadBean);
              //uploadUtility();
        public void uploadUtility(){
              String mimetype;
              String resourceName;
              String repository;
              FileInputStream sourceFileInput = null;
              IPortalComponentRequest request = (IPortalComponentRequest)this.getRequest();
         /*     IWDClientUser wdUser = WDClientUser.getCurrentUser();
              IUser user = wdUser.wdUser.getSAPUser(); */
              IUser epUser=(IUser)request.getUser().getUser();
              System.err.println("epUser - " + epUser);
              ResourceContext ctx = new ResourceContext(epUser);
              repository = "/Folder1/Folder2";
              RID rid=RID.getRID(repository);
              System.err.println("getting RID :- " + rid);
              IPageContext context = PageContextFactory.createPageContext(request,response);
         //     PageContext context = PageContextFactory.createPageContext(request, response);
              Event event=context.getCurrentEvent();
              if(null!=event)
                   String event_name=event.getAction();
                   if(null!=event_name && event_name.trim().equalsIgnoreCase("upload_file"))
                        //FileUpload fileUpload = (FileUpload)context.getComponentForId("fileupload");
                        FileUpload fileUpload = (FileUpload)context.getComponentForId("fileupload");
                             if(null !=fileUpload && null!=fileUpload.getFile())
                                       mimetype = fileUpload.getFile().getContentType();
                                       resourceName = fileUpload.getFile().getFileName();
                                       //sourceFileInput = new FileInputStream(fileUpload.getFile().getFile().getAbsolutePath());
                                       try {
                                            sourceFileInput = new FileInputStream(fileUpload.getFile().getFile().getAbsolutePath());
                                       } catch (FileNotFoundException fnf) {
                                            System.err.print("FileNotFoundException Occured " + fnf.toString());
                                       Content content = new Content(sourceFileInput, mimetype, -1L);
                                       //IResource resource = (ResourceFactory.getInstance().getResource(rid, ctx));
                                       IResource resource = null;
                                       try {
                                            resource =(IResource) (ResourceFactory.getInstance().getResource(rid, ctx));
                                       } catch (ResourceException resexp) {
                                            System.err.print("Resource Exception Occured for IResource" + resexp.toString());                          }
                                       ICollection aCollection=(ICollection)resource;
                                       //IResource newResource = aCollection.createResource(resourceName, null, content);
                                       try {
                                            IResource newResource = (IResource) aCollection.createResource(resourceName, null, content);
                                       } catch (NotSupportedException e2) {
                                            System.err.print("Not Supported Exception Occured" + e2.toString());
                                       } catch (AccessDeniedException e2) {
                                            System.err.print("Access Denied Exception Occured" + e2.toString());
                                       } catch (ResourceException e2) {
                                            System.err.print("Resource Exception Occured for ICollection" + e2.toString());      
                                       }//end of catch
                        }//end of innermost if
              }//end of 2nd if
         }//end of 1st If
    }// end of uploadUtil
        public void doProcessAfterInput() throws PageException {
              uploadUtility();
        public void doProcessBeforeOutput() throws PageException {
          this.setJspName("File_Upload.jsp");
    Kindly help with expert suggestions :

    I put this
    public void onUpload_file (Event event) {
              uploadUtility();
    In my FileUploadUtilityDynPage.java and its still throwing the same error.
    {0}#1#com.sapportals.htmlb.page.PageException: Eventhandler- "upload_file" or "onUpload_file" not found!
         at com.sapportals.htmlb.page.DynPage.doProcessCurrentEvent(DynPage.java:168)
         at com.sapportals.htmlb.page.PageProcessor.handleRequest(PageProcessor.java:115)
         at com.sapportals.portal.htmlb.page.PageProcessorComponent.doContent(PageProcessorComponent.java:134)
    I've also imported import com.sapportals.htmlb.event.*;
    No relief!!

  • Null Pointer Exception in "Documents" page after creating a Coll. room

    Hi,
      I am new to KMC. we are on EP7 SP5.
      I have created a collaboration room template.. and created a ROOM (say CommunityRoom) via this Room template...
      I have referred the following document:
    <a href="http://sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/documents/a1-8-4/Collaboration%20with%20SAP%20NetWeaver%20Learn%20How%20to%20Create%20New%20Collaboration%20Room%20Templates%20Exercise">How to create a collaboration room template</a>
    (Probably as this document was on EP6.. i didn't have all the properties and their parameters ..exactly as said in this document)
      I have added the following pages in the Room template:
    [code]  --> com.sap.netweaver.coll.RoomDiscussionsPage
      --> com.sap.netweaver.coll.RoomDocumentsPage
      --> RoomMaintenance
      --> Test page (my custom page.. )[/code]
      After i enter into the room..i am able to see the discussions, room maintenance & test page .. pages...but, I am getting the following error in the 'Documents' page:
    [code]     java.lang.NullPointerException
         at com.sap.ip.collaboration.core.impl.properties.resolver.ConfigFWKPropertyResolver.wrapConfigurable(ConfigFWKPropertyResolver.java:313)
         at com.sap.ip.collaboration.core.impl.properties.resolver.ConfigFWKPropertyResolver.wrapValue(ConfigFWKPropertyResolver.java:331)
         at com.sap.ip.collaboration.core.impl.properties.resolver.ConfigFWKPropertyResolver.wrapConfigurable(ConfigFWKPropertyResolver.java:320)
         at com.sap.ip.collaboration.core.impl.properties.resolver.ConfigFWKPropertyResolver.getWrappedConfigurable(ConfigFWKPropertyResolver.java:287)
         at com.sap.ip.collaboration.core.impl.properties.resolver.ConfigFWKPropertyResolver.resolveProperty(ConfigFWKPropertyResolver.java:86)
         at com.sap.ip.collaboration.core.impl.properties.PropertyRegistry.getPropertyFromConfigFWK(PropertyRegistry.java:115)
         at com.sap.ip.collaboration.core.impl.properties.PropertyRegistry.getProperty(PropertyRegistry.java:89)
         at com.sap.ip.collaboration.core.impl.properties.portal.PropertyRegistryService.getProperty(PropertyRegistryService.java:50)
         at com.sap.netweaver.coll.coreui.api.registry.PropertyRegistryReader.getContextMenus(PropertyRegistryReader.java:83)
         at com.sap.netweaver.coll.coreui.api.generic.GenericUIBOGroupCommand.getResourceCommands(GenericUIBOGroupCommand.java:125)
         at com.sapportals.wcm.rendering.uicommand.UIGroupCommand.getResourceGroupCommands(UIGroupCommand.java:131)
         at com.sapportals.wcm.rendering.uicommand.UIGroupCommand.getResourceCommands(UIGroupCommand.java:101)
         at com.sapportals.wcm.rendering.uicommand.UIGroupCommand.getListWithReplaceCommands(UIGroupCommand.java:191)
         at com.sapportals.wcm.rendering.uicommand.UIMenuFactory.getRenderMenu(UIMenuFactory.java:217)
         at com.sapportals.wcm.rendering.readymades.UICommandComponent.buildContentWithFactory(UICommandComponent.java:156)
         at com.sapportals.wcm.rendering.readymades.UICommandComponent.buildContent(UICommandComponent.java:140)
         at com.sapportals.wcm.control.util.components.base.BaseCompositeComponent.buildComposition(BaseCompositeComponent.java:190)
         at com.sapportals.htmlb.AbstractCompositeComponent.preRender(AbstractCompositeComponent.java:33)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.AbstractCompositeComponent.preRender(AbstractCompositeComponent.java:34)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.AbstractCompositeComponent.preRender(AbstractCompositeComponent.java:34)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.Container.preRender(Container.java:118)
         at com.sapportals.htmlb.rendering.PageContext.render(PageContext.java:944)
         at com.sapportals.htmlb.page.DynPage.doOutput(DynPage.java:237)
         at com.sapportals.htmlb.page.PageProcessor.handleRequest(PageProcessor.java:129)
         at com.sapportals.htmlb.page.PageProcessorServlet.handleRequest(PageProcessorServlet.java:62)
         at com.sapportals.htmlb.page.PageProcessorServlet.doGet(PageProcessorServlet.java:29)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sapportals.wcm.app.servlet.WcmHtmlbBaseServlet.service(WcmHtmlbBaseServlet.java:104)
         at com.sapportals.wcm.portal.proxy.PCProxyServlet.service(PCProxyServlet.java:332)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sapportals.portal.prt.core.broker.ServletComponentItem$ServletWrapperComponent.doContent(ServletComponentItem.java:110)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.serviceDeprecated(AbstractPortalComponent.java:209)
         at com.sapportals.portal.prt.component.AbstractPortalComponent.service(AbstractPortalComponent.java:114)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.component.PortalComponentResponse.include(PortalComponentResponse.java:215)
         at com.sapportals.portal.prt.pom.PortalNode.service(PortalNode.java:646)
         at com.sapportals.portal.prt.core.PortalRequestManager.callPortalComponent(PortalRequestManager.java:328)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:136)
         at com.sapportals.portal.prt.core.PortalRequestManager.dispatchRequest(PortalRequestManager.java:189)
         at com.sapportals.portal.prt.core.PortalRequestManager.runRequestCycle(PortalRequestManager.java:753)
         at com.sapportals.portal.prt.connection.ServletConnection.handleRequest(ServletConnection.java:240)
         at com.sapportals.portal.prt.dispatcher.Dispatcher$doService.run(Dispatcher.java:522)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sapportals.portal.prt.dispatcher.Dispatcher.service(Dispatcher.java:405)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.servlet.InvokerServlet.service(InvokerServlet.java:156)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:390)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:264)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:347)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:325)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:887)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:241)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:95)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:160)[/code]
       I guess, i have made some mistake in the mappings section of the 'Documents' page. I have given the following mappings:
    <b>com.sap.netweaver.coll.RoomDocumentsPage</b> PAGE:
    [code]  1) <i>com.sap.netweaver.coll.RoomInformation</i> iView
         --> com_sap_netweaver_coll_information_roomid = roomid
      2) <i>com.sap.netweaver.coll.RoomDocuments</i> iView
         --> roomId = roomid
         i couldnot map the properties <b>path</b> and <b>startUri</b> = <i>'private_store_cmStore'</i> (as I didn't have the option <i>'private_store_cmStore'</i> in the dropdown on the right hand side)
      3) <i>com.sap.netweaver.coll.RoomMemberList</i> iView
         --> path = room_allusersgroup_rid
         --> roomRid = room_rid
         --> startUri = room_allusersgroup_rid[/code]
    What could be the issue?
    Please help me...
    Regards,
    SK.

    Hi Devendra,
    Did you get a chance to see the OA Framework FileUploadBean section in Dev guide. When you create a messageFileUpload bean, you might not require to write custom logic. Please see the dev guide section for details
    Regards
    Sumit

  • File upload with jsp

    I am trying to upload a file to a mysql database (using a jsp tomcat 4.1 container) for each new member of my website (typically a cv which is a .rtf word file). I have used the example on the oreilly page and have managed to get the image of the file I have uploaded. Now I am trying to save this into my database for each member so that they can enter all of their details on the one page i.e. name age etc and also a browse for file button which will store the path of their file on their computer. When they click the submit button, all of their details are then stored into the database by the resultant page which outputs wehter they have been successful or not.
    The upload bean code (from the oreilly site):
    package com.idhcitip;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletInputStream;
    import java.util.Dictionary;
    import java.util.Hashtable;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FileUploadBean {
    private String savePath, filepath, filename, contentType;
    private Dictionary fields;
    public String getFilename() {
    return filename;
    public String getFilepath() {
    return filepath;
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    public String getContentType() {
    return contentType;
    public String getFieldValue(String fieldName) {
    if (fields == null || fieldName == null)
    return null;
    return (String) fields.get(fieldName);
    private void setFilename(String s) {
    if (s==null)
    return;
    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
    filepath = s.substring(pos+10, s.length()-1);
    // Windows browsers include the full path on the client
    // But Linux/Unix and Mac browsers only send the filename
    // test if this is from a Windows browser
    pos = filepath.lastIndexOf("\\");
    if (pos != -1)
    filename = filepath.substring(pos + 1);
    else
    filename = filepath;
    private void setContentType(String s) {
    if (s==null)
    return;
    int pos = s.indexOf(": ");
    if (pos != -1)
    contentType = s.substring(pos+2, s.length());
    public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();
    byte[] line = new byte[128];
    int i = in.readLine(line, 0, 128);
    if (i < 3)
    return;
    int boundaryLength = i - 2;
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    fields = new Hashtable();
    while (i != -1) {
    String newLine = new String(line, 0, i);
    if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
    if (newLine.indexOf("filename=\"") != -1) {
    setFilename(new String(line, 0, i-2));
    if (filename==null)
    return;
    //this is the file content
    i = in.readLine(line, 0, 128);
    setContentType(new String(line, 0, i-2));
    i = in.readLine(line, 0, 128);
    // blank line
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    PrintWriter pw = new PrintWriter(new BufferedWriter(new
    FileWriter((savePath==null? "" : savePath) + filename)));
    while (i != -1 && !newLine.startsWith(boundary)) {
    // the problem is the last line of the file content
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    pw.print(newLine.substring(0, newLine.length()-2));
    else
    pw.print(newLine);
    newLine = new String(line, 0, i);
    pw.close();
    else {
    //this is a field
    // get the field name
    int pos = newLine.indexOf("name=\"");
    String fieldName = newLine.substring(pos+6, newLine.length()-3);
    //System.out.println("fieldName:" + fieldName);
    // blank line
    i = in.readLine(line, 0, 128);
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    StringBuffer fieldValue = new StringBuffer(128);
    while (i != -1 && !newLine.startsWith(boundary)) {
    // The last line of the field
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    fieldValue.append(newLine.substring(0, newLine.length()-2));
    else
    fieldValue.append(newLine);
    newLine = new String(line, 0, i);
    //System.out.println("fieldValue:" + fieldValue.toString());
    fields.put(fieldName, fieldValue.toString());
    i = in.readLine(line, 0, 128);
    } // end while
    This works fine and I can access the image name of the file by using the commands in my jsp code(on the resultant page of the new member form):
    <%@ page import="java.sql.*, com.idhcitip.*"%>
    <jsp:useBean id="TheBean" scope="page" class="com.idhcitip.FileUploadBean" />
    <%
    TheBean.doUpload(request);
    out.println("Filename:" + TheBean.getFilename());
    So I am wondering how can I then store this image into a text blob in the database?
    I found some code on the java.sun forum, but am not entirely sure how I am meant to use it?
    package com.idhcitip;
    import java.sql.*;
    import java.io.*;
    class BlobTest {
    public static void main(String args[]) {
    try {
    //File to be created. Original file is duke.gif.
    //DriverManager.registerDriver( new org.gjt.mm.mysql.Driver());
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    String host="localhost";
    String user="root";
    String pass="";
    String db="idhcitip";
    String conn;
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
    pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    /*PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobTest VALUES( ?, ? )" );
    pstmt.setString( 1, "photo1");
    File imageFile = new File("duke.gif");
    InputStream is = new FileInputStream(imageFile);
    pstmt.setBinaryStream( 2, is, (int)(imageFile.length()));
    pstmt.executeUpdate();
    PreparedStatement pstmt = Conn.prepareStatement("SELECT image FROM testblob WHERE Name = ?");
    pstmt.setString(1, args[0]);
    RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
    ResultSet rs = pstmt.executeQuery();
    if(rs.next()) {
    Blob blob = rs.getBlob(1);
    int length = (int)blob.length();
    byte [] _blob = blob.getBytes(1, length);
    raf.write(_blob);
    System.out.println("Completed...");
    } catch(Exception e) {
    System.out.println(e);
    Once I have managed to store the file, I would just like people to be able to view each members profile and then to click on a link that will have their stored c.v.
    Thanks for a reply anyone

    You could do this one of two ways..
    using a prepaired statment, you could read in a byte array...
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBytes(1, byte[]); //Your byte array buffer from your FileUploadBean
    ps.executeUpdate();or you could just use the input stream..
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBinaryStream(1, InputStream, length); //You'll have to do some work to get length
    ps.executeUpdate();

  • Multiple times constructors calling in Myfaces

    Hi
    i m fasing multiple times constructor calling for myfaces programs
    i have created a small web appl. with one text box and one submit button, to test this behaviour.
    i have used this sample to
    get web page
    enter some text value
    submit the page
    and atlast page get returned to me
    i don't understand the multiple times consturctor calling and exact sequence of Getter/Setter calling?
    Following are details -
    faces-config.xml
    <managed-bean>
    <managed-bean-name>fileUploadBean</managed-bean-name>
    <managed-bean-class>com.dbschenker.dts.model.backingbean.FileUpload</managed-bean-class>
    <manged-bean-scope>request</manged-bean-scope>
    </managed-bean>
    jsp file
    <h:inputText id="txtSample" value="#{fileUploadBean.txtName}"/>
    <h:commandButton action="#{fileUploadBean.uploadFile}"
    image="../../images/upload_0.png"
    onmouseover="this.src='../../images/upload_0.png'"
    onmouseout="this.src='../../images/upload_1.png'"
    onclick="return true;"/>
    Backing bean
    public class FileUpload {
    private String txtName;
    public void setTxtName(String txtName) {
    System.out.println("Calling Setter... ");
    this.txtName= txtName;
    public String getTxtName() {
    System.out.println("Calling Getter... ");
    return txtName==null?"":this.txtName;
    public FileUpload() {
    System.out.println("Calling Constructor... ");
    public String uploadFile() {
    System.out.println("Upload Form Submitted... ");
    return "";
    Output to Console
    Calling Constructor...
    Calling Getter...
    Calling Constructor...
    Calling Constructor...
    Calling Getter...
    Calling Constructor...
    Calling Setter...
    Calling Constructor...
    Upload Form Submitted...
    Calling Constructor...
    Calling Getter...

    Hi
    that blog was really good and in depth...
    but i have one real time problem with multiple time constructor calling
    if you replace text box with file upload tag in my earlier sample program and then following is out put ...
    Calling Constructor...
    getUploadedFile()...
    Calling Constructor...
    getUploadedFile()...
    Calling Constructor...
    setUploadedFile()...
    Uploaded File Name - D:\AsnUploadTemplate02.XLS
    Calling Constructor... ------------------(.1
    Upload Form Submitted...
    java.lang.NullPointerException
         at com.dbschenker.dts.model.backingbean.FileUpload.uploadFile(FileUpload.java:40)
    ----------- trailing exception stack trace...
    Calling Constructor...
    getUploadedFile()...
    form this output u can find that my UploadedFile backing bean object gets null just before form submit method...
    whereas its has been properly instantiated in setter method,
    if constructor (1 wasn't call then object (uploadedFile) can be found in method (FileUpload.uploadFile)
    i have also tried to make scope of backing bean Session , but constructor, getter & setter calling sequence doesn't different even after.
    i have also considered both of your blog as ---
    http://balusc.blogspot.com/2006/09/debug-jsf-lifecycle.html
    http://balusc.blogspot.com/2008/02/uploading-files-with-jsf.html
    but my problem stands as it is
    kindly help

  • FileUpload problem

    Hello all,
    I'm using the FileUpload component in a JSPDynPage but it does not seem to work for me. The problem is a lot like the one Patrick O'Neill asked about. I used the HTMLB example but for some strange reason variable fu remains NULL. Please have a look at my code and explain to me what the problem is. The JSP contains a file upload component and a button to start the upload event.
    This is the java code I used (testprogram):
    import com.sapportals.htmlb.enum.ButtonDesign;
    import com.sapportals.htmlb.event.Event;
    import com.sapportals.htmlb.page.DynPage;
    import com.sapportals.htmlb.page.PageException;
    import com.sapportals.portal.htmlb.page.JSPDynPage;
    import com.sapportals.portal.htmlb.page.PageProcessorComponent;
    import com.sapportals.portal.prt.component.IPortalComponentContext;
    import com.sapportals.portal.prt.component.IPortalComponentProfile;
    import com.sapportals.portal.prt.component.IPortalComponentRequest;
    // for htmlb upload
    import java.io.File;
    import com.sapportals.htmlb.rendering.IFileParam;
    import com.sapportals.htmlb.FileUpload;
    // for debugging
    import com.sapportals.portal.prt.runtime.PortalRuntime;
    import com.sapportals.portal.prt.logger.ILogger;
    import com.sapportals.portal.prt.logger.Level;
    import bean.FileUploadBean;
    public class FileUploadExample extends PageProcessorComponent {
        public DynPage getPage() {
            return new RealJSPDynPage();
        public class RealJSPDynPage extends JSPDynPage {
              FileUploadBean myBean;
              private ILogger defaultLogger = PortalRuntime.getLogger();
            public RealJSPDynPage() {
            public void doInitialization() {
                   // Get the request, context and profile from portal platform
                    IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
                    IPortalComponentContext myContext = request.getComponentContext();
                    IPortalComponentProfile myProfile = myContext.getProfile();
                   defaultLogger.setActive(true);
                   defaultLogger.setLevel(Level.ALL);
                    // Initialization of bean
                    FileUploadBean myBean = new FileUploadBean();
                    setBeanFromProfile(myProfile, myBean);
                    // Put the bean into the application context
                    myContext.putValue("myBeanName", myBean);
            public void doProcessAfterInput() throws PageException {
                   // Get the request, context and profile from portal platform
                    IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
                    IPortalComponentContext myContext = request.getComponentContext();
                    IPortalComponentProfile myProfile = myContext.getProfile();
                    // Get the bean from application context
                    myBean = (FileUploadBean) myContext.getValue("myBeanName");
                    setBeanFromProfile(myProfile, myBean);
             public void doProcessBeforeOutput() throws PageException {
                        setJspName("fileupload.jsp");
              public void onClick(Event event) throws PageException {
                   myBean.setText("I was clicked");
                 String ivSelectedFileName;
                   FileUpload fu = (FileUpload) this.getComponentByName("myfileupload");
                   // debug info message, other option is: severe
                   defaultLogger.info(this, "Hello this is a test");
                   if (fu == null) {
                        // error
                        defaultLogger.severe(this, "strange error");
    //       this is the temporary file
                   if (fu != null) {
    //       Output to the console to see size and UI.
                      System.out.println(fu.getSize());
                      System.out.println(fu.getUI());
                      defaultLogger.info(this, String.valueOf(fu.getSize()));
                      defaultLogger.info(this, fu.getUI());
    //       Get file parameters and write it to the console
                      IFileParam fileParam = fu.getFile();
                      System.out.println(fileParam);
    //       Get the temporary file name
                      File f = fileParam.getFile();
                      String fileName = fileParam.getFileName();
                      defaultLogger.info(this, fileName);
    //       Get the selected file name and write ti to the console
                      ivSelectedFileName = fu.getFile().getSelectedFileName();
                      System.out.println("selected filename: "+ivSelectedFileName);
                      defaultLogger.info(this, "selected filename: "+ivSelectedFileName);
              private void setBeanFromProfile(IPortalComponentProfile myProfile, FileUploadBean myBean) {
                        // FileUpload properties
                        myBean.setSize(myProfile.getProperty("size"));
                        myBean.setMaxLength(myProfile.getProperty("maxLength"));
                        myBean.setAccept(myProfile.getProperty("accept"));
                        // Button properties
                        myBean.setDisabled(myProfile.getProperty("disabled"));
                         myBean.setDesign(ButtonDesign.getEnumByString(myProfile.getProperty("design")));
                         myBean.setEncode(myProfile.getProperty("encode"));
                         myBean.setText(myProfile.getProperty("text"));
                         myBean.setTooltip(myProfile.getProperty("tooltip"));
                         myBean.setWidth(myProfile.getProperty("width"));
    This is the JSP:
    <%--- FileUpload.jsp --%>
    <%@ taglib uri= "tagLib" prefix="hbj" %>
    <%--- Get the Bean named myBeanName from the application context --%>
    <jsp:useBean id="myBeanName" scope="application" class="bean.FileUploadBean" />
    <hbj:content id="myContext" >
      <hbj:page title="Template for a portal component">
       <hbj:form id="myFormId" encodingType="multipart/form-data">
         <hbj:fileUpload
                      id="myFileUpload"
                      size="<%=myBeanName.getSize() %>"
                      maxLength="<%=myBeanName.getMaxLength() %>"
                      accept="<%=myBeanName.getAccept()%>">
         </hbj:fileUpload>
         <hbj:button
              id="MyButton"
              text="<%=myBeanName.getText() %>"
              width="<%=myBeanName.getWidth() %>"
              tooltip="<%=myBeanName.getTooltip() %>"
              onClick="click"
              design="<%=myBeanName.getDesign().getStringValue() %>"
              disabled="<%=myBeanName.isDisabled() %>"
              encode="<%=myBeanName.isEncode() %>">
         </hbj:button>
       </hbj:form>
      </hbj:page>
    </hbj:content>
    The Bean:
    package bean;
    import com.sapportals.htmlb.enum.ButtonDesign;
    public class FileUploadBean
         // FileUpload
         public String size;
         public String maxLength;
         public String accept;
         public String getSize() {
              return size;
         public void setSize(String size) {
              this.size = size;
         public String getMaxLength() {
              return maxLength;
         public void setMaxLength(String maxLength) {
              this.maxLength = maxLength;
         public String getAccept() {
              return accept;
         public void setAccept(String accept) {
              this.accept = accept;
         // Button
         public String disabled;
         public ButtonDesign design;
         public String encode;
         public String text;
         public String tooltip;
         public String width;
         // constructor
    //     public ButtonBean() {
         public String isDisabled() {
              return disabled;
         public void setDisabled(String disabled) {
              this.disabled = disabled;
         public ButtonDesign getDesign() {
              return design;
         public void setDesign(ButtonDesign design) {
              this.design = design;
         public String isEncode() {
              return encode;
         public void setEncode(String encode) {
              this.encode = encode;
         public String getText() {
              return text;
         public void setText(String text) {
              this.text = text;
         public String getTooltip() {
              return tooltip;
         public void setTooltip(String tooltip) {
              this.tooltip = tooltip;
         public String getWidth() {
              return width;
         public void setWidth(String width) {
              this.width = width;
    and the Portalapp.xml
    <?xml version="1.0" encoding="utf-8"?>
    <application>
      <application-config>
        <property name="startup" value="true"/>
        <property name="SharingReference" value="htmlb"/>
      </application-config>
      <components>
        <component name="FileUpload">
          <component-config>
            <property name="ClassName" value="FileUploadExample"/>
            <property name="SecurityZone" value="com.sap.portal.pdk/low_safety"/>
          </component-config>
          <component-profile>
            <property name="maxLength" value="125000">
              <property name="personalization" value="dialog"/>
            </property>
            <property name="accept" value="Accept">
              <property name="personalization" value="dialog"/>
            </property>
            <property name="size" value="50">
              <property name="personalization" value="dialog"/>
            </property>
            <property name="width" value="250">
              <property name="personalization" value="dialog"/>
              <property name="type" value="number"/>
            </property>
            <property name="disabled" value="FALSE">
              <property name="personalization" value="dialog"/>
              <property name="type" value="boolean"/>
            </property>
            <property name="encode" value="True">
              <property name="personalization" value="dialog"/>
              <property name="type" value="boolean"/>
            </property>
            <property name="tooltip" value="Initial Tooltip">
              <property name="personalization" value="dialog"/>
            </property>
            <property name="text" value="Initial Button Text">
              <property name="personalization" value="dialog"/>
            </property>
            <property name="tagLib" value="/SERVICE/htmlb/taglib/htmlb.tld"/>
            <property name="design" value="STANDARD">
              <property name="personalization" value="dialog"/>
              <property name="type" value="select[STANDARD,SMALL,EMPHASIZED]"/>
            </property>
          </component-profile>
        </component>
      </components>
      <services/>
    </application>

    Hi Raymond,
    within your JSP, you have given the ID "myFileUpload" whereas within your coding you try to retrieve a component with ID "myfileupload". That's all so far.
    Some additinal hints:
    When referring to another thread, please give the link; in this case, you talked about Problem with FileUpload component
    If you give (non) working examples, please reduce them to an absolute minimum, so that they show what they should show, but nothing more. This does not only hold on SDN but for all bug tracking systems. People get ill from reading 1000 lines of code where 10 would do
    And for formatting on SDN, you can use [ code ] and [/ code ] (without spaces), makes life easier too.
    And don't forget to press the yellow star button on helping answers...
    So far for today
    Hope it helps
    Detlev

  • How to call jsp in javascript

    i am trying to show a confirm dialog and when the user click on the ok button, i want it to call a method inside my .java file. what i want to do is something like this:
    <script>
    var ans = confirm("Are u sure you want to over write file);
    if(ans)
    //call the method doUpload
    else
    //do nothing
    </script>
    /////////////.java///////////////
    public class FileUploadBean{
    public void doUpload(HttpServletRequest req, HttpServletResponse res){

    Something along these lines ought to do what you want:
    <html>
    <body>
    <form name='foobar' action='foobar.jsp'>
    <script language='Javascript'>
    function askim() {
      if (confirm('Is you sure?')) {
        document.foobar.submit();
      } else return false;
    </script>
    <input type='button' value='Submit' onClick='askim()'>
    </form>
    </body>
    </html>
    Your mileage may vary.
    But the idea here is that the Javascript merely submits the form if the user clicks "OK" on the confirmation pop-up. Otherwise, nothing happens. The form is submitted to a JSP file which accepts the request, does something (such as call your Java class), then prints out some HTML in response.

  • Myfaces -tomhawk 1.1.3

    Hi I am using the FileUpload component from tomhawk1.1.3 ..
    I am getting the file browsed and selected but behind the scenes , I am not able to populate the UploadFile instance..
    I am getting a NPE as follows .. anybody pls help.. (its workin for earlier version)
    java.lang.NullPointerException
         at com.actifi.success.web.FileUploadBean.upload(FileUploadBean.java:29)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at com.sun.el.parser.AstValue.invoke(AstValue.java:130)
         at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
         at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
         at com.sun.facelets.el.LegacyMethodBinding.invoke(LegacyMethodBinding.java:69)
         at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:63)
         at javax.faces.component.UICommand.broadcast(UICommand.java:106)
         at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:94)
         at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:168)
         at org.apache.myfaces.lifecycle.LifecycleImpl.invokeApplication(LifecycleImpl.java:343)
         at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:86)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:137)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:144)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:292)
         at org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:108)
         at org.acegisecurity.intercept.web.SecurityEnforcementFilter.doFilter(SecurityEnforcementFilter.java:197)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:143)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:154)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.ui.basicauth.BasicProcessingFilter.doFilter(BasicProcessingFilter.java:214)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:246)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:220)
         at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:303)
         at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:173)
         at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:120)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:174)
         at com.contata.filters.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:34)
         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Unknown Source)

    WEB.XML
    <filter>
              <filter-name>MyFacesExtensionsFilter</filter-name>
              <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
              <init-param>
                   <param-name>maxFileSize</param-name>
                   <param-value>20m</param-value>
              </init-param>
              <init-param>
    <param-name>uploadThresholdSize</param-name>
    <param-value>100k</param-value>
    </init-param>
         </filter>
         <!-- extension mapping for adding <script/>, <link/>, and other resource tags to JSF-pages -->
         <filter-mapping>
    <filter-name>MyFacesExtensionsFilter</filter-name>
    <!-- servlet-name must match the name of your javax.faces.webapp.FacesServlet entry -->
    <servlet-name>Faces Servlet</servlet-name>
         </filter-mapping>
         <!-- extension mapping for serving page-independent resources (javascript, stylesheets, images, etc.) -->
         <filter-mapping>
    <filter-name>MyFacesExtensionsFilter</filter-name>
    <url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
         </filter-mapping>
    UI
    <t:inputFileUpload required="true" id="myFileId" storage="file"
                             value="#{Bean.uploadedFile}" />
    BACKING BEAN
    import org.apache.myfaces.custom.fileupload.UploadedFile;
    private UploadedFile uploadedFile ;
    if(getUploadedFile()!=null){
                   String uploadedFileName = "uploaded/" + getUploadedFile().getName();
                   System.out.println("Inside file upload " + uploadedFileName);
                   }else{
                        System.out.println("Inside file upload , file uploaded is null !" );
    RESULT
    File uplaoded is Null ! :(((

  • Action method not called in Backing Bean

    I am using <x:inputFileUpload> tag inside my jsp page. I am trying to call action method when clicking button, but action method not called.
    My jsp page:
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <%@ taglib uri="http://myfaces.apache.org/extensions" prefix="x"%>
    <html>
         <head>
              <title>File upload Test</title>
         </head>
         <body>
              <f:view>
                   <h:form id="form1" enctype="multipart/form-data">
                        <h:messages id="asdghsda"/>          
                        <h:outputText value="This is file upload page functionlaity POC" />                                   
                        <h:inputText value="#{fileUploadBean.textField}" />
                        <x:inputFileUpload id="myFileId" value="#{fileUploadBean.myFile}" storage="file" required="true"/>                    
                        <h:commandButton action="#{fileUploadBean.storeFile}" value="Enter here" />                    
                        <h:commandLink value="Clicl Here!!" action="#{fileUploadBean.storeFile}"></h:commandLink>
                   </h:form>               
              </f:view>
         </body>     
    </html>
    My backing bean:
    package com.beans;
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import org.apache.log4j.Logger;
    import org.apache.myfaces.custom.fileupload.UploadedFile;
    public class FileUploadBean {     
         private static Logger logger = Logger.getLogger(FileUploadBean.class.getName());
         private String textField;
         private UploadedFile myFile;
         public UploadedFile getMyFile() {
              logger.info("inside get method");
         return myFile;
         public void setMyFile(UploadedFile myFile) {
              logger.info("inside set method");
              this.myFile = myFile;
         public void storeFile(){          
              logger.info("Inside the storeFile method");
              logger.info("The text field value: " + getTextField());
              try {
                   InputStream in = new BufferedInputStream(myFile.getInputStream());
                   logger.info("The string is: " + in.read());
                   System.out.println(in.read());
                   File f = new File("D:\\share\\sample.txt");               
                   OutputStream out = new FileOutputStream(f);
                   out.write(in.read());
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              logger.info("Exit from the storeFile method");
         public String getTextField() {
              return textField;
         public void setTextField(String textField) {
              this.textField = textField;
    My web.xml file:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>MyJSFProject</display-name>
    <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
    </context-param>
    <filter>
    <filter-name>ExtensionsFilter</filter-name>
    <filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
    <init-param>
    <param-name>uploadMaxFileSize</param-name>
    <param-value>10m</param-value>
    </init-param>
    <init-param>
    <param-name>uploadThresholdSize</param-name>
    <param-value>100k</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>ExtensionsFilter</filter-name>
    <servlet-name>FacesServlet</servlet-name>
    </filter-mapping>
    <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    </web-app>
    Can someone help me on this? I need urgently.

    One straight and simple answer which i can give you method associated to action attributes always returns a java.lang.String Object.
    REF :
    action:
    =====
    If specified as a string: Directly specifies an outcome used by the navigation handler to determine the JSF page to load next as a result of activating the button or link If specified as a method binding: The method has this signature: String methodName(); the string represents the outcome
    source : http://horstmann.com/corejsf/jsf-tags.html#Table4_15
    therefore
    change
    public void storeFile(){
    logger.info("Inside the storeFile method");
    logger.info("The text field value: " + getTextField());
    try {
    InputStream in = new BufferedInputStream(myFile.getInputStream());
    logger.info("The string is: " + in.read());
    System.out.println(in.read());
    File f = new File("D:\\share\\sample.txt");
    OutputStream out = new FileOutputStream(f);
    out.write(in.read());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    logger.info("Exit from the storeFile method");
    }to
    public String storeFile(){
    logger.info("Inside the storeFile method");
    logger.info("The text field value: " + getTextField());
    try {
    InputStream in = new BufferedInputStream(myFile.getInputStream());
    logger.info("The string is: " + in.read());
    System.out.println(in.read());
    File f = new File("D:\\share\\sample.txt");
    OutputStream out = new FileOutputStream(f);
    out.write(in.read());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    logger.info("Exit from the storeFile method");
    return "success";
    }else where you can make use of actionlistener property in the following senario.
    but the method signature has to be void storeFile(ActionEvent ae)
    and could be use like
    <h:commandButton actionlistener="#{fileUploadBean.storeFile}" action="success" value="SUBMIT" /> Hope that might help :)
    REGARDS,
    RaHuL

  • Questions about Bluprint app Petstore 2.0

    Sean and whoever can help:
    I am studing petstore 2.0 and have some questions.
    1. Why were both Adress class and AdressBean class used in the petstore application? why cannot we just use Address class?
    2. What is the purpose of FileUploadBean and AutocompleteBean? Can we move the logic to the CatalogFacade?
    Your answer will be very appreciated.
    Shawn

    rjzamora wrote:
    I have read quite a bit of the upgrade documentation that I could find. I have run two test upgrades, one from 10.2.0.3 to 11.2.0.3 and another from 11.2.0.2 to 11.2.0.3. I have also successfully upgraded one database to 11.2.0.3 with no issues or questions.
    Pl post OS details.
    Last night I attempted to upgrade one of my instances from 10.2.0.3 to 11.2.0.3. A number of questions came up:
    1) I got an ORA-3113. When I created an SR it recommended dropping the xdb.migr9202status table. I will be trying that tonight when my maintenance window opens up. The general question that I have is: Should I drop this table, proactively, before each upgrade, or do I need to wait for the upgrade to fail before I drop the table?Pl post the complete error message from the database alert log and the upgrade log files. You should not have to drop this table in general. Have you asked Support why they think this is the solution to the issue ?
    2) When I run the pre-upgrade script, there is a note that the timezone needs to be upgraded and to run the correct DBMS script. There is an option in the upgrade assistant to upgrade the timezone. What is the best practice, to let the script perform the time zone or should I upgrade the timezone manually?You should manually upgrade timezone related settings after the database upgrade. I do not believe DBUA takes care of this. Pl see this MOS Doc
    Actions For DST Updates When Upgrading To Or Applying The 11.2.0.3 Patchset [ID 1358166.1]
    3) There is also a note about configuring the network ACLs for several users. I foulnd a web page:
    http://www.pythian.com/news/3434/setting-up-network-acls-in-oracle-11g-for-dummies/
    Is this the correct way, and should it be performed after the upgrade?
    Yes - this needs to be done as one of the post-upgrade steps.
    http://docs.oracle.com/cd/E11882_01/server.112/e23633/afterup.htm#UPGRD12428
    Thanks in advance for the help, RJZHTH
    Srini

  • Upload/download program

    Hello, Java expert around the world:
    To create a uploading and downloading program, what are the considerations should i make before derive the coding?
    Is it the downloading program is the reverse of uploading program?

    My application just want to upload the file(all kind of format) from client to server, and download file(all kind of format) from server to client.
    I have tried the code below:
    import java.io.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletInputStream;
    public class FileUploadBean {
    public void doUpload(HttpServletRequest request, String f )
    throws IOException {
    PrintWriter pw = new PrintWriter(
    new BufferedWriter(new FileWriter( f )));
    ServletInputStream in = request.getInputStream();
    int i = in.read();
    while (i != -1) {
    pw.print((char) i);
    i = in.read();
    pw.close();
    The code have successful upload the file, but the file size is different after upload to server. How to correct the code above?

  • Help, what's wrong with my upload function

    Hi,
    I want to write a java Bean (FileUploadBean) to upload the image files. I use a very simple txt file to test my Bean code, I've already know the syntax of the entity body of httpServletRequest object, it's like below:
    "-----------------------------7d327203032e
    Content-Disposition: form-data; name="toefl_form"; filename="C:\transfer\Picasso_ljm\jakarta-tomcat-4.0.1\webapps\junmin\image\test.txt"
    Content-Type: text/plain
    hi, this is a test;
    -----------------------------7d327203032e--
    My original test.txt file is only a line without '\r', '\n'.
    "hi, this is a test."
    But after call my upload function, the saved file is:
    hi, this is a test.
    There are 4 more bytes than the original file. Below is my FileUploadBean file, does anyone can figure out what's wrong in my upload function? Does the readLine read the return carriage and new line charactor too? Thank you very much!
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletInputStream;
    import java.util.Dictionary;
    import java.util.Hashtable;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class FileUploadBean {
    private String savePath, saveFilename, filepath, filename, contentType;
    // private Dictionary fields;
    public String getFilename() {
    return filename;
    public String getFilepath() {
    return filepath;
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    public void setSaveFilename(String saveFilename) {
    this.saveFilename = saveFilename;
    public String getContentType() {
    return contentType;
    private void setFilename(String s) {
    if (s==null)
    return;
    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
    filepath = s.substring(pos+10, s.length()-1);
    // Windows browsers include the full path on the client
    // But Linux/Unix and Mac browsers only send the filename
    // test if this is from a Windows browser
    pos = filepath.lastIndexOf("\\");
    if (pos != -1)
    filename = filepath.substring(pos + 1);
    else
    filename = filepath;
    private void setContentType(String s) {
    if (s==null)
    return;
    int pos = s.indexOf(": ");
    if (pos != -1)
    contentType = s.substring(pos+2, s.length());
    public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();
    // read boundary
    byte[] line = new byte[256];
    int i = in.readLine(line, 0, 256);
    if (i < 3)
    return;
    int boundaryLength = i - 2;
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    String newLine = new String(line, 0, i);
    if (newLine.startsWith("Content-Disposition: form-data; name=\""))
    if (newLine.indexOf("filename=\"") != -1) {
    setFilename(new String(line, 0, i-2));
    if (filename==null)
    return;
    //this is the file content
    i = in.readLine(line, 0, 256);
    setContentType(new String(line, 0, i-2));
    // blank line
    i = in.readLine(line, 0, 256);
    // read the first byte of the file
    i = in.read();
    FileOutputStream fo = new FileOutputStream((savePath==null? "" : savePath) + saveFilename);
    while (i != -1) {
    // if this byte is equal to the first byte of the boundary, then first mark this place, and
    // go ahead to check if it encounter the ending boundary. If it belongs to the file, then reset
    // the read position and reread.
    if( (char)i == '\r') {
    in.mark(256);
    i = in.read();
    char c1 = (char)i;
    i = in.read();
    char c2 = (char)i;
    i = in.readLine(line, 0, 256);
    // if it is the end of request body, then close the OutputStream. Since the first byte is
    // read already, then the final boundary size if +3
    if ( (c1 == '\n') && (c2 == '-') && (i==boundaryLength+3) // + 3 is eof
    && (new String(line, 0, i).startsWith(boundary.substring(1)))) {
    i = in.read();
    else {
    // it is not the eof, then write this byte into the outputStream and reset the read position
    fo.write(i);
    in.reset();
    i = in.read();
    } // end if
    // else if (char)i != '-', then write directly to the fileOutputStream
    else {
    fo.write(i);
    i= in.read();
    } // end while
    // close the fileOutputStream
    fo.close();
    }// end function

    HI,
    I find a bug myself. I add a line "i = in.read(line, 0, 256);" in doUpload function in the following position:
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    i = in.read(line, 0, 256);
    String newLine = new String(line, 0, i);
    But still, when I was trying to read a image file, it even didn't finish reading and quit already! Still has bugs, need help!
    Junmin

Maybe you are looking for

  • Excel will not close using activeX

    I have been reading a ton of the responses on the forums regarding this issue and I seem to have everything correct (obviously not since I cant get it to work).  I cant find the reference that is causing excel.exe to remain in memory after I run the

  • Problem in the background

    Hi Friends, i am facing the problem with the funciton module, I have executed my custom program in background (SM37) but the program job  was compled with in few minutes. i have debugged the background job in jdbg and find out the problem in Function

  • Why does it keep telling me I have too many tabs open even if I only have one or 2?

    When I am online, several times a day it will not open a new tab and pop up a screen that tells me I have too many tabs open and gives me the option to let it close them or I can close them. But I may only have 1 tab open, sometimes more than that bu

  • Accessing Field Help from item on different Page

    I manually created a tabular form used for posting and I wanted to implement the field help for the column headers. I have a seperate maintenance form that already has the appropriate help text stored for each item. I want to have my tabular form pop

  • [SOLVED] Dmenu + Xmonad, problem in a new version.

    Hello guys. I recently have problem with the new version of Dmenu on Xmonad. Dmenu version is 4.5 and the code i use is this: keys' :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ()) keys' conf@(XConfig {XMonad.modMask = modMask}) = M.fromList $ --