j2ee에서 쿠키 자동 로그인 실현

14584 단어 cookie자동 로그인
.
1. 사용하는 상수

package com.hydom.util;

public final class CommonConstants {

	//    session   
	public final static String SESSION_USER = "session_user";
	
	/**        cookie       */
	public final static String BROWSER_COOKIE_EMAIL = "HKPhotoUserEmail";
	
	/**        cookie       */
	public final static String BROWSER_COOKIE_PASSWORD = "HKPhotoUserPassword";
	
	/**        cookie     15  */
	public final static int BROWSER_COOKIE_MAX_AGE = 15*24*60*60;
	
	/**        cookie         */
	public final static String BROWSER_COOKIE_AUTO_STATUS_NAME = "HKPhotoAutoLoginStatus";
	
	/**        cookie       */
	public final static String BROWSER_COOKIE_LOGIN_OUT_NAME = "HKPhotoLoginOut";
}

2. 필터

package com.hydom.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
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;

import com.hydom.entity.User;
import com.hydom.service.IUserService;
import com.hydom.util.CommonConstants;
import com.hydom.util.pico.PicoContainer;

/**
 *  :    session    user,       cookie            <BR>
 *          user  session <BR>
 *         doFilter()<BR>
 * 
 * @author [email protected]<BR>
 * @date 2011-9-22<BR>
 * @version 1.0 <BR>
 * 
 */
public class CookieLoginFilter extends BaseFilter {
	//        

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

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

		Object object = request.getSession().getAttribute(
				CommonConstants.SESSION_USER);

		User cookieUser = null;
		String email = null;
		String password = null;
		String autoStatus = null;

		if (object == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
//				System.out.println("cookies.length=" + cookies.length);
				for (int i = 0; i < cookies.length; i++) {
					Cookie cookie = cookies[i];

					//   Cookie        "HKPhotoUserEmail"
					if (CommonConstants.BROWSER_COOKIE_EMAIL.equals(cookie
							.getName())) {
						email = cookie.getValue().trim();
					}

					//   Cookie        "HKPhotoUserPassword"
					if (CommonConstants.BROWSER_COOKIE_PASSWORD.equals(cookie
							.getName())) {
						password = cookie.getValue().trim();
					}

					//   Cookie            "HKPhotoAutoLoginStatus"
					if (CommonConstants.BROWSER_COOKIE_AUTO_STATUS_NAME
							.equals(cookie.getName())) {
						autoStatus = cookie.getValue().trim();
					}
				}
				if (autoStatus!=null&&autoStatus.equals("1")) {
					if (email != null && password != null && email.length() > 0
							&& password.length() > 0) {
						cookieUser = new User();
						cookieUser.setEmail(email);
						cookieUser.setPassword(password);

//						System.out.println("email=" + cookieUser.getEmail());
//						System.out.println("password="
//								+ cookieUser.getPassword());

						IUserService userService = PicoContainer.PICO
								.getComponent(IUserService.class);
						cookieUser = userService.validLogin(cookieUser);

						if (cookieUser != null) {
							//   user   session 
							request.getSession().setAttribute(
									CommonConstants.SESSION_USER, cookieUser);
						} else {
							chain.doFilter(request, response);
						}
					} else {
						chain.doFilter(request, response);
					}
				} else {
					chain.doFilter(request, response);
				}

			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

}


3.web.xml 설정 쿠키 로그인 필터

	<!-- cookie          -->
	<filter>
		<filter-name>cookie-login-filter</filter-name>
		<filter-class>com.hydom.filter.CookieLoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>cookie-login-filter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

4. 사용자가 로그인한 경우

public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private String email = null;//     
	private String password = null;//     
	private boolean autoLoginStatus = false;

	public boolean getAutoLoginStatus() {
		return autoLoginStatus;
	}

	public void setAutoLoginStatus(boolean autoLoginStatus) {
		this.autoLoginStatus = autoLoginStatus;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	//        
	private IUserService userService = PicoContainer.PICO
			.getComponent(IUserService.class);
        @Override
	public String execute() throws Exception {
		try {
			//       
			String message = checkAndFilterUsersInfo();
			;
			User user = null;
			if (message == null) {
				user = new User();
				user.setEmail(this.email);
				user.setPassword(this.password);
				user = userService.validLogin(user);
			}

			//     
			StringBuilder msg = new StringBuilder();
			msg.append("{");
			if (user != null) {
				super.getSession().setAttribute(CommonConstants.SESSION_USER,
						user);
				msg.append("msg:'success'").append(",");
				msg.append("userName:'").append(user.getUserName()).append("'");

				if (autoLoginStatus) {		
					//                              
					addCookieingUserToResponse(user);
				}else{
					removeCookieingUserInResponse();
				}

			} else {
				if (message == null) {
					msg.append("msg:'        '");
				} else {
					msg.append("msg:'").append(message).append("'");
				}
			}

			msg.append("}");
			ajaxJson(msg.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 *                 
	 * 
	 * @param cookieingUser
	 */
	private void addCookieingUserToResponse(User cookieingUser) {

		//   cookie     
		Cookie cookieEmail = new Cookie(CommonConstants.BROWSER_COOKIE_EMAIL,
				cookieingUser.getEmail());
		cookieEmail.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		cookieEmail.setPath(super.getRequest().getContextPath());
		super.getResponse().addCookie(cookieEmail);

		//   cookie     
		Cookie cookiePassword = new Cookie(
				CommonConstants.BROWSER_COOKIE_PASSWORD, cookieingUser
						.getPassword());	
		cookiePassword.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		cookiePassword.setPath(super.getRequest().getContextPath());
		super.getResponse().addCookie(cookiePassword);
		
		
		//   cookie         
		Cookie autoLoginStatusCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_AUTO_STATUS_NAME,
				"1");
		autoLoginStatusCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		autoLoginStatusCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(autoLoginStatusCookie);
		
		//   cookie     
		Cookie loginOutCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_LOGIN_OUT_NAME,
				"0");
		loginOutCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		loginOutCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(loginOutCookie);
	}
	
	public void removeCookieingUserInResponse(){
		//   cookie     
		Cookie cookieEmail = new Cookie(CommonConstants.BROWSER_COOKIE_EMAIL,
				null);
		cookieEmail.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		cookieEmail.setPath(super.getRequest().getContextPath());
		super.getResponse().addCookie(cookieEmail);

		//   cookie     
		Cookie cookiePassword = new Cookie(
				CommonConstants.BROWSER_COOKIE_PASSWORD, null);	
		cookiePassword.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		cookiePassword.setPath(super.getRequest().getContextPath());
		super.getResponse().addCookie(cookiePassword);
		
		
		//   cookie         
		Cookie autoLoginStatusCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_AUTO_STATUS_NAME,
				"0");
		autoLoginStatusCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		autoLoginStatusCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(autoLoginStatusCookie);
		
		//   cookie     
		Cookie loginOutCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_LOGIN_OUT_NAME,
				"0");
		loginOutCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		loginOutCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(loginOutCookie);
	}
}

5. 종료

public class LogOutAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	//     
	@Override
	public String execute() throws Exception {
		super.getSession().removeAttribute(CommonConstants.SESSION_USER);
		
		//   cookie     
		Cookie loginOutCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_LOGIN_OUT_NAME,
				"1");
		loginOutCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		loginOutCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(loginOutCookie);
		
		//   cookie         
		Cookie autoLoginStatusCookie = new Cookie(
				CommonConstants.BROWSER_COOKIE_AUTO_STATUS_NAME,
				"0");
		autoLoginStatusCookie
				.setMaxAge(CommonConstants.BROWSER_COOKIE_MAX_AGE);
		autoLoginStatusCookie.setPath(super.getRequest()
				.getContextPath());
		super.getResponse().addCookie(autoLoginStatusCookie);
		
		PrintWriter out = super.getResponse().getWriter();
		out.close();
		return null;
	}

}

6.jsp 로그인 페이지

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script src="<%=base%>js/common/jquery.js"></script>
<script src="<%=base%>js/common/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	var email=$.cookie('<%=CommonConstants.BROWSER_COOKIE_EMAIL%>');
	var password=$.cookie('<%=CommonConstants.BROWSER_COOKIE_PASSWORD%>');
	var autoStatus=$.cookie('<%=CommonConstants.BROWSER_COOKIE_AUTO_STATUS_NAME%>');
	var loginOut=$.cookie('<%=CommonConstants.BROWSER_COOKIE_LOGIN_OUT_NAME%>');
	
	if(autoStatus=="0"&&loginOut=="1"){
		$("#newemail").attr("value",email.replace(new RegExp('"',"gm"),""));
		$("#newpassword").attr("value",password.replace(new RegExp('"',"gm"),""));
	}

});
</script>

<div class="hidden" id="smallLay">
              <span><a href="javascript:closedialog()" onFocus="this.blur()" > <img src="<%=base%>images/cose.gif" /></a></span>
              <p class="logo"><img onerror="this.src='<%=base%>images/logo.jpg'" src="<%=base%><%=logo.getSmallPath()%>" /></p>
              <div class="user">
                  <ul>
                      <li><b>  :</b><input type="text" id="newemail" onblur="checkAdminEmail(this.value)" value=""/></li>
                      <li><b>  :</b><input type="password" id="newpassword" value=""/></li>
                  </ul>
                  <samp><input name="autoLoginStatus" id="autoLoginStatus" checked="checked" type="checkbox" value=""  class="check"/><d>      </d> <a href="javascript:startRegister()" style="color:red;text-decoration: underline;"">    </a></samp>
                  <p><input type="button" class="land" onclick="gologin()"  value="   "/></p>
                  <samp><b>          :</b><img src="<%=base%>images/f.gif" onclick="tofacelogin()"/><u></u><img src="<%=base%>images/sina.gif" /></samp>
              </div>
</div> 

좋은 웹페이지 즐겨찾기