cookie登录功能实现

网站常用的记住我,或是一周内自动登录,这些功能一般都是是用cookie进行登录的!下面对此功能进行分析:


package cookielogin;

import java.io.IOException;

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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieLogin implements Filter {

	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		Cookie username = this.getCookie(req, USERNAME);
		Cookie password = this.getCookie(req, PASSWORD);

		if (null != username && null != password) {

			System.out.println("用户登录");
			// userService.login(username.getValue,password.getValue());
			System.out.println("username:" + username.getValue() + ",password:"
					+ password.getValue());

		} else {
			//保存cookie
			resp.setCharacterEncoding("UTF-8");
			
			Cookie nameCookie = new Cookie(USERNAME, "username");
			
			Cookie passCookie = new Cookie(PASSWORD, "password");

			resp.addCookie(nameCookie);
			resp.addCookie(passCookie);
		}
		chain.doFilter(req, resp);
	}

	public Cookie getCookie(HttpServletRequest request, String cookieName) {

		Cookie[] cookies = request.getCookies();

		if (null == cookies) {
			return null;
		}

		for (Cookie c : cookies) {
			if (c.getName().equals(cookieName)) {
				return c;
			}
		}

		return null;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}

测试时需要在web.xm加入拦截器!

你可能感兴趣的:(工作)