在做一个网站的时候,用户登录后,一个servlet中可以用session.isNew()来判断当前页面的session是否Timeout了,而当用户没有通过登录页面而直接通过在地址栏输入url去访问一个页面是,此时也可以通过session.isNew()来判断用户是否非法访问(即直接输入url访问,没有登录!)现在有个问题,我想要的结果是当页面的session Timeout后,我想弹到一个“session Timeout”的界面,而当用户非法访问的时候再弹到另一个“非法访问”的界面!有什么办法来解决这个问题?(我都是用的session.isNew()来判断的,能不能有其他方法来判断呢?)
在sessionDestroyed方法中做.
import javax.servlet.http.*;
import javax.servlet.*;import java.io.IOException;public class UserLoginFilter implements Filter {
protected FilterConfig filterConfig = null; protected String forwardPath = null;
private static boolean timeOut = false;
public void destroy() {
this.filterConfig = null;
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
String requesturi = httpServletRequest.getRequestURI();
HttpSession session = httpServletRequest.getSession(false);
if (session == null
&& !requesturi.endsWith("/logon.do")
&& !requesturi.endsWith("/logoff.do")
&& !requesturi.endsWith("/mainMenu.jsp")
&& !requesturi.endsWith(httpServletRequest.getContextPath()
+ "/")) {
httpServletResponse.sendRedirect(httpServletRequest
.getContextPath()
+ "/logon.do");
timeOut = true;
return;
}
chain.doFilter(request, response);
} public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.forwardPath = filterConfig.getInitParameter("forwardpath");
} public static boolean getTimeOut(){
return timeOut;
} public static void setTimeOut (boolean newTimeOut){
timeOut = newTimeOut;
}
}
web.xml文件中对filter的调用
<!-- Set Login Filter -->
<filter>
<filter-name>Login Filter</filter-name>
<filter-class>de.rzbw.webapp.UserLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>其中,TimeOut变量是用来在跳转时候判断是否是由于session timeout的跳转,相应输出合适的提示信息希望对楼主有帮助
两个类.一个负责登陆,一个是过滤器.
登陆的类里,当一个用户登陆时,
...
String currUser=(String)request.getSession().getAttribute("currUser");
if(currUser==null){
request.getSession().setAttribute("currUser", "currUser");
}else{
response.sendRedirect(contextPath + "/error.jsp");
}
....
在过滤器类里
public void doFilter(ServletRequest req, ServletResponse res, FilterChain c) throws IOException, ServletException {
// TODO Auto-generated method stub
if (((HttpServletRequest) req).getSession().getAttribute("currUser") == null) {
req.getRequestDispatcher("/login.jsp").forward(req, res);
} else {
c.doFilter(req, res);
}
}
web.xml文件中对过滤器的调用
<filter>
<filter-name>CheckLogin</filter-name>
<init-param>
<param-name>excludePages</param-name>
<param-value>/:/login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CheckLogin</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>