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");
%>

Similar Messages

  • Are session-scoped beans singleton

    Hi all, I miss something in the bean lifecycle within JSF. Assume that a page action navigates toward another page, linked to a session-scoped bean: this is created for the duration of this session. Then a button leads back to the original page, so that another action will lead to another page with its associated bean. Is this a new bean or the previous one ?
    This question is linked to the topic of bean dependencies through managed properties: it works fine, but since a bean is declared per class and not per instance, I miss the overall instantiation philosophy.

    Once the bean is created the first time in session, it will not be created again (until the session dies and you attempt to access the bean again of course).
    So in your scenario, the first time you access the page the bean gets created. When you go back and then go forward to the page again, a new bean is not created. The originally created one is re-used. Which means the constructor is not called again.
    CowKing

  • Using Query String Parameters with Session Scoped bean

    I would like to pass query string parameters from a product page (user clicks on a specific product commandLink) that is request scope to a details page that is session scoped.
    The problem is that the session scoped page only handles the first request. If you view the details of a product and then navigate back to the product page and choose another product ... the details page will not handle the new query string parameters and display the details for the first product chosen.
    Is there a way to make the session scoped bean recognize the query string parameters past the first request?

    I was able to replicate this problem with a very simple app that performs a redirection... just like the real app. Here's the simple app that I put together:
    From request scope page:
    <f:view>
             <h:form>
               <h:commandButton value="Link 1" action="#{reqbean.Link1}"/>
               <br/><br/>
              <h:commandButton value="Link 2" action="#{reqbean.Link2}"/>
            </h:form>
           </f:view>
    From request scope bean:
    public String Link1() throws IOException
        // Add event code here...
        //redirect the user
        FacesContext.getCurrentInstance().getExternalContext().redirect("untitled2.jspx?p=1");
        return null;
      public String Link2() throws IOException
        // Add event code here...
        //redirect the user
        FacesContext.getCurrentInstance().getExternalContext().redirect("untitled2.jspx?p=2");
        return null;
      }At this point... I put a println in the constructor of the session scoped bean because this is where I want to get the query string params. The constructor only gets called the first time a redirect is performed.

  • Add FacesMessage to FacesContext in an session scoped bean HOWTO?

    I have an simple question. How can I add an FacesMessage to the FacesContext in a session scoped bean.
    This code works fine for request scoped beans.
    String message = "Some message";          
    FacesMessage curentMessage = new FacesMessage(message, message);
    curentMessage.setSeverity(FacesMessage.SEVERITY_ERROR); //Mark as ERROR
    context.addMessage(�userForm�, curentMessage);          When I change bean scope to "session" I am getting java.lang.IllegalStateException at the last line when adding message to context.
    Thanks:
    -- Nermin

    I have an simple question. How can I add an
    FacesMessage to the FacesContext in a session scoped
    bean.
    This code works fine for request scoped beans.
    String message = "Some message";          
    FacesMessage curentMessage = new FacesMessage(message,
    message);
    curentMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
    //Mark as ERROR
    context.addMessage(�userForm�, curentMessage);          When I change bean scope to "session" I am getting
    java.lang.IllegalStateException at the last line when
    adding message to context.
    Thanks:
    -- NerminHow do you get "context"? If you are storing it as an instance variable of the bean, then you
    should expect to get an exception. The FacesContext is scoped only to one request. Instead
    of storing it in the bean, use FacesContext.getCurrentInstance() each time you need to use it.

  • NullPointerException When trying to Get Session Scoped Bean data in another ManagedBean

    hello
    i wont to access to some data in my session scoped bean from a request bean so when i try to get this data all i get is 
    com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection
    on managed bean «discussionlaoder»
    in the end of the exception there is
    Caused by: java.lang.NullPointerException at Hiber.discussionlaoder.init(discussionlaoder.java:35)
    this is my code:
    1-the request scoped bean
    @ManagedBean
    @RequestScoped
    public class discussionlaoder {
      private MyadmninHelper halper;
    @ManagedProperty(value="#{serviceBean}")
         private ServicesBean  serviceBean;
        @PostConstruct
        public void init() {
          halper=getServiceBean().getHalper();  // line 35
    //seter and geter code
    2-the sesions scoped bean
    @ManagedBean (eager=true)
    @SessionScoped
    public class ServicesBean {
        private MyadmninHelper halper;
    //seter and geter code
    am using glassfish server 3.1
    thank's for help

    What you need to do is fix all those typos in your code, then you don't have to override names.
    - the proper Java class name is DiscussionLoader, not discussionlaoder (fix english typo also)
    - if you want to inject a class named ServicesBean, then also call the property the same.
    @ManagedProperty
    public ServicesBean servicesBean;
    But what you're doing now is call the class 'ServicesBean' and then in your managed bean declaration you seem to change your mind and it should all of a sudden be 'serviceBean'. Well then rename the class so you don't have your typo anymore!

  • Spring framework - Error with session scoped Beans

    Hello guys,
    I'm trying execute my Java Application inside Netweaver Application Server, but I'm having problems with serviceBeans with scope session. Anyone have already used Spring with session scope?
    Thanks,
    Cleiton.

    After many attempt, when I declared the bean with <aop:scoped-proxy  /> it works, however it could cause performance problem. I don't need refer this bean by another singleton bean, i did a wrong configuration in order to make a work a round...
    When I run my application on tomcat server, the DWR starts perfectly the "session scope bean form IOC container", but in the WEBAS maybe it's running in other thread. Is it possible?
    Anyone had a problem like this?
    I got a detailed error with log4j,
    ERROR Application [1] org.directwebremoting.impl.DefaultCreatorManager - Error loading class for creator 'SpringCreator[CounterSpringFacade]'.
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'counterSpringFacade': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
         at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:312)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
         at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881)
         at org.directwebremoting.spring.SpringCreator.getInstance(SpringCreator.java:145)
         at org.directwebremoting.spring.SpringCreator.getType(SpringCreator.java:107)
    Edited by: Cleiton dos Santos Garcia on Jan 7, 2009 5:02 PM

  • Session scoped beans other than SessionBean1

    Let's say I want to provide a logout action. I can end the session by using the below in my logoutButton_action method:
    try {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
    session.invalidate();
    this.getExternalContext().redirect("Page1.jsp");
    } catch (Exception e) {
    log("Logout exception: " + e.getMessage());
    I would not have been able to figure out even that much if it wasn't for this forum. BUT, what about if I have other managed beans (i.e. just plain classes registered in managed-beans.xml) that have session scope, such a class to a hold a logged-in user's details during the session. How do I destroy that when the user logs out?

    {color:#333399}*hi*
    you can set any Object in ur sessionBean1 to be NULL,, by this way , ur session will hold no more data.
    {color}

  • PLZ Help: how to get value of a request scoped Bean/Attribute in JSF ?!!!

    hi,
    I noticed this part of code to retrieve session scoped beans/vars in an ActionListener or other jsf classes, but it does not work for request scoped beans/vars :( what's the problem then ? what shall i do ?
    Type var = (Type)Util.getValueBinding("myBeanInRequest")).getValue(context);
    I have also set that getPhaseId() returns UPDATE_MODEL_VALUES or APPLY_REQUEST_VALUES.
    Any comment or idea ?

    I have declared my Bean in my JSP page not in the
    faces-config.xml. Does this make any problem ? Also I
    have tried the way you told me as well, but still the
    returned attribute is null.
    P.S. My bean is declared in my JSP page this way:
    <jsp:useBean id="newSurveyVar" class="SurveyModel"
    scope="request" />
    This declaration causes the SurveyModel instance to be created in request scope when the page is rendered, but that doesn't help you when the form is submitted -- that is going to happen on the next request (so the request attribute created here goes away). Basically, <jsp:useBean> is not typically going to be useful for request scope attributes (it's ok for session or application scope, though).
    and further I have this jsf code:
    <h:command_button label="Create" commandName="create"
    action="create" >
    <f:action_listener
    r type="CreateNewSurveyActionListener"/>
    </h:command_button>
    and this is my
    CreateNewSurveyActionListener.processAction(ActionEvent
    e) {
    if (actionCommand.equals("create_the_survey")) {
    FacesContext context =
    t = FacesContext.getCurrentInstance();
    SurveyModel survey =
    y =
    (SurveyModel)(Util.getValueBinding("newSurveyVar")).get
    alue(context);
    if (survey==null) // returns true :(((
    And since I've declared my beans here there is nothing
    special declared in my faces-config.xml
    For me again it is really strange why it is not
    working !!!
    Any idea ? Because the event listener is fired in a separate request, so the one you created in the page is gone.
    This is why the managed bean creation facility was created. If your component contains a valueRef that points at the bean name (or you evaluate a ValueBinding as illustrated earlier in the responses to your question), then the bean will get instantiated during the processing of the form submit.
    Craig McClanahan

  • We should NEVER use the session back bean?

    Because the user can open a new window by right click the link, and the session scope back bean is not thread-safe.
    So we should forget it?

    Your concern makes really no sense, or you must be storing request scoped data in a session scoped bean instead of a request scoped bean, which can indeed lead to undesireable behaviour in multiple requests on the same 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

  • 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.

  • ADF BC how to access session backing bean value in servlet

    Hi everyone,
    How do I access session backing bean value in a servlet?

    Frank, thanks for your reply.
    I'm not sure how I can incorporate this example into my situation. Let me explain more detail about my problem.
    "servlet" in my post here actually means a custom servlet I wrote for rendering an image that is stored in db as ordimage. In this servlet, I get hold of my appmodule by using Configuation.createRootApplicationModule(). By doing so (If I'm not wrong) a new database session/connection is created. What I'm going to achieve is set application context for this new session/connection in db with the data stored in a session backing bean in the view layer.
    I can pass the required data to the servlet thru url parameter, but I don't want to do it this way for the reason that the data may contains sensitive information.
    I hope I have explained myself well.
    Message was edited by:
    bsmt

  • Error when Create Session Bean in JDeveloper

    Hi All,
    I followed the steps in the SRDemo tutorial to create Session bean SRPublicFacade. I used Create Session Bean wizard. Step 1 was ok. Step 2 when it's supposed to show all the POJOs and all methods (from Queries) it hang there, and skipped to Step 3 and so on... As a result I had an empty Session Bean with only class name and no methods in it. I do have correct database connection, and I have another project with similar Session Bean sucessfully. I just don't know what happened to this project or the way I created session bean this time. Any conflict when create Session Bean to the same database or something(?) Anyone has any idea please let me know.
    Thank you very much,
    John

    Frank,
    Yes, I compiled the project before building the session facade. I used JDeveloper 10.1.3.3.0
    The thing is I once created successfully the session facade in another project, like SRdemo. Now I would like to repeat that in another project say SRdemo2, then it went wrong. It skipped step 2 in the wizard and look like it cannot detect the tables and named queries.
    Thanks,
    John

  • How to create session in JSP & Servlet

    Hi All
    I'm really new to JSP & Servlet. So I want to know how to create sessions and how to pass details to another web page
    Thanks
    Padma

    You can easily pass objects from one jsp or servlet to another.
    On your servlet execute method (for example), you can do this as follows:
    HttpSession session = request.getSession();
    User u = new User();
    session.setAttribute("user", u);And get it again on other servlets:
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");I hope this helps you.

  • Lose alredy created session bean

    Hi all!
    I have a problem with useBean and session. I use a OrderCartBean and this object contain an
    ArrayList of OrdeBeans. I can add an OrderBean to OrderCartBean ArrayList. But next time I try to add an OrderBean to same OrderCartBean's ArrayList it does not work.
    The problem is that I don't use the same OrderCartBean from session. The jsp-page seems to create a new
    OrderCartBean instead of using the one in session and put the next OrderBean to the new OrderCartBean ArrayList
    I looked around in many pages on the internet but i can't see what i'm doing wrong?
    Thanx in advance...
    Here is my code:
    ode]
    [orderCart.jsp]
    <jsp:useBean id="orderCart" scope="session" class="bean.OrderCart"/>
    <html>
    <body>
    <form method="post" name="order" action="orderCart.jsp">
    <table border=0 cellspacing=2 cellpadding=5 width=400>
    <input name="action" type="hidden" value="addItemToOrder" />
    <tr>
    <td><label>Art.no</label>
    <input type="text" name="artNo"></td>
    <td><label>Name</label>
    <input type="text" name="artName"></td>
    <td><label>Quantity</label>
    <input type="text" name="quantity" size="4"></td>
    </tr>
    <tr>
    <td colspan=2 align=left><input type="submit" value="Add to order" name="AddValue"></td>
    </tr>
    <%
         String action = request.getParameter("action");
         if (action != null && action.equals("addItemToOrder")) {
         //Set values to OrderBean
    %>
    <jsp:useBean id="order" class="com.easy.bean.Order" scope="request" />
    <jsp:setProperty name="order" property="*" />
    <%
         //I got different orderCart every time. Not the same from session?
         System.out.println(orderCart);
         //Add order to OrderCart ArrayList
         orderCart.addOrderToArray(order);
         //Get orders from OrderCart array
         Iterator iter = orderCart.getOrderArr().iterator();
         while(iter.hasNext()){
         com.easy.bean.Order tmpOrder = (com.easy.bean.Order)iter.next();
    %>
    <tr>
    <td><B>Art.no.</B></td>
    <td><B>Name</B></td>
    <td><B>Antal</B></td>
    </tr>
    <tr>
    <td><%=tmpOrder.getArtNo()%></td>
    <td><%=tmpOrder.getArtName()%></td>
    <td><%=tmpOrder.getQuantity()%></td>
    </tr>
    <%}%>
    </table>
    </form>
    </body>
    </html>
    [OrderCart.java]
    package com.easy.bean;
    import java.util.ArrayList;
    public class OrderCart {
    ArrayList<Order> orderArr = new ArrayList<Order>();
    public OrderCart() {}
    public ArrayList<Order> getOrderArr() {return this.orderArr;}
    public void setOrderArr(ArrayList<Order> orderArr) {this.orderArr = orderArr;}
    public void addOrderToArray(Order order) {this.orderArr.add(order);     }
    public void removeOrderFromArray(Order order) {     this.orderArr.remove(order);}
    [Order.java]
    package com.easy.bean;
    public class Order {
    int artNo;
    int quantity;
    String artName;
    public Order() {}
    public String getArtName() {return this.artName;}
    public void setArtName(String artName) {this.artName = artName;}
    public int getArtNo() {     return this.artNo;}
    public void setArtNo(int artNo) {this.artNo = artNo;}
    public int getQuantity() {return this.quantity;}
    public void setQuantity(int quantity) {this.quantity = quantity;}

    So a stateless bean could hold the value of the key throughout its lifetime and each separate method call would have access to it?

Maybe you are looking for

  • Cannot access backup made before last iOS update

    This past Saturday (the 16th) I plugged my iPhone into my computer for it to get the latest update. It showed it was backing up then went on to do the update. It was taking forever so I left to get dinner. Came back and the phone was bricked. No erro

  • Hard disk not detected on Satellite Pro 4270

    I took out the 2"5 hard disk from my SP4270 to transfer data to my PC through a 3"5-2"5 EIDE adapter, the HD was detected by my PC bios and the transfer was successful. Then I reinserted my hard disk into the 2"5 notebook bay, but I get a "Insert sys

  • Unreadable Files: cannot import files error message

    I am trying to import old photos from a previous hard drive and get the following message- Unreadable Files: (# of files) The following files could not be imported (they may be an unrecognized file type or the files may not contain valid data). Then

  • IDXNOALE - table is populated automatically

    Hi every one, I am working on Idoc - XI - Idoc scenario, whenever I send an Idoc from R/3 to XI, the IDXNOALE - table is populated automatically. Y is this. Can anyone please explain this? -Naveen.

  • EA Version 4.0 - plsql_debug = TRUE

    The actual version sets the session parameter PLSQL_DEBUG to TRUE. All normal (without debug) compiled plsql objects were compiled with debug!!! aaaarg! an additional test: i closed all connections and opened them again and the wrong icons are still