Instantiate a bean from within a Servlet

I am attempting to instantiate a bean from within a Servlet. Basically, I would like to set my bean properties from within a central controlling servlet, then call a worker class to take care of my database insert. The worker class would get its values from the bean.
Does this sound reasonable? I'm sure this is quite possible and very easy to pull off, however I can't seem to find a single example. An example would be greatly appreciated.

Hi,
I have read what you have done.
Now in the servlet add something like
HttpSession ses=request.getSession(true);</stro
ses.addAttribute("user","your Bean name");*
in the JSP get this atribute by
session.getAttribute("user");+
Anyway, how have you configured your server? I am using a Bean Class and trying to instantiate in a sevlet. An exception is occuring.
import mypack.User; //it is nicely imported*
//in the doPOST() method
User user=new User();+ //trying to instantiate
it is giving an Exception. Kindly help.

Similar Messages

  • Executing a Perl Script from within a Servlet

    I'm trying to call a script from within a servlet.This is the code i'm using:
    Process process = Runtime.getRuntime().exec(new String[]{"sh","-c",script,nick,pass});
    InputStream input = process.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;
    while ((i=input.read())!=-1) {
    baos.write(i);
    System.out.println(baos.toString());
    I can`t make it work.This is the output i'm getting.
    java.io.IOException: CreateProcess: sh -c /home/script.sh user pass error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:477)
    at java.lang.Runtime.exec(Runtime.java:443)
    at controllers.EmailAcountCreate.doPost(EmailAcountCreate.java:34)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    Thanks in advance.

    I am facing the same problem. Could you please post the answer if you have one now. Please treat this as very urgent.

  • Obtain parent directory of WEB-INF from within a servlet

    hi to everyone!
    i have got a directory containing a WEB-INF directory (with web.xml and all the other stuff necessary). Hoy is it possible to obtain the parent directory of WEB-INF directory FROM WITHIN A SERVLET, put in lib directory?
    let's say:
    A----WEB-INF---classes
    ---lib----MyServlet.jar
    ---tlds
    ---dtds
    How can I get A from within MyServlet.jar? Please help. Thank's a lot...
    Wendigo

    getServletContext().getRealPath("WEB-INF")

  • Opening an https connection from within a Servlet.

    I am having problems trying to establish an HTTPS connection to a servlet from within a different servlet.
    I get the java.net.MalformedURLException: unknown protocol: https. SSL is setup for the web server. Direct connections from the browser to a servlet work fine with SSL, but a connection from one servlet to another servlet fails. I'm stumped. Is there a separate SSL install/configuration required for the servlet engine? Could anyone explain?

    When you set up SSL enabled web server, you should be getting a trust cert file that knows the hand shake protocol to talk to that server. Once you have that file, you can load that file from that servlet using System.load and then you would be able to talk to anything that runs on that SSL enabled Web server.
    Also you must have JSSE jar files installed in your system .
    Check out this url:
    http://java.sun.com/products/jsse/INSTALL.html
    Let me know if you still have problems

  • How to use the same bean from Jsp and Servlet

    I want to use the same bean instance from both the servlet and jsp.
    for eg. if a create a bean using the jsp:useBean in servlet and if a modify some values, that values should be reflected while i access the same bean from the servlet. But instead of that the servlet is creating a new instance of the bean.
    is it possible?
    Thanks in advance

    Hi,
    When you call jsp:useBean you inform a scope (session, request, page...)
    This means the bean instance will be stored in that scope.
    So, if the informed scope is session, then, in the servlet you could get the bean instance back from the session, this way:
    HttpSession session = request.getSession();
    Bean b = (Bean) session.getAttribute("bean_id");
    Regards,
    Filipe Fedalto

  • Can I use SimpleFdkCredential() from within a servlet?

    I have a test program that logs in to content DB using SimpleFdkCredential, and works perfectly well run from the main() method of a Java class from within JDeveloper. When I try to login the same way from within the doGet() method of a servlet, doGet() hangs on the call to ManagersFactory.login() using the same SimpleFdkCredential that works in-process. The login() call doesn't throw any exceptions, it just sits there waiting[I presume], and never returns.
    Is it necessary to use S2SFdkCredential for any authentication that originates from a servlet invocation? It seems that SimpleFdkCredential should work in this instance as well.
    Thanks.

    Can you check the Content DB http node log (application.log) with debug log level set, to see if the request from the servlet for the RemoteLoginManager Web Service was received?
    I would also check that all libraries are present/accessible from servlet - and that there are no conflicts with existing libraries.
    Also, check the servlet log for anything strange.
    Finally, you could try remote debugging of your servlet .. e.g -Xdebug java option.
    -Matt.

  • URLConnection returns NULL when called from within a weblogic servlet

    The following code snippet works when executed outside of weblogic, but does
    not work from within a weblogic servlet instance.
    URL u = new URL("http://" + ipString + newString.toString());
    URLConnection uc = u.openConnection();
    BufferedReader in = new BufferedReader (new InputStreamReader(uc.getInputStream()));
    String response = "", response2 = "";
    while(response2 != null)
         response = ((response2 = in.readLine()) == null) ? response : response + response2;
    The response is quite big. When this code is executed from within a weblogic servlet instance,
    in.readLine always returns a null right away. Yet a TCP/IP trace shows that the packets are coming
    back to my NT machine.
    Other info:
    Inside of weblogic:
    u's handler is of type weblogic.net.http.Hanlder
    uc is of type weblogic.net.http.HttpURLConnection
    Outside of weblogic:
    u's handler is of type sun.net.www.protocol.http.Handler
    uc is of type sun.new.www.protocol.http.HttpURLConnection
    Weblogic V4.51. Running on NT.
    Attempted the following to no avail:
    1. installing sp11
    2. changing the security to permission java.security.AllPermission;
    3. adding the following calls : uc.setRequestProperty("Content-Type", "text/xml");          
              uc.setDoInput(true);
              uc.setDoOutput(true);
    4. Started playing around with modifying the java.protocol.handler.pkgs system property,
    but I shouldn't have to do this.
    Any help would be appreciated.

    There are some problems with the WL implementations of certain protocols.
    WL hides the Sun implementations when you are in the WebLogic server. Here
    is an a solution that was posted to a similar problem:
    Https is an add-in so to speak. Try this before you create your url:
    System.setProperty ("java.protocol.handler.pkgs",
    "com.sun.net.ssl.internal.www.protocol");
    // add the default security provider (again, in JSSE1.0.1)
    int iap = java.security.Security.addProvider(new
    com.sun.net.ssl.internal.ssl.Provider() );
    dennisNote how the code overides the WL setting which overode the Sun setting.
    Cameron Purdy
    [email protected]
    http://www.tangosol.com
    WebLogic Consulting Available
    "Brian Howell" <[email protected]> wrote in message
    news:[email protected]...
    >
    The following code snippet works when executed outside of weblogic, butdoes
    not work from within a weblogic servlet instance.
    URL u = new URL("http://" + ipString + newString.toString());
    URLConnection uc = u.openConnection();
    BufferedReader in = new BufferedReader (newInputStreamReader(uc.getInputStream()));
    >
    String response = "", response2 = "";
    while(response2 != null)
    response = ((response2 = in.readLine()) == null) ? response : response +response2;
    The response is quite big. When this code is executed from within aweblogic servlet instance,
    in.readLine always returns a null right away. Yet a TCP/IP trace showsthat the packets are coming
    back to my NT machine.
    Other info:
    Inside of weblogic:
    u's handler is of type weblogic.net.http.Hanlder
    uc is of type weblogic.net.http.HttpURLConnection
    Outside of weblogic:
    u's handler is of type sun.net.www.protocol.http.Handler
    uc is of type sun.new.www.protocol.http.HttpURLConnection
    Weblogic V4.51. Running on NT.
    Attempted the following to no avail:
    1. installing sp11
    2. changing the security to permission java.security.AllPermission;
    3. adding the following calls : uc.setRequestProperty("Content-Type","text/xml");
    uc.setDoInput(true);
    uc.setDoOutput(true);
    4. Started playing around with modifying the java.protocol.handler.pkgssystem property,
    but I shouldn't have to do this.
    Any help would be appreciated.

  • Access network path from within servlet

    I'm trying to copy some files from a network path from within a servlet. I realize that I cannot use drive letter mappings as they are profile specific. Instead I'm trying to use the unc path. I'm getting the following error when I read the error inputstream from the process:
    String cmd = "XCOPY \\SERVER\SHARE\File.DAT C:\FOLDER /Y"
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(cmd);
    p.waitFor(); //execute process and wait for it to finish
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream());0 File(s) copied
    Invalid drive specification
    Exit code: 4
    It works from the command line, the problem I'm guessing is that Tomcat runs at as service under the SYSTEM account. What permissions should I put on the shared folder to allow this, or is it a path problem?
    Any help would be appreciated.

    Starting the Tomcat service under the Administrator account fixes the problem, is there any reason I shouldn't use the Administrator account for this?

  • Reading files from within helper classes

    From within a servlet, I can get the servlet context to get a path to the "web" directory of my project and easily access properties files for my project. If I create another package in my project to hold helper classes that perform some specific function and want to create and/or read from a properties file, I get a path to the bin directory of my servlet container:
    Servlet Path: D:\Documents and Settings\Josh\My Documents\Josh\Projects\ServletSandBox\build\web\
    Helper Class File Path: D:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.14\bin\test
    I'd like to develop my helper packages as reusable APIs, so they're not tied directly to my project or to a servlet in general, but I'd like the properties files to stay somewhere in my project folder, preferably in the WEB-INF directory with the servlet's own specific properties file.
    I can't figure out the best way to handle this. I wanted to just be able to pass the helper class a String if somebody wanted to specify a filename other than the default filename. Does it make sense to specify a file URL instead? Is there any other way to get the calling servlet's context path without having to pass in a variable?
    Thanks

    It seems that the helper API shouldn't need to be given a path to its own config file. I would like to have code that will load the file regardless of whether or not its in a stand alone java app or a servlet. Whenever the helper API is jarred up and imported into my servlet, it can't find the config file unless it's in the "D:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.14\bin\test" directory. OR, if I use the current thread to get the loader, it will locate it in the "classes" folder, which is the only solution I can come up with that will let me write code to load the file that will work, regardless of its implementation.
    The "project" folder I'm talking about is just the NetBeans "project" folder for the servlet, or the "ServetSandBox" folder in my example. I guess that doesn't really matter in the context of the servlet though.
    So is using the current thread the appropriate way to do this? When you say that code will work if I put the resource in the WEB-INF directory, that seems to only be true if I try to load it from the servlet itself, not the helper class. The helper class doesn't find the resource in the WEB-INF directory.
    Also, I would like to be able to write the default values to a new config file if one doesn't exist. How in the heck do I get a pointer to the "classes" folder, or any other folder that I can also read from using the classloader, so I can write to a new file?

  • How to get the JNDI name of an EJB from within itself

    Hello,
    I'm trying to find a way to get the JNDI name of a session bean from
    within itself.
    In the application I'm working on we need to support multiple
    customers. In order to do that, each EJB has a normal home and remote
    interface, a base class bean implementation and different children
    bean implemetations for each customer (when the logic for the
    customers is different). JNDI is used to get the proper implementation
    based on the customer.
    I've got an EJB that provides some services that are the same for all
    customers, except for the fact that it contains one variable that
    should have a different value depending on the customer. I don't want
    to creat subclasses just for that. What I want is to be able to get
    the JNDI name and set the variable based on the it.
    Is there a way to get the JNDI name for the EJB from within itself?
    TIA
    MJ

    Hi Pradeep,
    Please try referring to this post which is discussed earliar and seems its also answered.
    http://forums.adobe.com/thread/504861
    Thanks,
    Bhasker Chari

  • Open client socket from within a Web Service

    Hello,
    I need to open a client TCP/IP socket from within a Web Service-type WebLogic
    Workshop app. When I try to read from the socket, the socket read operation hangs.
    When I use the same code in a J2SE Java app on the same machine using Eclipse
    everything works fine. It also works fine from within WebLogic, if I use a "URL"
    object instead of a "Socket" object. (However, I cannot use this type of connection.)
    Can anyone tell me how to work with raw TCP/IP sockets in this situation?

    Hi Udi,
    I have tested my code from within a Servlet and it works fine.
    The Servlet and the Web Service both call the same simple JAVA class. This class wants to access a DB, and therefor, I am using the Data Source.
    When the Servlet calls the class, everything works fine. But when I use the Web Service to call this class, I get the Exception "No attributes are implemented".
    I hope this information helps you understanding my problem?
    Thank you very much for your help.
    Kind regards,
         Nadine

  • WPC: Access Java beans from XSL

    Hi,
    How can we access custom Java beans from within the XSLs used to render WPC webforms? Do we have to implement a custom XSLT Helper? I am able to access standard Java classes using the <xmlns> tag but when I try to reference our custom classes the WPC editor throws a ClassNotFound exception. Any help will be appreciated.
    Thanks and Regards,
    Shibendra

    Hi,
    How can we access custom Java beans from within the XSLs used to render WPC webforms? Do we have to implement a custom XSLT Helper? I am able to access standard Java classes using the <xmlns> tag but when I try to reference our custom classes the WPC editor throws a ClassNotFound exception. Any help will be appreciated.
    Thanks and Regards,
    Shibendra

  • Retrieving Session bean object in a Servlet from FacesContext Object

    Hi,
    I added code in a servlet to retrieve Session bean object from the Faces Context object. I don't know what the problem was, but when I am accessing the application from two different machines and I am trying to retrieve the value from the session object in the servelet it is giving the value what I set into the session bean on one machine browser into another machine browser. Just I want to know the code which I had included in the servlet is correct or not.
    This is the code I am using in my servelt:
    1) To get the Faces context object
    protected FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         if (facesContext == null) {
              //System.out.println("Current context was null...creating one now");
              FacesContextFactory contextFactory =
                   (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
              LifecycleFactory lifecycleFactory =
                   (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
              Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
              facesContext =
                   contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
              //Set using our inner class
              InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
              //set a new viewRoot, otherwise context.getViewRoot returns null
              UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "ContextName");
              facesContext.setViewRoot(view);
         return facesContext;
    2) Code to get the session bean:
    Utils utilsBean = (Utils) getFacesContext(request, response).getApplication().getVariableResolver().resolveVariable (getFacesContext(request, response), "utils");
    Edited by: Ramesh_Pappala on Nov 8, 2007 9:25 AM

    Ramesh_Pappala wrote:
    Hi Raymond,
    Thank you for the reply and can you please send the code No, I cannot do that.
    what you are talking about to get the bean from session through servelet session map so that I can use that one check whether it is working fine in my application or not.
    Thanks.

  • Problem calling servlet from within a jsp

    I have a servlet which obtains images for a page
    http://bychance.ca/servlet/ImageServlet?PhotoId=AJ-LA-4008
    I use the servlet from within a jsp
    <img src="servlet/ImageServlet?PhotoId=<%=rs.getObject("ID")%>" border="0">
    for some reason it does not work, the images are never called. I have another servlet which is called the same way and it works fine
    <img src="servlet/ImageServletLarge?PhotoId=<%=strPhotoId%>" border="0">
    Thank you all for your time

    this is my servlet code. Like I said it works fine in another servlet
    rs.next();
    byte[] bytearray = new byte[rs.getInt(1)];
    int size=0;
    InputStream sImage;
    sImage = rs.getBinaryStream(2);
    response.reset();
    response.setContentType("image/jpeg");
    while((size=sImage.read(bytearray))!= -1 )
    response.getOutputStream().write(bytearray,0,size);
    response.flushBuffer();
    sImage.close();

  • Information from within a Bean?  Auto Increment

    I am currently using 9iAS as my app server and Oracle as my db for a project. In order to get the next PK in a CMP bean I have created the code snippet below. What I was wondering is it possible to get the Initial Context Factory, the Security Principal, the Security Credential, the Provider Url, and the Data Source Name from within the CMP Bean, so I wouldn't have to pass them in or hard code? Maybe through the handle perhaps?
    public static long getNextPK(String initialContextFactory, String securityPrincipal, String _securityCredential,
    String providerUrl, String dataSourceName, String _sequenceName) throws Exception
    long l = 0l;
    Statement st = null;
    Connection con = null;
    Hashtable env = new Hashtable();
    try
    env.put(Context.INITIAL_CONTEXT_FACTORY, _initialContextFactory);
    env.put(Context.SECURITY_PRINCIPAL, _securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, _securityCredential);
    env.put(Context.PROVIDER_URL, _providerUrl);
    Context context = new InitialContext(env);
    DataSource ds = (DataSource)context.lookup(_dataSourceName);
    con = ds.getConnection();
    String query = "SELECT " + _sequenceName + ".NEXTVAL FROM dual";
    st = con.createStatement();
    ResultSet rs = st.executeQuery(query);
    if(rs.next())
    l = rs.getInt(1);
    if(!rs.wasNull())
    //System.out.println("getNextPK() returned "+ l);
    rs.close();
    catch(NamingException ne)
    //ne.printStackTrace();
    log.error("Naming Exception: ", ne );
    catch(SQLException se)
    log.error("SQLException: ", se );
    throw new Exception(se.getMessage());
    finally
    try
    if(st != null)
    st.close();
    if(con != null)
    con.close();
    catch(SQLException sqe)
    //sqe.printStackTrace();
    log.error("SQLException: ", sqe );
    return l;
    }

    For Oracle 9ias the documentation says:
    Defining an Auto-Generated Primary Key
    If you specify a java.lang.Object as the primary key class type in <prim-key-class>, but do not specify the primary key name in <primkey-field>, then the primary key is auto-generated by the container.
    For eg.
    <enterprise-beans>
    <entity>
    <display-name>Employee</display-name>
    <ejb-name>EmployeeBean</ejb-name>
    <local-home>employee.EmployeeLocalHome</local-home>
    <local>employee.EmployeeLocal</local>
    <ejb-class>employee.EmployeeBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>java.lang.Object</prim-key-class>
    <reentrant>False</reentrant>
    <cmp-version>2.x</cmp-version>
    <abstract-schema-name>Employee</abstract-schema-name>
    <cmp-field><field-name>empNo</field-name></cmp-field>
    <cmp-field><field-name>empName</field-name></cmp-field>
    <cmp-field><field-name>salary</field-name></cmp-field>
    </entity>
    </enterprise-beans>
    Once defined, the container creates a column called autoid in the entity bean table for the primary key of type LONG. The container uses random numbers for the primary key values.
    WHAT I DONT LIKE or probably not aware of is the disconnect between the oracle DB generated sequence and the container using random numbers to generated prim keys. If 9ias can auto generate a random number then I feel it should also allow us to specify what sequence from the DB if any, we would like to use... thats my 2cents worth

Maybe you are looking for

  • HT201263 HELP ON THE IPHONE NOT STARTING-UP

    Hi I reset my iphone yesterday and now the screen only shows the apple logo. Moreover, sometimes it show the red battery feature which i dont understand as i will be connecting the iphone to the computer and it all cant help me to charge the iphone.

  • Paid debugging help

    I'm nearing the end of a deadline for a project (tomorrow) that has proven to be too much for me to handle on my own in the time allowed. I'm still new to Flex and I'm not able to debug some of the issues as quickly as I'd like. If anyone can provide

  • My Audio Files will not load??? Help please!!!

    This is my first time to audition and it started with me wanting to do advanced editing from premier pro to audition. However as you can see nothing loads, waveform or playback. This is the first to audition, so its possible im missing something very

  • Sound on Apps

    I can't get the sound to work on the app books.  It has worked for one and not for all the rest. Can't work it out.

  • Fractional Octave Analysis

    My current application reads from six microphones in a reverb room, averages the signals and reports the data as a single source.  In the interest of tonal diagnostics we would like to be able to record data in full and 1/3 octaves at the same time.