본문 바로가기

Java, Spring/08일

8일차 5 - Cookie (2)

cookie 계속..

 

로그인에서

id저장 체크하면 다음 로그인시 id남아있고 체크박스에 체크되어있게 하기

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = request.getParameter("id");
	String pw = request.getParameter("pass");	
	int setid = 0;
	if(request.getParameter("setid") != null)
		setid = Integer.parseInt(request.getParameter("setid"));	
	
	//파일분할안하고 그냥 간단히
	Connection cn = null;
	PreparedStatement st = null;
	ResultSet rs = null;
	
	String driver = "oracle.jdbc.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	
	String sql = "SELECT name " +
				"FROM users " +
				"WHERE id=? AND password=? ";
	
	try {
		Class.forName(driver);
		cn = DriverManager.getConnection(url, "oraclejava", "oraclejava");
		st = cn.prepareStatement(sql);
		st.setString(1,id);
		st.setString(2,pw);
		rs = st.executeQuery();
		
		if(rs.next()) {
			session.setAttribute("id", id);
			session.setAttribute("name", rs.getString("name"));
			
			Cookie cookie = new Cookie("setid", id);
			if (setid == 1){
				cookie.setMaxAge(60*60*24*30);	//한달
			} else {
				cookie.setMaxAge(0);	//쿠키삭제
			}
			response.addCookie(cookie);
			
			response.sendRedirect("loginform.jsp");
			return;
		}
		
	} catch (Exception e) {
		e.printStackTrace();		
	} finally {
		if (rs != null ) try {rs.close();} catch(Exception e){}
		if (st != null ) try {st.close();} catch(Exception e){}
		if (cn != null ) try {cn.close();} catch(Exception e){}
	}	
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
		"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
alert('id 혹은 pw가 틀립니다.');
location.href='loginform.jsp';
</script>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = null;
	String name = null;
	String setid="";
	
	if(session.getAttribute("id") != null) {
		id = (String) session.getAttribute("id");
		name = (String)session.getAttribute("name");
	}
	
	Cookie[] cookies = request.getCookies();
	if (cookies != null){
		int cook_len = cookies.length;
		for(int i=0; i<cook_len; i++){
			if(cookies[i].getName().equals("setid")){
				setid = cookies[i].getValue();
			}
		}
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<% if (id == null || id == "") { %>
<body onload="javascript:document.loginform.id.focus();">
<form name="loginform" action="loginpro.jsp" method="post">
<table>
	<tr>
		<td>ID</td>
		<td><input type="text" name="id" value="<%=setid %>" /></td>
	</tr>
	<tr>
		<td>PW</td>
		<td><input type="password" name="pass" /></td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="checkbox" name="setid" value="1"
				<%if(setid != "") { %> checked <% } %> 
			/> id 저장 
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="submit" value="로그인" />
			<input type="reset" value="재입력" />
		</td>
	</tr>
</table>
</form>
</body>
<% } else { %>
<body>
<h1><%=name %>님이 로그인 되었습니다.</h1><br/>
<a href="logout.jsp">로그아웃</a>
</body>
<% }  %>
</html>

이제 체크한 상태에서 로그아웃해도 아이디값은 남아있지..

 

 

그런데..

조금 편하게 자바클래스를 만들어서 사용해보자..

Cooker 만들어 써보자.

package cookie;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class Cooker {
	//쿠키를 저장할 맵(키값-이름,value값-쿠키)
	private Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();

	//생성자 넘겨받은 request객체에서 쿠키를 읽어 맵에 저장해 놔..
	public Cooker(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		
		if(cookies!=null){
			for(int i=0; i<cookies.length; i++){
				cookieMap.put(cookies[i].getName(), cookies[i]);
			}
		}
	}
	
	//Cookie가 존재하는지 
	public boolean exist(String name){
		return cookieMap.get(name) != null;
	}
	
	//실제 쿠키타입을 리턴해주는 메서드
	public Cookie getCookie(String name){
		return cookieMap.get(name);
	}
	
	//쿠키의 값을 꺼내는..
	public String getValue(String name) throws UnsupportedEncodingException{
		Cookie cookie = cookieMap.get(name);
		
		if(cookie == null) return null;
		else return URLDecoder.decode(cookie.getValue(), "UTF-8");
	}
	
	//쿠키생성 (static이니 아무데서나 객체생성없이 바로 쓸 수 있지)
	public static Cookie createCookie(String name, String value) 
			throws UnsupportedEncodingException{
		return new Cookie(name, URLEncoder.encode(value, "UTF-8"));
	}

	//쿠키생성
	public static Cookie create(String name, String value, int maxAge) 
			throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
		cookie.setMaxAge(maxAge);
		return cookie;
	}
}

 

이제 이 편하게 Cooker를 사용해보자.

<%@page import="cookie.Cooker"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = null;
	String name = null;
	String setid="";
	
	if(session.getAttribute("id") != null) {
		id = (String) session.getAttribute("id");
		name = (String)session.getAttribute("name");
	}
	
	Cooker cooker = new Cooker(request);
	if(cooker.exist("setid")){
		setid = cooker.getValue("setid");
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<% if (id == null || id == "") { %>
<body onload="javascript:document.loginform.id.focus();">
<form name="loginform" action="loginpro.jsp" method="post">
<table>
	<tr>
		<td>ID</td>
		<td><input type="text" name="id" value="<%=setid %>" /></td>
	</tr>
	<tr>
		<td>PW</td>
		<td><input type="password" name="pass" /></td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="checkbox" name="setid" value="1"
				<%if(setid != "") { %> checked <% } %> 
			/> id 저장 
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="submit" value="로그인" />
			<input type="reset" value="재입력" />
		</td>
	</tr>
</table>
</form>
</body>
<% } else { %>
<body>
<h1><%=name %>님이 로그인 되었습니다.</h1><br/>
<a href="logout.jsp">로그아웃</a>
</body>
<% }  %>
</html>

<%@page import="cookie.Cooker"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = request.getParameter("id");
	String pw = request.getParameter("pass");	
	int setid = 0;
	if(request.getParameter("setid") != null)
		setid = Integer.parseInt(request.getParameter("setid"));	
	
	//파일분할안하고 그냥 간단히
	Connection cn = null;
	PreparedStatement st = null;
	ResultSet rs = null;
	
	String driver = "oracle.jdbc.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	
	String sql = "SELECT name " +
				"FROM users " +
				"WHERE id=? AND password=? ";
	
	try {
		Class.forName(driver);
		cn = DriverManager.getConnection(url, "oraclejava", "oraclejava");
		st = cn.prepareStatement(sql);
		st.setString(1,id);
		st.setString(2,pw);
		rs = st.executeQuery();
		
		if(rs.next()) {
			session.setAttribute("id", id);
			session.setAttribute("name", rs.getString("name"));
			
			if(setid == 1)
				response.addCookie(Cooker.createCookie("setid", id,60*60*24*30 ));
			else
				response.addCookie(Cooker.createCookie("setid", id, 0));
			
			response.sendRedirect("loginform.jsp");
			return;
		}
		
	} catch (Exception e) {
		e.printStackTrace();		
	} finally {
		if (rs != null ) try {rs.close();} catch(Exception e){}
		if (st != null ) try {st.close();} catch(Exception e){}
		if (cn != null ) try {cn.close();} catch(Exception e){}
	}	
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
		"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
alert('id 혹은 pw가 틀립니다.');
location.href='loginform.jsp';
</script>
</body>
</html>

간단해졌지?

 

 

 

 

'Java, Spring > 08일' 카테고리의 다른 글

8일차 2 - 화면분할(파일분할)  (0) 2012.09.20
8일차 3 - session  (0) 2012.09.20
8일차 4 - Cookie (1)  (0) 2012.09.20
8일차 6-2 - login Model2로 만들기 (1)  (0) 2012.09.20
8일차 7 - login Model2로 만들기 (2)  (0) 2012.09.20