How to setup session scope in servlet?

bean tag can be used in jsp to setup its scop, like
<jsp:usebean id="abc" class="def" scope="session"/>
but is it possible to setup session scope to divide two users in order not to use the same bean? becuase i encounter a problem that, when using bean in servlet, seemly A user would access the data that B user just store in; at first, i try to compare if session == null or session.isNew(), but finally find out that their session.getId() is difference, thus i suppose that if i am able to decide via users' session id to limit their access to the bean just as jsp:usebean does!
is that right? or in what way is better?(i am now to rewrite my original code, it's a little bit complicate for some reasons, so i think, if possible, that via compare session id, that i do not know how, would be a better way!)
thanks in advice,

If each user has a separate session, then each one
should get their own instance of the bean. Is it
possible that that you store and retrieve a reference
to the bean in a servlet instance variable? That
would cause the problem you describe.do you mean by putting variable in situation like A) ; yes i did, but if i put bean in the body of doPost method, each time when bean are "new"ed, there may be error occurred, accounting for i hope to instantize with default value, but default constructor do nothing; thus if by only construct with default constructor, error would occurred and so a new constructor with parameters i put in the position you refferred to! would you like to tell me what's the right way for i am not so familiar with servlet.
thanks in advice,
A)
public class MyClassName extends HttpServlet {
BeanClass myBean = new BeanClass();
... doGet(...){}
... doPost(...){...}

Similar Messages

  • How can a session scope bean access an application scope bean - help

    Hello,
    I have a JSP page that has references to an Application Scope and a Session Scope bean...
    <jsp:useBean id="myWebApp" scope="application" class="com.my.web.WebApplication" />
    <jsp:useBean id="myWebSession" scope="session" class="com.my.web.WebSession" />
    I would like the WebSession access methods in the WebApplication ... Can/ How does the WebSession object lookup the reference to WebApplication object?

    I don't think you should make the WebSession implement the session listener.
    The session listener will be created once, at the start of the servlet context and would be listening to all sessions. So you would have one instance of the WebSession belonging to the context (though not as an attribute), and others belonging to each session. This will be confusing in your code, I think.
    I would suggest having a different class act as the HttpSessionListener. Perhaps do something like this:
    public class WebSessionInjector implements HttpSessionListener {
      public void  sessionCreated(HttpSessionEvent e) {
        WebApplication webApp = (WebApplication)(e.getSession().getServletContext().getAttribute("webapp"));
        WebSession mySession = new WebSession();
        mySession.setWebApplication(webApp);
        e.getSession().setAttribute("mySession", mySession);
      public void sessionDestroyed(HttpSessionEvent e) { ... }
    }You may be able to use the WebApplication object itself as the listener ...
    Or, you could make the WebSession implement the HttpSessionBindingListener and use the valueBound event much like the sessionCreated event above, but from inside the WebSession object:
    public class WebSession implements HttpSessionBindingListener {
      public void  valueBound(HttpSessionBindingEvent e) {
        WebApplication webApp = (WebApplication)(e.getSession().getServletContext().getAttribute("webapp"));
        this.setWebApplication(webApp);
      public void valueUnbound(HttpSessionBindingEvent e) { ... }
    }

  • How to use Session scope in jsp page

    Hello, I have login form, where user provides username and password. Then click on submit, it will forward to validation.jsp. Where it will check in database make sure username and password exit. Now i can also retrive accountid of perticular user. I want to put that username and accountid in session scope. so all other pages can use that username and accountid. How can i do that. I'm new at this, so please provide me example too. Here is my code for login.jsp and validation.jsp..
    Validation.jsp
    <%@ page import="java.util.*" %>
    <%@ page import="java.sql.*" %>
    //String name = request.getParameter( "username" );//
    //session.setAttribute( "accountID",accountID );//
    <%
    String connURL = "jdbc:oracle:thin:@orca.csc.ncsu.edu:1521:ORCL";
         Connection conn = null;
         Statement stmt = null;
         ResultSet rs = null;
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    conn = DriverManager.getConnection(connURL, "vapatel","pjdas");
    stmt = conn.createStatement();
    String user=request.getParameter("userName");
    String password=request.getParameter("password");
    boolean entrance=false;
    stmt.excuteQuery("SELECT AccountID From Password WHERE USERNAME='"+user+"'");
    rs = stmt.executeQuery("SELECT * FROM Password WHERE USERNAME='"+user+"' AND PASSWORD='"+password+"'");
    while(rs.next()){
    String dbUser = rs.getString("USERNAME");
    String dbPassword= rs.getString("PASSWORD");
    if ((user.equals(dbUser)) && (password.equals(dbPassword))){
    entrance=true;
    if (entrance==true){%>
    <jsp:forward page="form.jsp"/>
    <%}
    else{%>
    <jsp:forward page="login.jsp"/>
    <%}
    %>

    hi,
    to put something into session scope in a jsp page use:
    session.setAttribute("counter", Integer.toString(5));to retrieve is from a jsp page use:
    String counterAttribute = (String)session.getAttribute("counter");

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

  • Can you tell me How to loading sessions.xml in servlet

    Can you tell me How to loading sessions.xml in servlet

    Getting a session in a servlet is no different than in any other environment except that you need to be careful which classloader you pass to the SessionManager and correctly configure what to do if your application is reloaded. If you use the oracle.toplink.util.SessionFactory introduced in 10.1.3.1 you don't have to worry about these details--it uses the correct settings. The SessionFactory greatly simplifies the code required to get a session or unit of work. It's well documented in the SessionFactory javadoc.
    If you do use SessionFactory beware there is a bug when running in a JTA environment and there's no transaction started. Doug posted a work around in his blog[1].
    --Shaun
    [1] http://www.jroller.com/page/djclarke/20060412

  • How to remove session scope?

    Hi,
    I instantiated a bean using the JSP useBean tag and set its session scope to session. I want to at one point be able to remove the bean from session, how can I do this?
    regards
    Siliconbt

    you make the bean object null then u can remove the session.
    the above answer given in my view
    if any pls forward to me

  • Cant able to get the output while using session scope

    Hi
    I am using jdeveloper 11.1.1.5
    As i posted in the previous post i had made some changes still i am not getting proper output
    These are steps that i had followed for developing login page
    1.I had created a TaskFlow in adfc-config.xml such that if the login is success it navigates to the other page pls verfiy the link
    http://www.4shared.com/photo/5PNrf1hd/E028_2.html
    2.I had also changed the scope to session in adfc-config.xml
    http://www.4shared.com/photo/HtVVOw_B/E029.html
    3.This was my Welcome.jspx code
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:f="http://java.sun.com/jsf/core"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <jsp:directive.page contentType="text/html;charset=UTF-8"/>
      <f:view>
        <af:document id="d1" binding="#{sessionScope.backing_welcome.d1}">
          <af:form id="f1" binding="#{sessionScope.backing_welcome.f1}">
            <af:inputText label="UserName" binding="#{backing_welcome.it1}"
                          id="it1" value="#{sessionScope.backing_welcome.auser}"/>
            <af:inputText label="Password" binding="#{backing_welcome.it2}"
                          id="it2"
                          value="#{sessionScope.backing_welcome.apassword}"/>
            <af:commandButton text="Login"
                              binding="#{backing_welcome.cb1}" id="cb1"
                              action="#{backing_welcome.cb9_action}"/>
          </af:form>
        </af:document>
      </f:view>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_welcome-->
    </jsp:root>3.This was my welcome.java backing bean for welcome.jspx page
        public String getAuser() {
            return auser;
        public void setApassword(String apassword) {
            this.apassword = apassword;
        public String getApassword() {
            return apassword;
        public String cb9_action() {
            String returnStr="error";
            System.out.println("Inside loginBtn_action");
            BindingContainer bindings = getBindings();
            OperationBinding operationBinding = bindings.getOperationBinding("checkLoginCredentials1");
            operationBinding.getParamsMap().put("p_user", auser);
            operationBinding.getParamsMap().put("p_pwd", apassword);
        operationBinding.execute();
        Object result = operationBinding.execute();
        if (!operationBinding.getErrors().isEmpty()) {
            returnStr= "success";
        System.out.println("returnStr= " + returnStr);
               return returnStr;
        }While i run my program no output is displayed!! No logs also been recorded!!
    Could any body pls help me!!

    thank you jhon!
    If i am not using any binding i m getting error as
    javax.el.PropertyNotFoundException: Target Unreachable, 'backing_welcome' returned nullI had used this jspx code
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:f="http://java.sun.com/jsf/core"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <jsp:directive.page contentType="text/html;charset=UTF-8"/>
      <f:view>
        <af:document id="d1" >
          <af:form id="f1" >
            <af:inputText label="UserName"
                          id="it1" value="#{sessionScope.backing_welcome.auser}"/>
            <af:inputText label="Password"
                          id="it2"
                          value="#{sessionScope.backing_welcome.apassword}"/>
            <af:commandButton text="Login"
                               id="cb1"
                              action="#{sessionScope.backing_welcome.cb9_action}"/>
          </af:form>
        </af:document>
      </f:view>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_welcome-->
    </jsp:root>Give me some guide how to use session scope!! Since i read all the documents i m not getting any proper output

  • Should we try to access session scope in ADF BC ?

    hi
    In the blog post "How to Access Session Scope in ADF BC "
    at http://andrejusb.blogspot.com/2012/01/how-to-access-session-scope-in-adf-bc.html
    Andrejus Baranovskis suggests it is no problem to access session scope in ADF BC using
    Map sessionScope = ADFContext.getCurrent().getSessionScope();But I wonder if this is really a good practice, as it looks very much like breaking the MVC pattern.
    At the same time I wonder where the Oracle documentation says this would be a good or bad idea.
    One starting point could be the ADFContext.getCurrent() method
    at http://docs.oracle.com/cd/E24382_01/apirefs.1112/e17486/oracle/adf/share/ADFContext.html#getCurrent%28%29
    that starts with saying "Gets the ADF context for the current thread. ..." which in a typical deployment scenario of ADF BC might not cause a problem.
    But, I wonder how defensive your programming should be when using the getSessionScope() method in your ADF Business Component code (that implements the Model).
    Ideas and feedback welcome.
    many thanks
    Jan Vervecken

    Hi Shay,
    Reviewing ADFContex methods it seems that this object shouldn't be accessible from BC. Example:
    public static ADFContext initADFContext(java.lang.Object context,
                                            java.lang.Object session,
                                            java.lang.Object request,
                                            java.lang.Object response)
        Initializes the ADFContext for the environment of the specified context.
        Parameters:
            context - the ServletContext or PortletContext of the current execution environment.
            session - the HttpSession or PortletSession of the current execution environment. OPTIONAL.
            request - the HttpServletRequest or PortletRequest of the current execution environment. OPTIONAL.
            response - the HttpServletResponse or PortletResponse of the current execution environment. OPTIONAL.
        Returns:
            the ADFContext that was current when init was invoked. Should be passed back to resetADFContext after the block requiring the ADFContext has completed.Kuba

  • Implementing session handling in servlet controller

    how to implementing session handling in servlet controller.
    instead of writing isNew() in every jsp page i wanted to write in my central controller ,where each request is passing through controller. can any body give me the solution

    i tried it it is failed because first time the request is coming to the controller.it checks for new since of it is a first request it is forwarded to the login page.how to avoid or skip the condition checking when the request is first time.

  • How to convert processScope to Session Scope.

    Hi,
    Could you please tell me any one, how to convert processScope to Session Scopde.
    because i need to pass 1 processScope value to Servlet. but servlets don't know ProcessScope value. for this i need to convert processScope value into Session scope value.
    Thanks and Regards,
    M. Ramu.

    Hi,
    Could you please tell me, what are the main configurations i need to done about this issue.
    The main requirement is, from Jspx page i need to pass one value to Servlet through xml file.
    as of now i am using processScope in Jspx page, but i passing through xml page to Servlet. As servlet cannot understand processscope, it is throwing null pointer exception.
    Thanks and Regards,
    M. Ramu.

  • How to get a parameter from each request in a session scope BackingBean

    While calling my JSF page, I pass an id as parameter in the URL, and in the Backing bean I retrieve it from the request.
    On each request I need to get the id and populate the page accordingly.
    But I am forced to create my Backing Bean in session scope b'cos otherwise ValueChangeListener method does not work properly.
    So where and how do I get the id on each request?
    Pls. help

    What you can do is create it in the request scope like this:
    <managed-bean>
          <managed-bean-name>personBean</managed-bean-name>
          <managed-bean-class>
            com.PersonBean
          </managed-bean-class>
          <managed-bean-scope>request</managed-bean-scope>
           <managed-property>
                 <property-name>id</property-name>
                 <property-class>java.lang.Long</property-class>
              <value>#{param.id}</value>
          </managed-property>
    </managed-bean>And then in the page use a hidden field to set the id in case of a postback (validation error):
    <h:inputHidden id="id" value="#{personBean.id}"/>Does that help you?
    Thomas

  • How to use session variable in JSP function  & How to use both JSP  Servlet

    Hi,
    I am new to JSP and servlets
    Still I am devloping a website in JSP. I am not mixing JSP with servlets, but I do create Java files for bean, logic and database works.
    I try to keep the hard coding part out of JSP.
    I dont how to use both JSP and Servlets in combination.
    Hence If needed I write some functions in JSP.
    but it gives me error
    +<%! public void abc()+
    +{+
    int intUserId = Integer.valueOf((Integer) session.getAttribute("MySession_UserID"));
    +}+
    +%>+
    Saying cannot find symbol session
    1) So can u please tell how can I access session variables within JSP function
    2) And also give me some links/tutorials about useing both JSP and Servlets in combination.
    Thanks
    Venkat

    The application architecture when you use Servlets and JSP in a standard MVC pattern is explained here (under the heading "Integrating Servlets and JSP Pages") and here ...

  • I don't know how to setup FF to open in last session of windows wont let me save current sessions like it used to ask me fairly disappointing can you help m? Phil

    Question
    i don't know how to setup FF to open in last session of windows wont let me save current sessions like it used to ask me fairly disappointing can you help m? Phil

    ''want FF to open in last session of windows -- won't ask me if I want to save current sessions like it before''
    '''You can still have the old messages''', to make sure you get your tabs restored immediately, but with or without the messages and whichever way you respond to the message you can still get back your previous session through the History menu. (see item #31 "tabslost")
    * http://dmcritchie.mvps.org/firefox/firefox-problems.htm#tabslost
    You can make '''Firefox 6.0''' look like Firefox 3.6.*, see numbered items 1-10 in the following topic [http://dmcritchie.mvps.org/firefox/firefox-problems.htm#fx4interface Fix Firefox 4.0 toolbar user interface, problems (Make Firefox 4.0 thru 6.0, look like 3.6)]. ''Whether or not you make changes, you should be aware of what has changed and what you have to do to use changed or missing features.''
    * http://dmcritchie.mvps.org/firefox/firefox-problems.htm#fx4interface

  • Problem with beans in session scope

    Hello,
    I developped a website using JSP/Tomcat and I can't figure out how to fix this problem.
    I am using beans in session scope to know when a user is actualy logged in or not and to make some basic informations about him avaible to the pages. I then add those beans to an application scope bean that manages the users, letting me know how many are logged in, etc... I store the user beans in a Vector list.
    The problem is that the session beans never seem to be destroyed. I made a logout page which use <jsp:remove/> but all it does is to remove the bean from the scope and not actualy destroying it. I have to notify the application bean that the session is terminated so I manualy remove it from its vector list.
    But when a user just leave the site without using the logout option, it becomes a problem. Is there a way to actualy tell when a session bean is being destroyed ? I tried to check with my application bean if there are null beans in the list but it never happens, the user bean always stays in memory.
    Is there actualy a way for me to notify the application bean when the user quits the website without using the logout link ? Or is the whole design flawed ?
    Thanks in advance.
    Nicolas Jaccard

    I understand I could create a listener even with my current setup Correct, you configure listeners in web.xml and they are applicable to a whole web application irrespective of whether you use jsp or servlets or both. SessionListeners would fire when a session was created or when a session is about to be dropped.
    but I do not know how I could get a reference of the application bean in >question. Any hint ?From your earlier post, I understand that you add a UserBean to a session and then the UserBean to a vector stoed in application scope.
    Something like below,
    UserBean user = new UserBean();
    //set  bean in session scope.
    session.setAttribute("user", user);
    //add bean to a Vector stored in application scope.
    Vector v = (Vector)(getServletContext().getAttribute("userList"));
    v.add(user);If you have done it in the above fashion, you realize, dont you, that its the same object that's added to both the session and to the vector stored in application scope.
    So in your sessionDestroyed() method of your HttpSessionListener implementation,
    void sessionDestroyed(HttpSessionEvent event){
         //get a handle to the session
         HttpSession session = event.getSession();
          //get a handle to the user object
          UserBean user = (UserBean)session.getAttribute("user");
           //get a handle to the application object
          ServletContext ctx = session.getServletContext();
           //get a handle to the Vector storing the user objs in application scope
            Vector v = (Vector)ctx.getAttribute("userList");
           //now remove the object from the Vector passing in the reference to the object retrieved from the Session.
            v.removeElement(user);
    }That's it.
    Another approach would be to remove the User based on a unique identifier. Let's assume each User has a unique id (If your User has no such feature, you could still add one and set the user id to the session id that the user is associated with)
    void sessionDestroyed(HttpSessionEvent event){
         //get a handle to the session
         HttpSession session = event.getSession();
          //get a handle to the user object
          UserBean user = (UserBean)session.getAttribute("user");
           //get the unique id of the user object
           String id = user.getId();
           //get a handle to the application object
          ServletContext ctx = session.getServletContext();
           //get a handle to the Vector storing the user objs in application scope
            Vector v = (Vector)ctx.getAttribute("userList");
           //now iterate all user objects in the Vector
           for(Iterator itr = v.iterator(); itr.hasNext()) {
                   User user = (User)itr.next();               
                    if(user.getId().equals(id)) {
                           //if user's id is same as id of user retrieved from session
                           //remove the object
                           itr.remove();
    }Hope that helps,
    ram.

  • How to get javabean data in Servlets.( JavaBean -- Servlet(Controller)

    how to get javabean data in Servlets.
    1) I am using name ,password in Jsp(View )
    2) when I submit this Bean will be called and Setter methods will be called .
    3) In ServletController (controller) I want to get data of javabean.
    In this I have to do validation of user.
    I want to pass the javabean obj as like -->
    request.getAttribute("beanObj");
    My intention is to get all the poperties in javabean by passing bean id
    or beanobj ,
    Is there any way to get all the data using bean id or beanObj.
    Plz Reply,

    Now in the Servlet we can get the same bean by this code:
    PageContext pageContext = JspFactoryImpl.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
    UserBean userbean = (UserBean)pageContext.getAttribute("userbean", PageContext.SESSION_SCOPE);
    String userid = userbean.getUsername();
    For this code to work it is needed to import 2 files:
    import org.apache.jasper.runtime.JspFactoryImpl;
    import javax.servlet.jsp.PageContext;
    The JspFactoryImpl is in jasper-runtime.jar file provided in tomcat dir.It seems to me that you are exactly knowing what you are doing :-(
    You can get a Bean stored in a Session by
    request.getSession().getAttribute("userbean");
    In the login.jsp page for example we have the code
    <jsp:useBean id="userbean" scope="session"class="com.newproj.UserBean" />
    <jsp:setProperty name="userbean" property="*" />the jsp:setProperty is not called when you click on the submit button
    if fills the bean with the request values from the previous request.
    andi

Maybe you are looking for

  • FCE Exporting Nightmares...Motion artifact

    I've done nearly a dozen projects now in FCE 4, but still can never get the same export format to work twice. My latest project: Filmed as always on a HDD camcorder 1920x1080, ingested and edited without a problem. Project looks great within Final Cu

  • Item category TA YTAK cannot be invoiced with billing type F2

    Hi Experts, Error message in creating billing I did not make shipment and directly make delivery PGI This is transportation relevance showing in delivery. Is this reason preventing from creating F2 blling type? I am getting error for item category YT

  • Internet is messed up

    I have recently moved and my internet worked the first week or so. Now it doesn't. So we bought a lynksis router and it still shuts down. Every hour, it shuts off. First few weeks it was ever 53th minute of the hour. Now its ever 11th minute of the h

  • Itunes consumes 100% of CPU 15 seconds after startup

    I was using iTunes 8, and experienced the following very annoying problem : 15 seconds after startup, the itunes application starts to consume 100% of CPU, and the application is not responding anymore. If I started to play a file within those 15 sec

  • From Recruitment to Retirement

    Dear Experts, Client assigned me to give a presentation on SAP HR from recruitment to retirement completely with SAP screen shots. Please give me your valuable suggestion on this. Kindly help me in this regard. Edited by: sivakpt on May 10, 2011 5:39