重定向到登录页面而不使用spring security

时间:2013-09-19 08:51:02

标签: spring-mvc

我是Spring和创建Web应用程序的新手,  我想在用户未经过身份验证且不使用spring security.xml时重定向到登录页面? 是否可以进行会话管理?

2 个答案:

答案 0 :(得分:1)

一种简单的方法是使用'HandlerInterceptorAdapator':

public class CheckUserInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private UserSession userSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws IOException {

        if (request.getServletPath().equals("/login.htm")) {
            return true;
        }

        String username = userSession.getUsername();

        // If the username has not been set by the login controller    
        if (username != null) {
            return true;
        } else {
            response.sendRedirect("login.htm");
            return false;
        }
    }

}

在这种情况下,您需要在Spring XML文件中声明拦截器:

<mvc:interceptors>
    <bean class="fr.unilim.msi.dad.web.mvc.CheckUserInterceptor" />
</mvc:interceptors>

另一种方法,例如,如果您的Spring MVC控制器未配置为处理所有请求,则在servlet级别使用过滤器:

public class AccessControlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest) request).getSession(true);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            String urlRoot = ((HttpServletRequest) request).getContextPath();
            ((HttpServletResponse)response).sendRedirect(urlRoot + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}

答案 1 :(得分:0)

我猜您可以在登录控制器中执行以下操作:

if(isUserAuthenticated())
{
    return "home";
}
else
{ 
    session.invalidate();
    return "redirect:login";
}