Java Web project, filter determines session failure

Source: Internet
Author: User

Generally, Java Web projects use filters to determine whether a session is invalid. The following example shows how to implement a filter to verify whether a user's session is lost.

Configuration in Web. xml:

<Filter> <filter-Name> filter </filter-Name> <filter-class> com. zyujie. Common. loginfilter </filter-class> </filter> <! -- Servlet specification, cannot use /*. the end of JSP is full or written as/APP /*, this is the case --> <filter-mapping> <filter-Name> filter </filter-Name> <URL-pattern>/* </url-pattern> </filter-Mapping> <session-config> <session-Timeout> 1 </session-Timeout> </session-config>

Filter class:

Package COM. zyujie. common; import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. filter; import javax. servlet. filterchain; import javax. servlet. filterconfig; import javax. servlet. servletexception; import javax. servlet. servletrequest; import javax. servlet. servletresponse; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. htT P. httpsession; public class loginfilter implements filter {public void destroy () {// todo auto-generated method stub} public void dofilter (servletrequest req, servletresponse res, filterchain chain) throws ioexception, servletexception {// todo auto-generated method stubhttpservletrequest request = (httpservletrequest) req; httpservletresponse response = (httpservletresponse) RES; httpsession session = Request. getsession (); // if the session is not empty, you can browse other pages with string url = request. getservletpath (); system. out. println (URL); // specifies the Directory and suffix, which can also be written on the web. in XML, use URL-pattern to intercept if ing if ((! Request. getservletpath (). Equals ("/login. Action "))&&(! Request. getservletpath (). Equals ("/login. jsp "))&&(! Request. getservletpath (). Equals ("/relogin. jsp "))&&(! Request. getservletpath (). equals ("/jquery-1.8.0.min.js") {system. out. println (request. getservletpath (); If (Session. getattribute ("userinfo") = NULL) {session. invalidate (); response. setcontenttype ("text/html; charset = gb2312"); printwriter out = response. getwriter (); out. println ("<script language = 'javascript 'Type = 'text/JavaScript '>"); out. println ("alert ('session becomes invalid because you haven't performed this operation for a long time! Please log on again! '); Window. location. href = '"+ request. getcontextpath () + "/relogin. JSP '"); out. println ("</SCRIPT>");} else {chain. dofilter (request, response) ;}} else {chain. dofilter (request, response) ;}} public void Init (filterconfig arg0) throws servletexception {// todo auto-generated method stub }}

I did a test: All Ajax requests cannot be filtered, and I don't know why. If Ajax needs to determine the session, it can use the Interceptor: Code: (Ajax requests cannot jump to the page, but do not know how to implement this Ajax request, the session is lost, and the page jumps .)

Struts2 configuration, Interceptor:

<package name="myInterceptors" namespace="/system/login" extends="struts-default"><interceptors><interceptor name="timer" class="com.zyujie.common.TimerInterceptor" /><interceptor name="logger" class="com.zyujie.common.LoggerInterceptor" /><interceptor name="sessionFilter" class="com.zyujie.common.SessionFilterInterceptor" /></interceptors><action name="userLogin" class="userLoginAction" method="userLogin">        <interceptor-ref name="logger" />        <interceptor-ref name="timer" /><result name="input" type="redirect">/login.jsp</result><result name="success" type="redirect">/ok.jsp</result>   </action>      <action name="getSession" class="userLoginAction" method="getSession">   <result name="input" type="redirect">/login.jsp</result>   </action><action name="reLogin" class="userLoginAction" method="reLogin"><result name="input" type="redirect">/relogin.jsp</result><result name="success" type="redirect">/ok.jsp</result></action><action name="testSession" class="userLoginAction" method="testSession"><interceptor-ref name="sessionFilter" /><result name="input" type="redirect">/login.jsp</result><result name="success" type="redirect">/ok.jsp</result></action></package>

Interception class:

Package COM. zyujie. common; import Java. io. printwriter; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; import Org. apache. struts2.servletactioncontext; import COM. opensymphony. xwork2.action; import COM. opensymphony. xwork2.actioninvocation; import COM. opensymphony. xwork2.interceptor. abstractinterceptor; public class sessionfilterinterceptor extends actinterceptor {@ Overridepublic string intercept (actioninvocation Invocation) throws exception {httpsession session = servletactioncontext. getrequest (). getsession (); If (Session. getattribute ("userinfo") = NULL) {// httpservletresponse response = servletactioncontext. getresponse (); // servletactioncontext. getresponse (). sendredirect (action. input); // session. invalidate (); // response. setcontenttype ("text/html; charset = gb2312" ); // Printwriter out = response. getwriter (); // out. println ("<script language = 'javascript 'Type = 'text/JavaScript '>"); // out. println ("alert ('session becomes invalid because you haven't performed this operation for a long time! Please log on again! '); Window. location. href = '/login. JSP '"); // out. println ("</SCRIPT>"); // return "NONE"; Return Action. input;} else {return invocation. invoke ();}}}

For Ajax requests, the page cannot be redirected. Many people say that they only need to determine the return value on the page to jump.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.