在没有使用spring安全性的情况下,在spring mvc中将会话超时页面重定向到登录页面

时间:2014-04-21 17:49:57

标签: java spring spring-mvc spring-security

使用Spring Security很容易。但是,如果我没有使用Spring Security并希望将用户重定向到登录页面,并在Spring MVC中显示“Session Expired”消息,该怎么办。

Spring有没有具体方法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

是的,您可以使用以下代码段。尝试将此行包含在页面的标题中。并根据用户会话对象替换User属性。

HttpSession session = request.getSession("User");
if(session != null && !session.isNew()) {
   //do something here
} else {
    response.sendRedirect("/redirect_the_page.jsp");
}

答案 1 :(得分:1)

终于解决了。

我在web.xml中添加了过滤器。

 <filter>
    <filter-name>SessionFilter</filter-name>
    <filter-class>
        com.java.util.SessionFilter
    </filter-class>
    <init-param>
        <param-name>avoid-urls</param-name>
        <param-value>/firstPage.htm</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SessionFilter</filter-name>
    <url-pattern>*.htm</url-pattern>
</filter-mapping>

然后创建了一个Filter类

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    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.http.HttpSession;

    public class SessionFilter implements Filter {

private ArrayList<String> urlList;

public void destroy() {
}

public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getServletPath();
    boolean allowedRequest = false;
    if (urlList.contains(url)) {
        allowedRequest = true;
    }

    if (!allowedRequest) {
        HttpSession session = request.getSession(false);
        if (null == session) {
            response.sendRedirect("startup.jsp");
        } else {
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }
}

public void init(FilterConfig config) throws ServletException {
    String urls = config.getInitParameter("avoid-urls");
    StringTokenizer token = new StringTokenizer(urls, ",");
    urlList = new ArrayList<String>();
    while (token.hasMoreTokens()) {
        urlList.add(token.nextToken());

    }
}
}

注意我执行了这一行&#34; chain.doFilter(request,response);&#34;仅当会话处于活动状态时否则它会给出异常&#34; java.lang.IllegalStateException:在提交响应后无法转发&#34;