How to set session attributes in a bean?

How do I set a session attribute in a server-side bean?
I'm not sure if I asked the question the right way. What I meant is, while it's easy to set session attributes in a JSP page (session.setAttribute("sessionname", "sessionvalue")), I'd want to set such an attribute within a server-side bean defined in this web application. But what is the syntax for doing it?

Here a simple bean that stores something in the session and retrieves something from it.
import javax.servlet.http.HttpSession;
public class TestBean {
  private String value;
  public void doSomething(HttpSession session, int a, int b) {
    if (a+b > 0) {
      session.setAttribute("ab",Boolean.TRUE);
    } else {
      session.setAttribute("ab",Boolean.FALSE);
  public void init(HttpSession session) {
    if (session != null) {
      Boolean b = (Boolean)session.getAttribute("ab");
      if (b == Boolean.TRUE) {
        value = "a + b is greater than zero";
      } else {
        value = "a + b is not greater than zero";
    } else {
      value = "no session";
  public String getValue() {
    return value;
}In your JSP, use something along the lines of :
<%
  TestBean bean = new TestBean();
  bean.init(session);
  bean.doSomething(session,1,2);
%>If your bean only lives during one request, you can pass the session to the constructor, which stores it in a private variable. This saves passing the session each time.
Hope this helps,
--Arnout                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Javascript to JSP question...Can javascript function set session attributes

    hello,
    i have a web app that, on one of its pages, displays "tabbed pane" as an image map at the top (a la amazon.com). my problem is this: each "logical" page contains separate forms that all use the same javabean. in other words, imagine that the tabs represent an account maintenance web ui for an on-line record store. the first tab might be labeled "General," the second "Contact info," the third "Shipping Info." Each uses the same account bean and displays portions of its properties relevant to the tab at hand. what i want to do is allow a user to enter the account maintenance ui, update info on the first tab, click on tab two and have the request with the changes sent to a processing jsp. yet, since each "tab" is actually a separate URL to another page, how do i get the updated info on the first tabe without adding some sort of "SAVE" button on each tab. ive considered using javascript, but dont know how to get the request params out of the first tab whn i click on another tab. is it possible to include an "onClick" function in each URL that "grabs" the updated form fields off the preceeding tab? can a javacript function set session attributes in jsp?

    hello there,
    wow, you've created one big mammy-jammy tool.
    first, javascript cannot access, set values to the session, without having to post to another JSP. javascript is great for manipulating objects, layers, form values, etc.
    you have 2 issues [if i understand correctly]:
    1) you need to able to save user info for a specific tab without having to reloading the page.
    ---you can create a form for EACH of your tabs and POST all the information to a hidden IFRAME or LAYER for NN4. that hidden IFRAME / LAYER will load a JSP page which with all the parameters you posted to it. or you can build a FRAMESET and target that document["frame-name"].src with that same JSP.
    2) handling when the SAVE INFO action should happen: hence some javascript event handler: onMouseOver, onClick, etc
    ---i don't know the dynamics of your tabs, but if store which tab was clicked on last, then if the user clicks on some other tab, javascript can submit that FORM to a JSP [see condition above]
    you have an interesting tool. can i see?
    i hope i wasn't too confusing, but your problem is sooo interesting. =)
    -WJP

  • How to set two attributes as  a primary key in database ?

    how to set two attributes as a primary key?
    Take COffeesbreak as an example ,
    let's suppose that there are cof_name ,sup_id,price and so on;
    the same cof_name may be suplied by more sup_ids,
    and one sup_id may suply more cof_names.
    so the Primary key should be set the cof_name and sup_id ,
    how to set ?
    (of course that i konw if I set a cof_id,the problem will be easy work out
    but now there are those like above)
    I set that as following:
    create table coffees (cof_name VARCHAR(32) PRIMARY KEY,sup_id INTEGER, PRIMARY KEY,PRICE INTEGER )
    THE database print error :cant add more primary keys!
    thanks in advance

    You can only use the PRIMARY KEY declaration on a column if it is the only Primary Key column.
    Use the PRIMARY KEY constraint statement instead.
    create table coffees (
      cof_name VARCHAR(32),
      sup_id INTEGER,  
      PRICE INTEGER,
      PRIMARY KEY ( cof_name ,sup_id )
    )Dave

  • How to set an attribute while creating an XML?

    Hi All,
    I am required to create an XML in the following manner :
    here  <ITEMS ITEMCOUNT="2"> where ITEM is an element and itemcount=2 is the attribute which means their are 2 line items
    - <HEADER>
      <PR_NO>sap pr no</PR_NO>
      <REVISION_NO>0</REVISION_NO>
       </HEADER>
    - <ITEMS ITEMCOUNT="2">
    - <ITEM>
      <PR_LINE_NO>1</PR_LINE_NO>
      <ITEM_DESCRIPTION>Security Locks</ITEM_DESCRIPTION>
      </LOCATIONS>
      </ITEM>
    </items>
    Please suggest how to set the attribute ITEMCOUNT?
    Thanks,
    Lina

    I am also trying to do something similar to this.  I tried the suggestion given but it still only allows 1 parameter.  A snippet of my .icd file is below.
    Attribute (ROI Settings) {
    Value (Integer) {
    Min (0)
    Max (79)
    Increment (1)
    Display {
    Multiplier (8.000000)
    Offset (0.000000)
    Precision (0)
    Units (Pixel)
    Default (0, 0, 0, 0)
    Current (0, 0, 0, 0)
    Action (Serial) {
    Command (ROI %d, %d, %d, %d\r)
    Response ()
    Timeout (1000)
    Delay (100)
    Any answer or help is appreciated.
    Thanks,
    Bruce

  • How to set a attribute value of a sub node binded to a table.. pls respond.

    Hi friends,
    I have context defined like this.
         Head_node ( table 1)
              Item_node ( table 2, sub node ).  ( now this im saving in global internal table).
    so now when i hit save button, im passing my internal table (it has col1- sales order no, col2 item details(table type, which can have more than one record) to a FM, to create sales order.
    My sales order is getting saved.
    But the function module will return some new values (like sales order number, item number etc).
    Now i want these values to be updated in my context.
    Meaning whenever after that i do get_attribute, i should get these new (sales order no, item no ) also.
    I dont know how to set the context values of sub nodes , so im missing these values.
    kindly respond back to me..
    thanks in advance,
    Niraja

    Its very simple.
    Follow these steps. e.g you want to get the new sales order number. Define a attribute in ur node (or set of attributes in ur case as per reqruirement) say new_so_number.
    Check your FM, if its returning new_so_number then it's fine, otherwise you have to change the FM to return the new_so_number or you have to get from db table somehow, which best suites your req.
    So once you have new_so_number after calling the FM, say in lv_new_so_number field. Then write this code to set the attribute (change the variables as per your context attributes)
    DATA lo_nd_head TYPE REF TO if_wd_context_node.
      DATA lo_el_head TYPE REF TO if_wd_context_element.
      DATA ls_head TYPE wd_this->element_head.
      DATA lv_new_so_number LIKE ls_head-new_so_number.
    * navigate from <CONTEXT> to <HEAD> via lead selection
      lo_nd_head = wd_context->get_child_node( name = wd_this->wdctx_head ).
    * get element via lead selection
      lo_el_head = lo_nd_head->get_element(  ).
    lv_new_so_number = new_so_number. " (You got this as a exporting parameter of FM etc..)
    * get single attribute
      lo_el_head->set_attribute(
        EXPORTING
          name =  `NEW_SO_NUMBER`
          value = lv_new_so_number ).
    Hope it works.

  • How to set the attributes of request in JSF Programming

    Hi All,
    for setting the attribute values for session, we do something like below.
    setValue("#{sessionScope.PREFERED_TOTALDAYS}",request.getParameter("txtDays")!=null?request.getParameter("txtDays"): ""+jobRowSet.getInt("PREFERED_TOTALDAYS"));
    Now my query is for setting the attribute values of request what is the code I need to use??
    thanks,
    sudhakar

    Just replace "sessionScope" with "requestScope". That will set the attribute request scope.
    Regards
    -Jayashri
    Creator team.

  • Setting session attributes at the Role level

    I am running AM7.1 in Legacy mode and I am trying to create a role and assign session attributes at this role level. I followed the instructions for doing this but it does not seem to be working. I created the role and added the session service to it. I then went in an changed the attributes (Max Idle, Max Session, etc.) to the values I need for the role. I then assigned the role to a user. However when I log in as this user and look at the Active Sessions panel all of the values are still saying they are set at the defaults. It is not picking up the new values for the user. Am I missing something? Help! -Jeff

    Reply i was also getting this problem in relam mode but 7.0..........but when i specify in the url?role=rolename..........i see the session info applied but i wanted it to be dyanmically applied(without specifiying the role in the url).......i have raised an SR but that is for 7.0 .........please do it for 7.1 i think you might get some response.

  • How to set block attributes in oracle forms 6i

    Dear gents,
    I have two blocks on one canvas, How can I set different attributes (say different colors) for each record separately given a certain condition in a multi record block.?
    Looking forward hearing from you.
    Many thanks,
    Steve

    Hi,
    You can use SET_ITEM_INSTANCE property.
    Regards,
    Chris.

  • Unable set session attribute with certain types.

    Hello I was surprise that when I execute HttpSession.setAttribute("somekey", new HashMap()), "somekey" will not be stored in the Session. I can replace HashMap with HashSet and it's okay.
              Out of curiosity, I create a Java class like below :
              public class abc implements Serializable {
              public String def = "def";
              And I have the same issue with HashMap and it will not get stored in the Session attribute. Does anyone know what kind of valid object and what makes the object storable into the Session's attribute? Any inputs are appreciated. Thanks.
              yien

    Actually never mind. It have something to do with BEA's Portal Ad services. I will post this into the appropriate forum.

  • How to set field attributes type such as enumeration / boolean / text in Search UIBB when creating search creatria dynamically using default_config?

    Hi Experts !
    I am trying to build search UIBB where I need to configure the search criteria dynamically in the IF_FPM_GUIBB_SEARCH~GET_DEFAULT_CONFIG method.
    Please can anyone tell me is it possible to set the attribute types in dynamic configuration .... because I need to create a drop down field in the selection screen.
    Thanks !

    Was it really necessary to post the whole API description?!?
    Locale[] locales = Locale.ENGLISH();ENGLISH is not a method in class Locale, so do not add the braces "( );".
    Also, the constant ENGLISH is not an array, but just a single Locale object.
    You didn't say what your problem was. What do you want to achieve with your program and what is it that you don't understand?

  • How to transmit session attributes

    I am trying to transmit SESSION attributes from one JSP to another, it works rather unstable ... may be I'm doing something wrong someone can correct me!!!
    sender.jsp
    <%session.setAttribute("test", "test"); %>
    receiver.jsp
    <% String test = (String)session.getAttribute("test"); %>
    ...

    I am trying to transmit SESSION attributes from one JSP to another, it works rather unstable ... may be I'm doing something wrong someone can correct me!!!
    sender.jsp
    <%session.setAttribute("test", "test"); %>
    receiver.jsp
    <% String test = (String)session.getAttribute("test"); %>
    ...

  • How to set hidden value in managed bean?

    Hi
    I have the following :
                           <a4j:commandButton
                                          id="commandButton3"
                                          action="#{backing_CustSearchBean.serchCustomer}"
                                          image="images/btn_search.gif"
                                          style="position: relative; margin-right: 5px;"
                                          actionListener="#{backing_CustSearchBean.checkText}"
                                          immediate="true"
                                          status="wait"
                                          oncomplete="showQuickCreate()"
                                          >  
                                <h:inputHidden id="jsfHidden" binding="#{backing_CustSearchBean.jsfHidden}" />
                                  <a4j:status id="wait">
                                    <f:facet name="start" >
                                      <h:graphicImage url="images/SpinGear2.gif" style="position: absolute; left: 378px; top: 216px; width: 19px; height: 18px;"/>
                                    </f:facet>
                                  </a4j:status>
                     </a4j:commandButton>when the action goes in the managed bean I want to set the value of hidden parameter "jsfHidden" in managed bean and catch it in showQuickCreate (oncomplete="showQuickCreate()" ) javascript function on return to the page.
    Please help, how should I do it?

    I know nothing about a4j, but if you want to pass new parameters from JSF to the backing bean, then use f:param for commandlinks or f:attribute for commandbuttons.
    The h:inputHidden just saves backing bean properties from request to request. You can't set or change it from within the JSF.
    Not sure if the f:attribute will work for the a4j commandbutton (check if they have a support forum at their website?)
    Also see http://balusc.xs4all.nl/srv/dev-jep-com.html about passing parameters and accessing objects and beans in the facescontext.

  • How to set session timeout per user

    Hi,
    Ho do I set the session timeout per User in the
    Application.cfm File??
    I tried using
    <cfif SESSION.UID EQ 1>
    <CFAPPLICATION NAME="appControl" SESSIONMANAGEMENT="Yes"
    sessiontimeout="#CreateTimeSpan(0,0,20,0)#">
    </cfelse>
    <CFAPPLICATION NAME="appControl" SESSIONMANAGEMENT="Yes"
    sessiontimeout="#CreateTimeSpan(1,0,0,0)#">
    </cfif>
    But this didnt work because the cfapplication seems to have
    to be at the top before I call the variable SESSION.UID which
    I set on my login page..
    Someone know how to do this??
    Regards
    Martin

    Martin,
    Your code example cannot work because the "session" scope
    doesn't exist until your application scope is defined. So you have
    to handle this manually. Here's how you can get it done. First,
    define your application to the maximum sessiontimeout you want to
    have.
    <CFAPPLICATION NAME="appControl" SESSIONMANAGEMENT="Yes"
    SESSIONTIMEOUT="#CreateTimeSpan(1,0,0,0)#">
    Then, I don't know how you are doing your login
    authentication but when you have authenticated the user, you need
    to define the userid and the most recent activity in the session.
    Also determine your timeout value based on the userid. See example:
    <CFIF IS_AUTHENTICATED>
    <CFSET session.user.uid = form.userid>
    <CFSET session.user.most_recent_activity = now()>
    <CFIF session.user.id eq 1>
    <CFSET session.user.timeout_mins = 20>
    <CFELSE>
    <CFSET session.user.timeout_mins = 1440>
    </CFIF>
    </CFIF>
    Now, all you have to do is check whether the user has been
    idle for too long and kill the session by purging all session
    variables. For example:
    <!--- if user id is defined, this means user is logged in
    --->
    <CFIF structKeyExists(session, "user") and
    structKeyExists(session.user, "id")>
    <!--- check if timeout has expired --->
    <CFIF datediff("n", session.user.most_recent_activity,
    now()) gt session.user.timeout_mins>
    <!--- timeout has expired, kill the session and log the
    user out --->
    <CFSET StructClear(session)>
    <!--- insert your logout code here --->
    <CFELSE>
    <!--- user hasn't timed out, so reset the most recent
    activity to now --->
    <CFSET session.user.most_recent_activity = now()>
    </CFIF>
    </CFIF>

  • SelectManyListbox : How to set the value in the bean ?

    Hi,
    How can I set the selected values from a selectManyListbox in the bean ?
    My page:
                        <li>
                             <div class="box_multiple_selects clearfix">
                                  <div>
                                       <span>Esportes Selecionados</span>
                                       <h:selectManyListbox id="esportes_selecionados" size="10" value="artigoDetailsBean.esportes"/>
                                  </div>
                                  <div class="btns_fluxo fl">
                                       <button value="<<" name="all_right_hand">>></button>
                                       <button value=">" name="one_right_hand">></button>                                   
                                       <button value="<" name="one_left_hand"><</button>
                                       <button value="<<" name="all_left_hand"><<</button>
                                  </div>
                                  <div>
                                       <span>Esportes Cadastrados</span>
                                       <h:selectManyListbox id="esportes_cadastrados" size="10">
                                            <f:selectItems value="#{artigoDetailsBean.esporteList}" />
                                       </h:selectManyListbox>
                                  </div>
                             </div>
                        </li>
    "It´s a move right-left panel". In the right listbox are the database data, and the user click in the left arrow to move the elements (options) from right listbox to the left, and I´d like to get the selected values from the left listbox.
    The bean:
    public class ArtigoDetailsBean {
    private Collection<String> esportes;
         public Collection<String> getEsportes() {
              return esportes;
         public void setEsportes(Collection<String> esportes) {
              this.esportes = esportes;
         public List<SelectItem> getEsporteList() {
              List<SelectItem> esportes = new ArrayList<SelectItem>();
              for(Object esporte: artigoDetailsCommand.getEsporteList() ) {
                   esportes.add( new SelectItem( ((EsporteVO)esporte).getId().toString(), ((EsporteVO)esporte).getDescricao() ) );
              return esportes;
    Thanks in advance,
    Sergio Stateri Jr.
    [email protected]

    This blog shows an example of what you are trying to do - when the user clicks the left arrow it triggers an action event that puts the value into the left list, and vice-versa:
    [http://weblogs.java.net/blog/driscoll/archive/2008/11/jsf_20_the_swit_1.html|http://weblogs.java.net/blog/driscoll/archive/2008/11/jsf_20_the_swit_1.html]
    Ignore the 'JSF 2.0' in the header - it's not JSF 2.0 in this example!
    Also - don't post your email address on the forums - you might get spammed :)
    m

  • How to set column attributes in table control?

    I have the following requirement to build a table by using table control:
    if content of col 1 = 'Y', enable input for col 2 for that line only.
    if content of col 1 = 'N', disable input for col 2 for that line only.
    So the input attribute for col 2 in each line can be different.
    How can I achieve this?
    I have tried using loop at screen or loop at tablecontrol-cols into wa_cols statements,
    but these will change the entire column attributes to either on or off, and not on individual line.
    Instead of changing the COLUMN attributes, I think I should change the CELL attributes. 
    What is the syntax for that, is there something like tablecontrol-field?
    Thanks for any help in advance.

    I still not able to get the field attributes set on individual lines.
    These are my codes, can you help again.
    PROCESS BEFORE OUTPUT.
      MODULE pbo_0200.
      MODULE zitem_change_tc_attr.
      LOOP AT   lt_asset_item
           INTO ls_asset_item
           WITH CONTROL zitem
           CURSOR zitem-current_line.
        MODULE ZITEM_CHANGE_FIELD_ATTR.
        MODULE zitem_get_lines.
      ENDLOOP.
    MODULE zitem_change_field_attr OUTPUT.
    loop at screen.
      if ls_asset_item-replace_asset = 'X'.
         if screen-group1 EQ 'FR4'.        "these are the columns I want to turn input ON or OFF.
          screen-input = '1'.
          modify screen.
         endif.
      endif.
    endloop.
    Endmodule.
    At debug mode, the screen-input did change to '1'.  Can I check the return code of the MODIFY SCREEN statement?
    I tried to initialize the colums to be output only at screen definition, but it still doesn't help.
    I don't think I have to do anything at the PAI event.
    PROCESS AFTER INPUT.
    MODULE save_cursor_position.
      LOOP AT lt_asset_item.
       FIELD ls_asset_item-replace_asset
         MODULE get_replace_asset ON REQUEST.
        CHAIN.
         FIELD LS_ASSET_ITEM-REPLACE_ASSET.
         FIELD ls_asset_item-replace_cost.
          MODULE zitem_modify ON CHAIN-REQUEST.
        ENDCHAIN.
        FIELD ls_asset_item-mark
          MODULE zitem_mark ON REQUEST.
      ENDLOOP.
      MODULE zitem_user_command.
    Thanks again.

Maybe you are looking for

  • Combining multiple rows into a single row

    Hi all, I have a tricky situation in a HR select. Imagine I have a dataset as below, simplified of course. Name Start Date End date Job Title Salary Tom 01/01/07 02/03/08 Gopher £500 Tom 03/03/08 jobsworth £600 Rick 04/05/09 Painter £500 Harry 02/06/

  • I want to read a SD card, but its not working. What need i to do?

    I have a 8GB SD card, and i want that my macbook-pro read this card, i put the card into my MBP, but its giving no response, and it doing nothing? Does somebody know what I can do? (Im using MAC os LION)

  • Air Application won't work

    New to fireworks.  I'm trying to prototype an air application.  I have succussfully created it once, but my links were not created yet so I started again from the original psd file.  Now, no matter what I do it will not finish the creation.  I get re

  • European to UK Adapter work on a Creative DDTS-100?

    Hi I got a Creative Decoder DDTS-100 of a friend but it only comes with a European AC power supply that has two round prongs and I need one for the UK mains, so I was wondering if anyone knows whether one of those European to UK Adapters would work w

  • Safari 6.0 update doesn't work with autoproxy?

    Software update gave me a new Safari 6.0 (7536.25) this morning on my MacPro running Mac OS X 10.7.4.  Now I can no longer access some websites which are reachable through proxies.  My system is still configured with an autoproxy.pac file but apparen