HOW TO MANAGE THE SESSION IN JSF 2.0

Hi to All.
I need your help, I am beginner in JSF 2.0, and wanted to know how the sessions work on jsf 2.0?. If you could send a small example.
I need my web application is safe, for example I have a web page users.xhtml to this web page must be entered after the login.xhtml loggedin and redirect if it is not.
On the other hand need to handle logout in my web application.
I hope I can help.
I thank you in advance for your help.
Greetings.

This may help you...
1. What is Session Tracking?
There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?
There are three typical solutions to this problem.
1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled:
* Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all),
* Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and
* Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).
2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.
3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session.
2. The Session Tracking API
Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions.
2.1 Looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. Thus, your first step usually looks like this:
HttpSession session = request.getSession(true);
2.2 Looking up Information Associated with a Session.
HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a builtin data structure that let you store any number of keys and associated values. In version 2.1 and earlier of the servlet API, you use getValue("key") to look up a previously stored value. The return type is Object, so you have to do a typecast to whatever more specific type of data was associated with that key in the session. The return value is null if there is no such attribute. In version 2.2, getValue is deprecated in favor of getAttribute, both because of the better naming match with setAttribute (the match for getValue is putValue, not setValue), and because setAttribute lets you use an attached HttpSessionBindingListener to monitor values, while putValue doesn't. Nevertheless, since few commercial servlet engines yet support version 2.2, I'll use getValue in my examples. Here's one representative example, assuming ShoppingCart is some class you've defined yourself that stores information on items being purchased.
HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling getValueNames, which returns a String array. In version 2.2, use getAttributeNames, which has a better name and which is more consistent in that it returns an Enumeration, just like the getHeaders and getParameterNames methods of HttpServletRequest.
Although the data that was explicitly associated with a session is the part you care most about, there are some other pieces of information that are sometimes useful as well.
* getId. This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions.
* isNew. This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.
* getCreationTime. This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar.
* getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which the session was last sent from the client.
* getMaxInactiveInterval. This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout.
2.3 Associating Information with a Session
As discussed in the previous section, you read information associated with a session by using getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue replaces any previous values. Sometimes that's what you want (as with the referringPage entry in the example below), but other times you want to retrieve a previous value and augment it (as with the previousItems entry below). Here's an example:
HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));
// You still have to do putValue, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.putValue("previousItems", previousItems);
3. Example: Showing Session Information
Here is a simple example that generates a Web page showing some information about the current session. You can also download the source or try it on-line.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
/** Simple example of session tracking. See the shopping
* cart example for a more detailed one.
* <P>
* Part of tutorial on servlets and JSP that appears at
* http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
* 1999 Marty Hall; may be freely used or adapted.
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Searching the Web";
String heading;
Integer accessCount = new Integer(0);;
if (session.isNew()) {
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
Integer oldAccessCount =
// Use getAttribute, not getValue, in version
// 2.2 of servlet API.
(Integer)session.getValue("accessCount");
if (oldAccessCount != null) {
accessCount =
new Integer(oldAccessCount.intValue() + 1);
// Use putAttribute in version 2.2 of servlet API.
session.putValue("accessCount", accessCount);
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +
" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +
"</TABLE>\n" +
"</BODY></HTML>");
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

Similar Messages

  • How to manage the sessions in struts framework

    i have an application which is a multi-user login(say public portal) for this i used struts fram work how can i manage the sessions for this

    Use iTunes on your computer to store items that you want to save but are not needed on the iPad. Learn to sync and also learn how to do file transfers. Delete unneeded items from the iPad.
    When you connect your iPad to iTunes you will see a bar describing how much of your storage space is being used on your iPad. I always suggest leaving plenty of space open for the iOS and apps to operate.

  • How to get the session variable value in JSF

    Hi
    This is Subbus, I'm new for JSF framewrok, i was set the session scope for my LoginBean in faces-config.xml file..
    <managed-bean-name>login</managed-bean-name>
    <managed-bean-class>LoginBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope> like that...
    So all parameter in LoginBean are set in session right ?... for example i used userId is the Parameter...
    Now i need to get the the userId parameter from that session in my another JSP page.. how i get that ?..
    Already i tried
    session.getAtrribute("userId");
    session.getValue("userId");
    but it retrieve only "null" value.. could u please help me.. it's very urgent one..
    By
    Subbus

    Where i use that..is it in jsp or backend bean...
    simply i use the following code in one backend bean and try to get the value from there bean in the front of jsp page...
    in LogoutBean inside
    public String getUserID()
         Object sessionAttribute = null;
         FacesContext facescontext=FacesContext.getCurrentInstance();
         ExternalContext externalcontext=facescontext.getExternalContext();
         Map sessionMap=externalcontext.getSessionMap();
         if(sessionMap != null)
         sessionAttribute = sessionMap.get("userId");
         System.out.println("Session value is...."+(String)sessionAttribute);
         return (String)sessionAttribute;
         return "fail";
    JSP Page
    <jsp:useBean id="logs" scope="session" class="logs.LogoutBean" />
    System.out.println("SS value is ...."+logs.getUserID());
    but again it retrieve only null value.. could u please tell me first how to set the session variable in JSF.. i did faces-config only.. is it correct or not..
    By
    Subbus

  • Hi someone, I went to muse theme and browse widgets to find the toolbox 024 of google language translator, i saw the video explaining how to manage the widgets but now where can i found it to include it in my website because the french version of muse don

    Hi someone, I went to muse theme and browse widgets to find the toolbox 024 of google language translator, i saw the video explaining how to manage the widgets but now, where can i found it to include it in my website because the french version of muse don't have several free widgets for people like me who pay every month the application.Thanks

    I'm not aware of a free translator widget.
    I found these...
    Website Translator 
    Translator Widget  $6.99 for the widget
    Adobe Muse TB024 Widget | MuseThemes.com  $69/year Includes everything | I signed up for this and it's been well worth it, they have new themes & widgets every month.

  • How to get the session name of a batch input

    hi everybody
    does anybody know how to get the session name of a batch input?
    I have to put the name of the session at the end of my program so that the user can click on the session name to go directly to SM35 to run the batch input when the program ends

    Hi sia,
    1. Table is APQI
    2. field name for session name is GROUPID
    regards,
    amit m.

  • How to manage the files in Ipod?

    Hi everybody!
    I just bought a 80GB Ipod and I'm having a hard time figuring it out how to manage the files I've downloaded to it. I just sent a podcast to it but it doesn't appear it the Podcast folder. I have to search it in the entire list of files. Can someone tell me how I can manage these files?
    Thank you very much!

    Hi everybody!
    I just bought a 80GB Ipod and I'm having a hard time
    figuring it out how to manage the files I've
    downloaded to it. I just sent a podcast to it but it
    doesn't appear it the Podcast folder. I have to
    search it in the entire list of files. Can someone
    tell me how I can manage these files?
    Thank you very much!
    Use iTunes.

  • How to manage the memory in i pad

    how to manage the memory in i pad

    Use iTunes on your computer to store items that you want to save but are not needed on the iPad. Learn to sync and also learn how to do file transfers. Delete unneeded items from the iPad.
    When you connect your iPad to iTunes you will see a bar describing how much of your storage space is being used on your iPad. I always suggest leaving plenty of space open for the iOS and apps to operate.

  • HT4847 How i can download my backup data? And how to manage the data on i Cloud?

    How i can download my backup data? And how to manage the data on i Cloud?

    You can't download an iCloud backup, except to restore it to your device should you ever need to.
    iCloud data can be managed within the apps on your iPad.  Any changes to the data within the apps corresponding to the data you are syncing with iCloud will take place in iCloud.  You can also manage some of this data on icloud.com from your computer.
    This article explains ways to manage your iCloud storage space, should you need to reduce you iCloud storage: http://support.apple.com/kb/ht4847.

  • How to make the session to wait until other session get closed successfully

    Hi ,
    In my program , I am calling sql loader and after that I am opening a session and inside that I am calling stored procedure which validates the data.
    above calling of sql loader and stored procedure is done inside the shell script i.e .prog file which is registerd as host concurrent program.
    Here i am facing the problem like when two files are processed with same content then second file content's are not erroring out as duplicate though there is a duplicate validation exist inside the procedure. IF I call dbms_lock.sleep(60) then it is working and sencond file are records are error out with duplicate error message. but this is working only for small data files.
    Please suggest me how to make the session to come out successfully then only i can open other sesssion .
    Thanks
    Raghav

    user5853450 wrote:
    Hi ,
    In my program , I am calling sql loader and after that I am opening a session and inside that I am calling stored procedure which validates the data.
    above calling of sql loader and stored procedure is done inside the shell script i.e .prog file which is registerd as host concurrent program.
    Here i am facing the problem like when two files are processed with same content then second file content's are not erroring out as duplicate though there is a duplicate validation exist inside the procedure. IF I call dbms_lock.sleep(60) then it is working and sencond file are records are error out with duplicate error message. but this is working only for small data files.
    Please suggest me how to make the session to come out successfully then only i can open other sesssion .
    Thanks
    RaghavFor starters you could use external tables rather than SQL*Loader and then you could keep all the control on the database side of things rather than relying on an external utility. The external tables will give you all the functionality of SQL*Loader but all you to just read the data using SQL select statements instead and cut out all the shell script dependency.
    Alternatively you could also look at Job Chaining...
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14214/chapter1.htm#FEATURENO05574

  • How to manage the host root folder?

    I'm using iWeb08, and I'm on system OSX 10.5.8.
    Last week I flawlessly transferred my site from Apple to another host.
    My question is, to make a few simple changes to it, {mostly text and links}, do I have to load up ALL the files again to the ftp host?  I don't know how to manage the root folder yet and I don't want to clutter the folder or cause the site to malfunction.
    Is there any useful posts on managing a hosting root folder??
    Problems or thing I should know using iWeb08?
    Thanks...  Ghary.com

    Once you get to know the file structure its possible to just upload the changed files by intelligent guesswork.
    You can also look at the date on the local published files but this would be rather time consuming.
    Most FTP apps have a synchronise feature to handle this for you but you need to set this up carefully and do a test run to make sure it doesn't wipe out essential files on the server.
    If you do a lot of updates and you want to get your web pages downloading faster, an optimizer will do all the thinking for you. These screenshots are of one of Ton Brand's Optimizers - HTML Optimizer Plus
    On the first pass all the files are optimized and uploaded...
    After that, Smart Handling is turned on and only the changed files are processed...
    The original folder is 10.1 MB and the Optimized one is 7.7 MB. That's without optimizing the PNG images. The finished site downloads fast. It needs to since its designed to work on mobile devices.

  • How to manage the ATE_SEARCH_IDX-index in Ask the expert-application?

    I'm currently looking at the Ask the expert(=Tom Kyte) application and I cannot figure out how to manage the Oracle Text-index "ATE_SEARCH_IDX" ON "ATE_SUBMITTED_QUESTIONS" ("ANSWER")
    INDEXTYPE IS "CTXSYS"."CONTEXT".
    In the Readme-file can be read:
    "To customize search functionality, view the Oracle Text Index installation
    script. You can change the interval that the index is synched and change
    the fields that are used in the search."
    I don't see the Oracle Text Index installation-script.
    Can anyone give me the contents of the script or come up with an alternative?
    Thanks,
    Jan Willem

    Thank you, Marco. I found it.
    Still, the reason why I was looking for it was the fact that I asked myself a question, answered it and then tried to Search for it. I couldn't find my own question (and answer).
    The only way I found to make it work was to manually rebuild the index on the answer-column in ATE_SUBMITTED_QUESTIONS. But I'm sure there's another way, because these are not the kind of things you'd like a customer (or myself) to do on a regular basis.
    Can you give me another way to synchronize this index preferably managed from inside the database?

  • How to manage the Credit Control for Customer Consignment Process?

    Hi All,
    Could anyone tell me how to manage the Credit Control for Customer Consignment Process?
    Thanks

    Hi, there is not standard solution, we did customized process for consignment credit block , check below
    1. defined status profile - with lock/auto/approved/rejected and new t.code for approval or rejected.
    2. maintained consignment credit limit in Z table
    3. logic for detemining status written in sales order save userexit.
    4. while calcualting the values, system need to check open sonsignment order of customer/ open deliveries/ stocks at customer place MSKU table. and calculate value with MBEW/KONV ect.
    5. if value is less than Z table then status AUTO, which do not need release, if value is greater than Z table put status LOCK means credit block need to release from new T.code.
    Hope you get some idea

  • How to manage the Discoverer for OLAP catalog -Require Documentation

    how to manage the Discoverer for OLAP catalog - I need docuementation on this area. can some one please help it
    Thanks, Prasad

    Check the Discoverer Installation and Configuration Guide, Chapter 6. Also review the Discoverer for OLAP Best Practices Guide on the Discoverer OTN Home Page.
    Keith Laker
    Oracle EMEA Consulting
    BI Blog: http://oraclebi.blogspot.com/
    DM Blog: http://oracledmt.blogspot.com/
    BI on Oracle: http://www.oracle.com/bi/
    BI on OTN: http://www.oracle.com/technology/products/bi/
    BI Samples: http://www.oracle.com/technology/products/bi/samples/

  • How to find the sessions which generated maximum redo amount at instance?

    I use below query or Sql*Plus's set autotrace traceonly statistics > redo size statistic to calculate how much redo I generated in my session;
    CREATE OR REPLACE VIEW redo_size AS
    SELECT value
    FROM v$mystat, v$statname
    WHERE v$mystat.statistic# = v$statname.statistic#
    AND v$statname.name = ‘redo size’;
    But how to find the sessions which generated maximum(top 5 for example) redo from the last database startup on 9iR2 or also with new 10gR2 historic views?
    We need this information because from the produced archived log files we observe something new producing almost 2 times more redo for a week. I looked at statspack report but couldnt find as I suspected for a massive update or delete.
    Best regards,
    Tonguc

    I tried v$sysstat but I didnt think about v$sesstat Mr.Gasparotto, thank you very much :)
    SELECT ss.sid,
    sq.sql_text,
    se.status,
    se.username,
    se.osuser,
    se.program,
    se.machine,
    ss.VALUE
    FROM v$sesstat ss, v$statname sn, v$session se, v$sqlarea sq
    WHERE ss.statistic# = sn.statistic#
    AND se.sql_hash_value = sq.hash_value(+)
    AND se.sql_address = sq.address(+)
    AND ss.sid = se.sid
    AND sn.NAME = 'redo size'
    ORDER BY ss.VALUE DESC
    Best regards.

  • How to remove the Sessions used in the application

    Hai Techies,,,
    i am using many number of sessions in my application, for example i am using 5 sessions in reports module
    my application is a web based application
    if can't remove the sessions it contains the huge amount of data , my application is going into mess, and the application performance will be decreased..
    Can anybody tell the solution for this Problem
    How to remove the Sessions used in the application
    Hoping a reply
    Thanks & Regards
    Krishna mangamuri

    Hai Gita,
    i am not able to do the session invalidate method bcoz, i am mainatainting the session from login along with the current userid who is login into the system and putting some of the data in session....
    thats session is to be valid upto when i click on logoff link
    except that i have to remove the sessions in my application
    while navigating from one jsp to another i have to remove the sessions, bit somes times that sessions may be used somewhere
    Can u Understand My problem
    session remove method may also helpful to me but some times it will casue some prob to me
    Is there any other Way to remove the sessions in the Application ????
    Thanks & Regards
    Krishna Mangamuri

Maybe you are looking for