Redirection When Session Times Out

来源:互联网 发布:银河号事件 知乎 编辑:程序博客网 时间:2024/05/16 04:38
<session-config>
<session-timeout>1</session-timeout>
</session-config>
Create a Project With Two Pages
Youcan easily create this example yourself. Set up two pages in yourVisual Web application: a Page1 that has a button and an ErrorPage thatdisplays a session timeout message. If the user clicks the button onPage1 before the timeout value set in the web.xml file is reached, thennothing happens (because the session has not timed out). However, ifthe timeout value has been reached, indicating that the session hastimed out, then the button should take the user to the ErrorPage.

Rememberthat, to see if redirection works when the session times out, you mustwait more than whatever timeout value you have set in the web.xml filebefore clicking the button.

Using a Servlet Filter
Thebest way to redirect a user when a session times out is to use aServlet Filter. Using this approach, you do not need to make any codemodifications 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 andclick New -> Other to open the Choose File Type dialog. (In NetBeans5.5 or 5.5.1, right click the project and click New->File/Folder toopen the same dialog.) Then, in the dialog screen select Web in theCategories column (if it is not already highlighted) and Filter in theFiles Type column. Click Next.
The New Filter dialog displays.Enter SessionCheckFilter for the Class Name and click Next. (You canuse any name you want for the filter.)
In the Configure FilterDeployment dialog, select SessionCheckFilter in the Filter Mappingsbox, 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() {}
}


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

Now, youcan simply deploy and run the project. The filter redirects you to theerror page when you wait more than the timeout value (in our case, oneminute) before clicking the button on the main page. This redirectionoccurs regardless of how many times you may have previously clicked thebutton. Note, too, that the Servlet Filter works for any page and anycomponent. There is no need for you to write any special code for thecomponents on a page.

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

Inaddition to setting a timeout value, for this approach to work be surethat the javax.faces.STATE_SAVING_METHOD parameter in the web.xml fileis set to client. If set to server, then the button action method willnever be called, regardless of the timeout setting. To verify andchange the setting for this parameter, expand the web.xml file ContextParameters section. If the value for javax.faces.STATE_SAVING_METHOD isset to server, use the Edit button to change the property value toclient.


Figure 3: Setting javax.faces.STATE_SAVING_METHOD parameter

Allthe critical code is in the button’s action handler method. Open thePage1 button action handler method in the Java source editor and addthe following code to the method. After entering this code, use the FixImports 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 blockexecutes; otherwise, the user is still within the same session and theaction handler method returns. The redirection code is within the tryblock:

if (session.isNew()) {
try {
String errorPageURL = externalContext.getRequestContextPath() +
"/faces/ErrorPage.jsp";
externalContext.redirect(errorPageURL);
Theabove code establishes the path to the page you want redirection to goto, which in this case is the error page, ErrorPage.jsp. That path is acombination of the web application context and the name of the pagethat redirection goes to. The code uses theExternalContext.getRequestContextPath method to return the portion ofthe 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 redirectmethod, passing it the absolute URL path to the redirection page. Theredirect method redirects a client request to the specified URL. Italso invokes the responseComplete method on the current request'sFacesContext instance.

Summary
While both approaches work,it’s easy to see that using a Servlet Filter is the morestraightforward approach for handling redirection when a session timesout. 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 alsoavoids the need to have the redirection logic on each page (or includedwithin multiple component action handlers) for which you want to checkfor a session time out. 
原创粉丝点击