帮我创建登录表单

时间:2011-05-20 11:17:12

标签: cookies

我是网络应用程序的新手。可以帮助我只使用cookie创建登录身份验证。我不想要会话示例..

1 个答案:

答案 0 :(得分:1)

编写一个过滤器,用于检查具有所需授权的cookie,如果它没有创建cookie并将其添加到响应中。从下次开始,查找cookie,如果有权限,则允许访问该页面。

package myweb;

import java.io.IOException;

import javax.servlet。*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

/ **  * @author Ramesh PVK  * @version $ Revision $,$ Date $,$ Author $  * @since 2011年5月20日  * / 公共类MyFilter         实现过滤器 {

public void init(FilterConfig filterConfig) throws ServletException
{

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException
{
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    Cookie[] cookies = httpRequest.getCookies();
    Cookie authCooike = getCookieWithName(cookies, "authCookie");
    if (authCooike == null) {
        servletRequest.getRequestDispatcher("/loginPage").forward(servletRequest, servletResponse);
    } else {
        if (validateCookie(authCooike)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.getRequestDispatcher("/loginPage").forward(servletRequest, servletResponse);
        }
    }
}

private boolean validateCookie(Cookie authCooike)
{
    //write logic for validation
    return true;
}

private Cookie getCookieWithName(Cookie[] cookies, String s)
{
    for (Cookie cooky : cookies) {
        if (cooky.getName().equals(s)) {
            return cooky;
        }
    }
    return null;
}

public void destroy()
{

}

}

由于