Instantiating bean in Servlet

Hi All
I have written a bean that fetches data from another java class. My Servlet instantiates that bean and pass that object reference to another Java class, which is multi-threaded. One thread of that class calls another method of another object using that object reference. so, in that way the object reference of that bean (which is created by the servlet) is passed all over the application and fetches data from there to show in the Servlet.
Now my question is, as Servlet is multithreaded by default, it should create an instance of that bean everytime the servlet is accessed (not by calling from that servlet or any other servlets/JSPs)by different users. And by this way every servlet should have their own bean instances. In my case, when I am running that servlet in my localhost it works fine but at the same time when I try to invoke that servlet again from another browser it passes the bean object reference as null. I dont really understand that. Currently I am creating the bean instance in the class definition. I tried to create the instance in init() method but the problem remains same. If my approach is wrong then where should I create the bean instance.
Thanks in advance.
Regards
Anirban

Thanks very much.
I have no service method. I have doGet() and doPost() method. doGet is called just once to create the login screen in every session. doPost handles the form data and it is called several times.
should I create the bean instance in doGet method then? I have to pass that object reference as an object array in that method parameter. where should I initialize that object array and create the instance of the bean and pass the array to another method. I am passing that object reference to another java class method in doget() method.
Cheers!!
Anirban

Similar Messages

  • Strange behavior with entity beans and servlets in a cluster

    We have 2 WebLogic 4.5.1 servers in a cluster with none of the Service
              Packs installed. When a client uses the deployed entity beans or
              servlets they work every other time. The times they do not work nothing
              happens. No exceptions, no responses to the client ( i.e. HTTP 404s ),
              nothing. I suspect something in the cluster setup since we do not have
              these same problems on non-clustered entity beans or servlets. We have
              made sure all the entity beans have the Shared Database flag set on and
              added the delayUpdatesUntilEndOfTx false to the enviroment of the DD.
              That didn't fix the problem. Any ideas?
              Thanks in advance,
              Dallas Dempsey
              DEM - Houston, TX
              

    Do you have log files?
              - Prasad
              Chris Dempsey wrote:
              > We have 2 WebLogic 4.5.1 servers in a cluster with none of the Service
              > Packs installed. When a client uses the deployed entity beans or
              > servlets they work every other time. The times they do not work nothing
              > happens. No exceptions, no responses to the client ( i.e. HTTP 404s ),
              > nothing. I suspect something in the cluster setup since we do not have
              > these same problems on non-clustered entity beans or servlets. We have
              > made sure all the entity beans have the Shared Database flag set on and
              > added the delayUpdatesUntilEndOfTx false to the enviroment of the DD.
              > That didn't fix the problem. Any ideas?
              >
              > Thanks in advance,
              > Dallas Dempsey
              > DEM - Houston, TX
              

  • Using java bean in servlet

    Hi,
    I have a problem in getting the values from simple bean to servlet. The project has one html form. When the user click on the submit button one jsp will be invoked which calls a bean program to validate the user data for required fields. Based on the result, jsp program forward the control to a servlet which stores the data in a database. Otherwise another jsp is called to inform the user to fill in the required data.
    My problem is how to send the data from bean to servlet?
    The snippet of jsp that calls bean is like this :
    <%!
    %>
    <jsp:useBean id="formHandler" class = "subFormBean" scope="request">
    <jsp:setProperty name="formHandler" property="*"/>
    </jsp:useBean>
    <%
    if (formHandler.validate()) {
    %>
    <jsp:forward page="subscriberRegistration"/>
    <%
    } else {
    %>
    <jsp:forward page="retry.jsp"/>
    <%
    %>
    And the snippet of the bean is like this :
    public boolean validate() {
    boolean bool=true;
    if (subname.equals("")) {
    errors.put("subname","Please enter your Name");
    subname="";
    bool=false;
    public subFormBean() {
    subname="";
    public String getSubName() {
    return subname;
    public void setSubName(String sname) {
    subname =sname;
    The servlet which is to receive the data is like this :
    public class subscriberRegistration extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    subFormBean sfb = new subFormBean();
    sfb.setSubName(subname);
    But I'm getiing error while trying to compile the servelet saying that no variables found - sfb, subname etc.
    Please let me know how to invoke the bean from servlet. I want to use servlet to instead of jsp to insert records into database. How can i do this? Please help me. Thanks in advance.

    Hi Tolls,
    Sorry, I'll give a bigger snippet of the prog.code below :
    public class subscriberRegistration extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    subFormBean sfb = new subFormBean();
    sfb.setSubName(subname);
    sfb.setSubAddress(subaddress);
    sfb.setSubCity(subcity);
    sfb.setSubState(substate);
    sfb.setSubCntry(subcntry);
    sfb.setSubPin(subpin);
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection = DriverManager.getConnection(connectionURL,"scott","tiger");
    stmt = connection.createStatement();
    rs = stmt.executeQuery("SELECT subid_seq.NEXTVAL FROM DUAL");
    while(rs.next()) {
    String subno = rs.getString("NEXTVAL");
    PreparedStatement pst = connection.prepareStatement("insert into eps_subscriber(eps_subno, eps_subname, eps_subaddress, eps_subcity, eps_substate, eps_subcntry, eps_subpin, eps_subphno, eps_subemailid, eps_subuserid, eps_subpwd) values(?,?,?,?,?,?,?,?,?,?,?)");
    pst.setString(1,subno);
    pst.setString(2,sfb.subname);
    pst.setString(3,sfb.subaddress);
    pst.setString(4,sfb.subcity);
    pst.setString(5,sfb.substate);
    pst.setString(6,sfb.subcntry);
    pst.setString(7,sfb.subpin);
    I'm validating the form data in beans program. Servlet is used to insert records into the database. So, i'm trying to capture data from the bean. How to capture the data from the bean to servlet? Or should I get it from the form fields directly? The servlet worked well when data was captured directly from html form fields. Please help me to fix this. Thanks in advance.

  • Send data from bean to servlet and get results back to bean

    Hi,
    I'm new to this helpful forum and, as long as I'm practicing with JFS and Java Beans and Servlets, I really need some help about the following crappy issue.
    I made a JSP login page called "LoginPage.jsp" (using "Visual Web JSF Page" tool in NetBeans 6.0), and the action associated to the "Login" button pression is defined in the associated Java Bean "LoginPage.java":
    Code from "LoginPage.jsp":
    <webuijsf:button actionExpression="#{LoginPage.loginButton_action}" binding="#{LoginPage.loginButton}" id="loginButton" primary="true" style="height: 24px; left: 383px; top: 192px; position: absolute; width: 96px" text="Login"/>
    Code from "LoginPage.java":
    public String loginButton_action()
        if (usernameField.equals("guest") && passwordField.equals("guest")) // this control should be done by a servlet, not here!
            return "loginOK"; // this is the outcome for faces-config.xml that will lead to a "Welcome.jsp" page
        else
            return "loginERROR"; // this is the outcome for faces-config.xml that will lead to a "Error.jsp" page
    ...Now, the problem is that the username and password control should not be done by the bean itself, but by a servlet (call it "LoginServlet.java").
    In a few words, what I mean is that once the user writes username and password and presses the "Login" button, the called "loginButton_action()" forwards all the needed data to the servlet "LoginServlet.java", the servlet does the complete checks about login validity then prepares the result (it could be a string reporting "OK" or whatever else) and send it back to the bean "LoginPage.java", so that the flow can continue.
    My problem is that I absolutely don't know how to make a bean and a servlet communicate in both ways and respectively exchange data.
    Thanks in advance for any help, it will really be appreciated.

    Google for passing values in request and session.

  • Access of JSF Beans from Servlet Filter

    Is there any way how can I access session JSF beans from servlet filter?
    I need to check certain value of JSF bean stored in session scope in my filter.
    Thanks
    ferdo

    Frank,
    I am not sure about phase listener, this is the whole situation:
    as I am not using Container Managed Security with my JSF, after I do sucessfull login into application, I need to store some information into the session scope (user etc) and in the servlet filter I need to find out if the user is connected.
    I was trying to put such info into Servlet Session directly in my bean via External Context and reading the info in Filter.
    This is working fine when my application is running locally (jdev oc4j) but once deployed into Application server, when user login first time, user information is somehow removed from the session, and cannot figure out why.
    So I was thinking to try another approach, to find out from servlet filter if JSF bean value is set or not.
    Any other suggestions? Do not want to swicth to Container Manages Security now.
    ferdo
    null

  • Weblogic not finding javax.naming classes when instantiating bean

    Hello,
              I am developing a JSP which contains a JavaBean.
              This bean is a wrapper for a session EJB, the getProperty() methods in
              the bean call methods on the EJB's remote interface.
              I have tested this bean as a stand alone application by adding a
              main(String[] args) method to it and it works.
              However, when adding the bean to the JSP, the JSP does not show in the
              browser, I get a n internal server error 500 instead.
              It seems that Weblogic is not finding the javax.naming.NamingException
              class when instantiating the bean.
              When looking at the weblogic log, I see the following stack trace:
              Fri Aug 18 15:12:06 EDT 2000:<E> <ServletContext-General> Servlet failed
              with Exception
              java.lang.NoClassDefFoundError: javax/naming/NamingException
              at java.lang.ClassLoader.resolveClass0(Native Method)
              at java.lang.ClassLoader.resolveClass(ClassLoader.java:579)
              at
              weblogic.utils.classloaders.GenericClassLoader.reallyLoadClass(GenericClassLoader.java,
              Compiled Code)
              at
              weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java,
              Compiled Code)
              at
              weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java,
              Compiled Code)
              at java.beans.Beans.instantiate(Beans.java:194)
              at java.beans.Beans.instantiate(Beans.java:55)
              at weblogic.servlet.jsp.JspLexer.processBeanTag(JspLexer.java:1138)
              at weblogic.servlet.jsp.JspLexer.mXML_OPEN_USEBEAN(JspLexer.java,
              Compiled Code)
              at weblogic.servlet.jsp.JspLexer.mXML_THING(JspLexer.java:1554)
              at weblogic.servlet.jsp.JspLexer.mTOKEN(JspLexer.java, Compiled Code)
              at weblogic.servlet.jsp.JspLexer.nextToken(JspLexer.java, Compiled
              Code)
              at weblogic.servlet.jsp.JspLexer.parse(JspLexer.java, Compiled Code)
              at weblogic.servlet.jsp.JspParser.doit(JspParser.java, Compiled Code)
              at weblogic.servlet.jsp.JspParser.parse(JspParser.java:116)
              at weblogic.servlet.jsp.Jsp2Java.outputs(Jsp2Java.java:97)
              at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java,
              Compiled Code)
              at weblogic.servlet.jsp.JspStub.compilePage(JspStub.java, Compiled
              Code)
              at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:173)
              at weblogic.servlet.jsp.JspStub.checkForReload(JspStub.java:92)
              at
              weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:191)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:118)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.java:744)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.java:692)
              at
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContextManager.java:251)
              at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:363)
              at
              weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:263)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled Code)
              Any idea on how to fix this?
              Thanks for any help,
              David
              

              yes, weblogicaux.jar is definitely in the weblogic.class.path. i've even tried starting the server from the command line, declaring the classes there. my "trade.xml" document has the URI set as "http://localhost:7001/BizTalkServer". when i enter this on the "BizClient.jsp" form, i get the error discussed below. however, if i enter "http://localhost:7001", even though this is not the explicit location of the BizTalk server, the server returns:
              Thank you! Your trade has been recieved. A BizTalk document has been sent to http://localhost:7001/ with the following information: etc...............
              So there appears to be something wrong with the "/BizTalkServer" setup on my machine. Any ideas?
              Kumar Allamraju <[email protected]> wrote:
              >Make sure weblogicaux.jar is in your weblogic.class.path
              >
              >i.e -Dweblogic.class.path=$WL_HOME/lib/weblogicaux.jar:$WL_HOME/classes etc etc...
              >
              >--
              >Kumar
              >
              >Mike Bachers wrote:
              >
              >> I'm currently struggling with a similar problem, although as a newcomer to WL I'm having some trouble figuring it out. I'm trying to run the BizTalk server example (http://www.weblogic.com/docs51/examples/xml/biztalk/index.html) under Windows 2000 and JDK1.2.2. I'm able to proceed without problems until I submit the form on the "BizClient.jsp" page. At this point, I receive this error:
              >> ------------------------------------------------
              >> There was a problem connecting to the BizTalk server. Exception caught: java.io.FileNotFoundException: Response: '500' for url: 'http://localhost:7001/BizTalkServer'
              >> ------------------------------------------------
              >>
              >> At the same time, the WL console spits this out:
              >> ------------------------------------------------
              >> java.lang.NoClassDefFoundError: javax/naming/NamingException
              >> ....
              >> ------------------------------------------------
              >>
              >> I know this class is in the weblogicaux.jar, and it's included in my classpath. I think David's fix (see below) is getting at my problem, too, but I'm not sure. Anyone relate?
              >>
              >> "David R. Heffelfinger" <[email protected]> wrote:
              >> >Figured it out. The problem was that the beans were in a directory
              >> >in the JAVA_CLASSPATH in weblogic.properties. Moved the directory to
              >> >WEBLOGIC_CLASSPATH and the problem went away.
              >> >
              >> >David
              >> >
              >> >"David R. Heffelfinger" wrote:
              >> >
              >> >> Hello,
              >> >>
              >> >> I am developing a JSP which contains a JavaBean.
              >> >> This bean is a wrapper for a session EJB, the getProperty() methods in
              >> >> the bean call methods on the EJB's remote interface.
              >> >>
              >> >> I have tested this bean as a stand alone application by adding a
              >> >> main(String[] args) method to it and it works.
              >> >>
              >> >> However, when adding the bean to the JSP, the JSP does not show in the
              >> >> browser, I get a n internal server error 500 instead.
              >> >> It seems that Weblogic is not finding the javax.naming.NamingException
              >> >> class when instantiating the bean.
              >> >>
              >> >> When looking at the weblogic log, I see the following stack trace:
              >> >>
              >> >> Fri Aug 18 15:12:06 EDT 2000:<E> <ServletContext-General> Servlet failed
              >> >> with Exception
              >> >>
              >> >> java.lang.NoClassDefFoundError: javax/naming/NamingException
              >> >>
              >> >> at java.lang.ClassLoader.resolveClass0(Native Method)
              >> >>
              >> >> at java.lang.ClassLoader.resolveClass(ClassLoader.java:579)
              >> >>
              >> >> at
              >> >> weblogic.utils.classloaders.GenericClassLoader.reallyLoadClass(GenericClassLoader.java,
              >> >> Compiled Code)
              >> >>
              >> >> at
              >> >> weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java,
              >> >> Compiled Code)
              >> >>
              >> >> at
              >> >> weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java,
              >> >> Compiled Code)
              >> >>
              >> >> at java.beans.Beans.instantiate(Beans.java:194)
              >> >>
              >> >> at java.beans.Beans.instantiate(Beans.java:55)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.processBeanTag(JspLexer.java:1138)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.mXML_OPEN_USEBEAN(JspLexer.java,
              >> >> Compiled Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.mXML_THING(JspLexer.java:1554)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.mTOKEN(JspLexer.java, Compiled Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.nextToken(JspLexer.java, Compiled
              >> >> Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspLexer.parse(JspLexer.java, Compiled Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspParser.doit(JspParser.java, Compiled Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspParser.parse(JspParser.java:116)
              >> >>
              >> >> at weblogic.servlet.jsp.Jsp2Java.outputs(Jsp2Java.java:97)
              >> >>
              >> >> at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java,
              >> >> Compiled Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspStub.compilePage(JspStub.java, Compiled
              >> >> Code)
              >> >>
              >> >> at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:173)
              >> >>
              >> >> at weblogic.servlet.jsp.JspStub.checkForReload(JspStub.java:92)
              >> >>
              >> >> at
              >> >> weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:191)
              >> >>
              >> >> at
              >> >> weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:118)
              >> >>
              >> >> at
              >> >> weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.java:744)
              >> >>
              >> >> at
              >> >> weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImpl.java:692)
              >> >>
              >> >> at
              >> >> weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContextManager.java:251)
              >> >>
              >> >> at
              >> >> weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:363)
              >> >>
              >> >> at
              >> >> weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:263)
              >> >>
              >> >> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java, Compiled Code)
              >> >>
              >> >> Any idea on how to fix this?
              >> >>
              >> >> Thanks for any help,
              >> >> David
              >> >
              >
              

  • How do I lookup an EJB 3.0 Session bean from servlet or JSP?

    Does anyone knows how can I invoke an EJB from a servlet or JSP ?
    I deployed a simple EJB on a Oracle Application Server 10g release 10.1.3 and I'm working with JDeveloper 10.1.3. I deployed the files via JDeveloper, and I didn´t specify any orion-ejb-jar.xml or ejb-jar.xml file
    After deployment, the orion-ejb-jar.xml look like this in the server:
    <?xml version="1.0" encoding="utf-8"?>
    <orion-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/orion-ejb-jar-10_0.xsd" deployment-version="10.1.3.0.0" deployment-time="10b49516c8f" schema-major-version="10" schema-minor-version="0" >
    <enterprise-beans>
    <session-deployment name="HolaMundoEJB" location="HolaMundoEJB" local-location="HolaMundoEJB_HolaMundoEJBLocal" local-wrapper-name="HolaMundoEJBLocal_StatelessSessionBeanWrapper6" remote-wrapper-name="HolaMundoEJB_StatelessSessionBeanWrapper7" persistence-filename="HolaMundoEJB.home_default_group_1">
    </session-deployment>
    </enterprise-beans>
    <assembly-descriptor>
    <default-method-access>
    <security-role-mapping name="<default-ejb-caller-role>" impliesAll="true" />
    </default-method-access>
    </assembly-descriptor>
    </orion-ejb-jar>
    I'm trying to invoke the ejb in a servlet by doing the following:
    public void doGet(HttpServletRequest request, ....
    Context context = new InitialContext();
    HolaMundoEJB helloWorld =
    (HolaMundoEJB)context.lookup("java:com/env/ejb/HolaMundoEJB");
    String respuesta = helloWorld.sayHello("David");
    When i invoke the servlet I catch a NamingException whose message says something
    like this ....java:com/env/ejb/HolaMundoEJB not found in webLlamaEJB
    I tried different paths for the lookup but nothing....
    Can anyone help me with this topic? Thank you.

    Please try the following code:
    HelloEJBBean.java:
    @Stateless(name="Hello")
    @Remote(value={Hello.class})
    public class HelloEJBBean implements Hello {  ... }
    hello.jsp:
    Context ctx = new InitialContext();
    Hello h = (Hello)ctx.lookup("ejb/Hello");
    web.xml:
    <ejb-ref>
    <ejb-ref-name>ejb/Hello</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <remote>fi.kronodoc.test.model.Hello</remote>
    </ejb-ref>
    i think you should also define jndi mappings for the references in orion-ejb-jar.xml and orion-web.xml but for some reason it seems to be working also without these.

  • Calling Stateless Session bean from Servlet

    Dear Friends,
    A help will be Appreciated...
    I created a EJB (Stateless Session Bean) using WebSphere Application Developer with its Business logic in Main bean. Its working perfectly fine using UTC (Standalone Test Client). But when i use a servlet to communicate with this EJB, its giving me error as follows:
    Error Stack:
    java.lang.NoClassDefFoundError: package name/DemoHome
    at java.lang.Class.newInstance0(Native Method)
    at java.lang.Class.newInstance(Class.java:254)
    at java.beans.Beans.instantiate(Beans.java:213)
    at java.beans.Beans.instantiate(Beans.java:57)
    at com.ibm.servlet.engine.webapp.WebAppServletManager.loadServlet(WebAppServletManager.java:148)
    at com.ibm.servlet.engine.webapp.WebAppServletManager.getServletReference(WebAppServletManager.java:287)
    at com.ibm.servlet.engine.webapp.WebApp.getServletReference(WebApp.java:354)
    at com.ibm.servlet.engine.webapp.WebAppRequestDispatcherInfo.calculateInfo(WebAppRequestDispatcherInfo.java:167)
    at com.ibm.servlet.engine.webapp.WebAppRequestDispatcherInfo.<init>(WebAppRequestDispatcherInfo.java:51)
    at com.ibm.servlet.engine.webapp.WebApp.getRequestDispatcher(WebApp.java:1145)
    at com.ibm.servlet.engine.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:179)
    at com.ibm.servlet.engine.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:67)
    at com.ibm.servlet.engine.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:122)
    at com.ibm.servlet.engine.oselistener.OSEListenerDispatcher.service(OSEListener.java:315)
    at com.ibm.servlet.engine.http11.HttpConnection.handleRequest(HttpConnection.java:60)
    at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:323)
    at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:252)
    at com.ibm.ws.util.CachedThread.run(ThreadPool.java:122)
    For more Info let me provide the snipets of how i used the Sevlet:
    Client.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import packagename.*; //package name of imported ear file which is in
    //classpath
    public class Client extends HttpServlet {
    public void doGet(
    javax.servlet.http.HttpServletRequest request,
    javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.ServletException, java.io.IOException {
    PrintWriter out=response.getWriter();
    Properties p = new Properties();
    p.put(javax.naming.Context.PROVIDER_URL, "iiop:///");
    p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
    try {
    InitialContext initial = new InitialContext(p);
    Object objref = initial.lookup("JDemo");
    DemoHome home = (DemoHome)PortableRemoteObject.narrow(objref,DemoHome.class);
    Demo demo = home.create();
    int r=demo.testBean(4);
    out.println("EJB RESULT= "+r);
    } catch (Exception ex) {
    System.err.println("Caught an unexpected exception!");
    ex.printStackTrace();
    Kindly provide ur solution to this problem. Urgent solution will be helpful as its a part of our present project.
    Thanking you for ur esteemed help.
    regards,
    Arun.

    Perhaps you webserver can't see your package jar file.
    Try putting it in WEB-INF\lib directory of your app and restart your server.

  • Accessing  bean in servlet

    hi to all,
    i created a simple bean for login access that has getter and setter method...
    I am trying to access the bean in a servlet .. i got error....
    my bean code is ...
    simple login page
    <form method="post" action="/BeanServlet">
    user Name :
    <input type="input" name="username" >
    Password :
    <input type="password" name="password" >
    <input type="submit" value="submit" >
    </form>
    package use;
    public class UserData {
    String username;
    String password;
    public void setUsername( String value )
    username = value;
    public void setPassword( String value )
    password = value;
    public String getUsername() { return username; }
    public String getPassword() { return password; }
    please fill in the Servlet code is
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    UseData ud = (UserData) session.getAttribute();
    ????? what comes here
    out.println(ud.getPassword(););
    out.println(ud.getUsername());

    sorry kannankalli, but this is what i understood from your question, that you want to take the information of a form from a servlet,,
    and this is the servlet code:
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Servlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    public void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,IOException {
    String retrievedUserName = request.getParameter("userNameField");
    String retrievedPassword = request.getParameter("passwordField");
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Servlet</title></head>");
    out.println("<body>");
    out.println("<p>The userName is: </p>" + retrievedUserName);
    out.println("<p>The password is: </p>" + retrievedPassword);
    out.println("</body></html>");
    out.close();
    notice request.getParameter("userNameField"); the userNameField is the same name as the textField in the html page, and so the password...
    I hope i reached your point..(^_^);

  • Accessing Managed Session Bean in Servlet Filter

    I wrote a Servlet Filter to handle user authentication. Now I'm trying to access my Managed Session Bean in the filter in order to save the current user. Unfortunately the Session Bean is created after the Filter executes for the first time.
    I'm trying to access the Session Bean in this way:
    (SessionBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sessionBean");
    In this case getExternalContext() is equals null.
    Is there any way to create the Session bean before the filter executes or any other ideas how to handle this?
    I already searched around the internet but couldnt figure out something.
    Thanks guys,
    Paul

    Ok, fixed it like this. Works perfect. JSF finds and uses the handmade Session Bean as well.
    if(request.getSession().getAttribute(BeanNames.SESSION_SCOPE_BEAN) == null) {
         SessionBean sessionBean = new SessionBean();
         request.getSession().setAttribute(BeanNames.SESSION_SCOPE_BEAN, sessionBean);
    }Thanks,
    Paul

  • Managed session bean in servlet filter

    Hi,
    Is there a way to get hold of a managed bean with session scope in a servlet filter? The code below throws an error due to the fact that the faces context is null.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    System.out.println("facesContext: " + facesContext); // shows that facesContext is null
    ApplicationFactory appFactory = ApplicationFactory)FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
    Application app = appFactory.getApplication();
    Object obj = app.createValueBinding("user").getValue(facesContext); //throws the error due to the null parameter
    Object obj2 = app.createValueBinding("user"); //results in a valid ValueBindingHere is the faces-config snippet for the managed bean:
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>biz.libereco.skemo.info.asl.beans.User</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>For the record, I am using JSF 1.0 Final.
    Thank you,
    Marcel

    wynton_0 wrote:
    Yes, there is a way to get hold of a managed bean with session scope in a servlet filter.
    See here:
    [http://wiki.apache.org/myfaces/AccessFacesContextFromServlet]
    and here:
    [how to access faces context and backing beans in a servlet filter|http://www.thoughtsabout.net/blog/archives/000033.html]
    This makes no utter sense. A JSF session scoped managed bean is under the hood just put as a HttpSession attribute with the managed bean name as key. Guess what, you can just access the HttpSession in Filter by ((HttpServletRequest) request).getSession() and then just call getAttribute() on it. If it isn't there yet, then just do a setAttribute() with a new instance.
    After I get User bean in my Servlet filter, I populate value to this bean, for example:
    user.setLanguage(request.getParameter("locale"));
    The User bean is in session scope. The User bean's language attribute suppose to be same in the whole session scope, but later on, I got null. My question is:
    how to keep this value in session scope?The the session was apparently invalidated/renewed or you manually removed the bean or replaced it by null.
    In the future, please don't resurrect old topics, just start a new topic for each independent problem/question.

  • Create session scoped bean in servlet?

    I am working on a log in porgram for a jsp page using servlet.
    I need to create a bean in that servlet after user enter correct username and password, and the bean must have scope of session.
    How do I do this?
    How do I control the scope of variables in a servlet?
    thank you

    come on people! i just answered this 2 minutes ago! search the forums first! or a servlet book.
    servlet...
    Bean bean = new Bean();
    bean.setValue("value");
    request.getSession().setAttribute("bean", bean);
    jsp...
    <jsp:useBean id="bean" class="Bean" scope="session" />
    <%= bean.getValue() %>
    OR
    <%
    Bean bean = (Bean)session.getAttribute("bean");
    %>

  • Using Beans in Servlets

    Im using a servlet that accesses a java bean within a session in order to display all the contents within the bean. The code is shown below:
    HttpSession session = request.getSession();
    ItemBean bean = new ItemBean();
    bean.setProductID(results.getString("ProductID")); bean.setProductDescription(results.getString("ProductDescription")); bean.setProductName(results.getString("ProductName")); bean.setProductPrice(results.getString("ProductPrice"));
    bean.setQuantity(Quantity);
    ItemBeans item = (ItemBeans)session.getAttribute("basket");
    item.addItemBean(bean);
    I use a jsp page that uses this bean to display the items. Once all the items have been displayed on the page, the user clicks on a button and this calls another servlet which should take all the items in the bean and store them in a database. Does anyone know how to do this?
    Thanks.

    How do I actually store the information in the bean
    to my database?
    For example, the bean holds details of product name,
    description, price etc. How do I get all these
    details and store them on the database?
    All my other servlets simply retrieve one pair of
    information using request.getParameter(); and then
    run a query which adds this parameter to the
    database. But how do I do it for a bean?Very similar. Instead of using request.getParameter, you get the session. You get the bean from the session. You get<properyName>() from the bean. You run the query.

  • JSP, Bean, or Servlet?

    I've found that alot of the time, the systems I'm trying to design can use all of these to accomplish the same task. What's a good indicator of whether or not I should be using one technology over another?
    For example, most recently, I designed an html form that is used to create registration html forms for clients. I can send the data in my form to another jsp page, a servlet, or a bean. ALL THREE can accept the date and use BufferedWriter to create and write to the registration form. Why would I want to use one over the other?
    Any help here would be greatly appreciated. I am seriously lacking in proper system design knowledge.

    If you want to use the data all through the user session, posting data to a JSP or a Servlet may require either URL rewriting or using hidden elements to preserve the state.
    Its a better idea to store the data in a ValueObject (a simple java bean with get and set for all the properties).
    You may want to refer to J2EE Patterns to find out more about the patterns you can use to design good server side application.

  • How to return Collection from from entity bean to servlet?

    hi
    is it possible to return Collection from entity bean (Which is returns form CMR field ) to servlet ?
    thanks

    SERVLET
    public class test extends HttpServlet {
       @EJB
       private LocalBean lookupBean;
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
      for(Item i : lookupBean.getMyCollection() )
              out.println(i.getItemName());
            out.close();
    }BEAN INTERFACE
    public interface BeanLocal {
        Collection<Item> getMyCollection();  
    }BEAN IMPLEMENTATION
    @Stateless()
    public class Bean implements BeanLocal {
        @PersistenceContext()  
        private EntityManager em;      
         public Collection<Item> getMyCollection() {
            return em.createQuery("SELECT i from ITEM i").getResultList();
        }    and if you create an instance of your servlet you'll have to reinitialize LocalBean
    @EJB(name="myejbref", beanInterface=BeanLocal.class)
    private BeanLocal lookupBean;
    private BeanLocal getLookupBean() {
    if(lookupBean == null) {
    try {
    InitialContext ic = new InitialContext();
    lookupBean = (BeanLocal) ic.lookup("java:comp/env/myejbref");
    catch(Exception e){
    System.out.println(e.getMessage());
    return lookupBean;
    }

Maybe you are looking for