现在的位置: 首页 > 综合 > 正文

Redirection When Session Times Out

2013年07月27日 ⁄ 综合 ⁄ 共 6416字 ⁄ 字号 评论关闭
<session-config>
<session-timeout>1</session-timeout>
</session-config>
Create a Project With Two Pages
You
can easily create this example yourself. Set up two pages in your
Visual Web application: a Page1 that has a button and an ErrorPage that
displays a session timeout message. If the user clicks the button on
Page1 before the timeout value set in the web.xml file is reached, then
nothing happens (because the session has not timed out). However, if
the timeout value has been reached, indicating that the session has
timed out, then the button should take the user to the ErrorPage.

Remember
that, to see if redirection works when the session times out, you must
wait more than whatever timeout value you have set in the web.xml file
before clicking the button.

Using a Servlet Filter
The
best way to redirect a user when a session times out is to use a
Servlet Filter. Using this approach, you do not need to make any code
modifications to a button’s action handler.

The general steps are:

Use the GUI to create a Filter class and set its filter mapping to Servlet and Faces Servlet.
Replace the code in the Servlet Filter class with custom code.
Deploy the project.
Here’s how to accomplish this.

First,
create the Filter class. In NetBeans 6.0, right click the project and
click New -> Other to open the Choose File Type dialog. (In NetBeans
5.5 or 5.5.1, right click the project and click New->File/Folder to
open the same dialog.) Then, in the dialog screen select Web in the
Categories column (if it is not already highlighted) and Filter in the
Files Type column. Click Next.
The New Filter dialog displays.
Enter SessionCheckFilter for the Class Name and click Next. (You can
use any name you want for the filter.)
In the Configure Filter
Deployment dialog, select SessionCheckFilter in the Filter Mappings
box, if not already highlighted, then click Edit.

In the Filter Mapping dialog, check Servlet and be sure it is set to Faces Servlet. Click Finish.

Figure 2: Filter Mapping Dialog

Now, open the SessionCheckFilter class in the source editor and replace the entire class with the following code.
Code Sample 1: SessionCheckFilter Code for Redirection
public class SessionCheckFilter implements Filter {
private static int firstRequest = 0;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest)request;
HttpServletResponse hres = (HttpServletResponse)response; HttpSession session = hreq.getSession();
if (session.isNew()) {
if(firstRequest == 0){
firstRequest++;
} else {
hres.sendRedirect("faces/ErrorPage.jsp");
return;
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {} public void destroy() {}
}

The
Servlet Filter does all its processing in the doFilter method. It gets
a reference to the session and tests if the session is new or if the
user is still in the previous session. If new, the code increments the
variable firstRequest, indicating this is no longer a new session. But
if the user is still within the same session and it has timed out; the
Servlet Filter redirects the user to a page set up to handle time out
situations. In this example, it is faces/ErrorPage.jsp.

Now, you
can simply deploy and run the project. The filter redirects you to the
error page when you wait more than the timeout value (in our case, one
minute) before clicking the button on the main page. This redirection
occurs regardless of how many times you may have previously clicked the
button. Note, too, that the Servlet Filter works for any page and any
component. There is no need for you to write any special code for the
components on a page.

Modifying the Button Action Handler Method
You
can instead write some custom code for the button action handler method
to redirect the user to another page when a session expires.

In
addition to setting a timeout value, for this approach to work be sure
that the javax.faces.STATE_SAVING_METHOD parameter in the web.xml file
is set to client. If set to server, then the button action method will
never be called, regardless of the timeout setting. To verify and
change the setting for this parameter, expand the web.xml file Context
Parameters section. If the value for javax.faces.STATE_SAVING_METHOD is
set to server, use the Edit button to change the property value to
client.


Figure 3: Setting javax.faces.STATE_SAVING_METHOD parameter

All
the critical code is in the button’s action handler method. Open the
Page1 button action handler method in the Java source editor and add
the following code to the method. After entering this code, use the Fix
Imports function to import the classes used by the code.

Code Sample 2: Button Action Handler for Session Timeout Redirection
public String button1_action() {
ExternalContext externalContext = getFacesContext().getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
HttpSession session = request.getSession();
if (session.isNew()) {
try {
String errorPageURL = externalContext.getRequestContextPath() +
"/faces/ErrorPage.jsp";
externalContext.redirect(errorPageURL);
} catch(IOException ioe) {
System.out.println("==============");
ioe.printStackTrace(System.out);
System.out.println(ioe.toString());
System.out.println("==============");
}
} else {
System.out.println("==============");
System.out.println("*** Session is not New ***");
System.out.println("==============");
}
return null;
}

The key parts to the action handler method are at the beginning. The first three methods:

ExternalContext externalContext = getFacesContext().getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
HttpSession session = request.getSession();
give you a handle to the session itself.

Next,
you test if the session is new or if the user is still in the same
(previous) session. If new, then the code within the try block
executes; otherwise, the user is still within the same session and the
action handler method returns. The redirection code is within the try
block:

if (session.isNew()) {
try {
String errorPageURL = externalContext.getRequestContextPath() +
"/faces/ErrorPage.jsp";
externalContext.redirect(errorPageURL);
The
above code establishes the path to the page you want redirection to go
to, which in this case is the error page, ErrorPage.jsp. That path is a
combination of the web application context and the name of the page
that redirection goes to. The code uses the
ExternalContext.getRequestContextPath method to return the portion of
the request URI that identifies the request's web application context,
and it appends the name of the redirection page (/faces/ErrorPage.jsp)
to the context.

Then, call the ExternalContext redirect
method, passing it the absolute URL path to the redirection page. The
redirect method redirects a client request to the specified URL. It
also invokes the responseComplete method on the current request's
FacesContext instance.

Summary
While both approaches work,
it’s easy to see that using a Servlet Filter is the more
straightforward approach for handling redirection when a session times
out. Not only can you use the IDE dialogs to create the Servlet Filter,
the code you need to add is uncomplicated. Using a Servlet Filter also
avoids the need to have the redirection logic on each page (or included
within multiple component action handlers) for which you want to check
for a session time out. 

抱歉!评论已关闭.