Method 1: Use the session
Method 2: Use the filter
Method 1: Write the following statement in the servlet that handles the login
Set the session's expiration time in seconds
Request.getsession (). Setmaxinactiveinterval (1*60);
(You can also write the following statement in Web. XML to set the expiration time.) But the former has a high priority level.
<session-config>
<session-timeout>1</session-timeout> <!--units are minutes--
</session-config>
)
Role has, can let the main access to the name of the lander.
Request.getsession (). SetAttribute ("Loginuser", username);
You can also set up illegal access and write the following code on the JSP page
/*<%
Use session technology to determine if the user has logged in or not, and the session gets username null.
if (Session.getattribute ("Loginuser") ==null) {
Response.sendredirect ("index.jsp"); Username is empty, then jump to login interface
}
%>*/
Method 2: Write a class implementation of filter three methods destroy () DoFilter () init (), and then set it in Web. Xml.
Isloginfilter.java
Package filter;
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.HttpSession;
public class Isloginfilter implements Filter
{
public void Destroy () {}
public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
SYSTEM.OUT.PRINTLN ("Every request pass here");
Convert a request to a request from HTTP
HttpServletRequest hrequest= (httpservletrequest) request;
HttpSession session=hrequest.getsession ();
Get the information in session
Object stu = Session.getattribute ("Loginuser");
Add an If judgment
if (Stu = = null) {
Hrequest.getrequestdispatcher ("index.jsp"). Forward (request, response);
}
Chain.dofilter (Request,response);
}
public void init (Filterconfig filterconfig) throws Servletexception {
}
}
Settings in Web. xml
<!--Method 2: Use the filter Interceptor--
<filter>
<filter-name>isLoginFilter</filter-name>
<filter-class>filter.isLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>isLoginFilter</filter-name>
You can choose to describe the corresponding path as needed.
<url-pattern>/*</url-pattern>
</filter-mapping>
User not logged in JSP to prevent other links from accessing