본문 바로가기

Java, Spring/08일

8일차 3 - session

session

servlet 사용할 경우 httpsession 가져다 쓰면 되고

jsp에서 쓸 경우에는 내장객체에서 아주 편하게 쓸 수가 있어.

session.getAttribute

session.setAttribute

 

session은 서버단에 저장하는 것이기 때문에 커다란 데이터같은거 저장하며 안되겠지.

주로 id에 대한 정보, 인증정보, 접속정보 같은 거 저장하지.

 

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>세션 테스트 입니다.</title>
</head>
<body>
<h1>세션 테스트</h1>
<a href="makesession.jsp">[세션값 생성]</a>
<a href="removeid.jsp">[id 세션값 삭제]</a>
<a href="removepw.jsp">[pw 세션값 삭제]</a>
<a href="invalidate.jsp">[세션값 초기화]</a>
<hr/>
<h2>
<%=(session.getAttribute("id") == null) ? 
		"id값이 없습니다.":
		"id : " + session.getAttribute("id")%><br/>
<%=(session.getAttribute("pw") == null) ? 
		"pw값이 없습니다.":
		"pw : " + session.getAttribute("pw")%><br/>
</h2>
</body>
</html>

처음 실행하면 session이 안만들어졌으니까 null로 나오지.

 

session 생성

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.setMaxInactiveInterval(10); // 초단위(마지막접속 후)
	session.setAttribute("id", "서태지");
	session.setAttribute("pw", "taiji");
%>
<!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>
<% response.sendRedirect("sessionApp.jsp"); %>
</body>
</html>

 

10초 후에 reflesh하면 다시 null이겠지.

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% session.removeAttribute("id"); %>
<!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>
location.href="sessionApp.jsp";
</script>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% session.removeAttribute("pw"); %>
<!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>
location.href="sessionApp.jsp";
</script>
</body>
</html>

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% session.invalidate(); %>
<!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("세션 정보가 \n초기화 되었습니다.");
location.href="sessionApp.jsp";
</script>
</body>

 

loginform.jsp

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = null;
	String name = null;
	
%>
<!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 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" /></td>
	</tr>
	<tr>
		<td>PW</td>
		<td><input type="password" name="pass" /></td>
	</tr>
	<tr>
		<td colspan="2">
			<input type="submit" value="로그인" />
			<input type="reset" value="재입력" />
		</td>
	</tr>
</table>
</form>
</body>
</html>

<body onload="javascript:document.loginform.id.focus();">

  • onload tag : body tag안에 들어있을 때 body에 있는 모든 내용이 로드가 되고나면 자동으로 자바스크립트 실행

javascript  : JAVA는 아니고 그냥 클라이언트 브라우저 언어야. 네스케이프에서 만들었는데 망해서 크게 발전하지는 않았지만 최근들어 많이 발전하고 있어.. JQuery 퍼지기 시작한 이후로 JQuery와 함께.. 또 최근에는 Node.js라고 서버단에서 동작도 시킬 수 있어.  그래서 점점 중요성이 높아져.

앞으로 뷰단을 Node.js로 많이 사용할 듯..

참고서적 http://kangcom.com/sub/view.asp?sku=201202070001&mcd=571 http://kangcom.com/sub/view.asp?sku=201202110002&mcd=571

 

document.loginform.id.focus();

  • document : 현재문서. 언제나 접근할 때는 문서가 제일 먼저야
  • loginform :  폼 이름이야 그러니까 폼에 이름을 줘야해 (<form name="loginform" ..)
  • id 에 focus를 준다는거지..

 

id와 pw입력하면 이걸 session에 집어넣고 다시 이 창에 오면 로그인 되어있으면 로그인되어있다고 메세지 주고 아니면 로그인폼을 보여주게 해보자. 간단하게.

테이블부터 만들고

CREATE TABLE users (	
	id 			varchar2(30) 	not null, 	
	password 	varchar2(30) 	not null, 		--비밀번호
	name 		varchar2(30) 	not null, 		--작성자
	lev 	number 		default 0
);

insert into users values ('aaaa', 'qwer', '신남현', 1);

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = null;
	String name = null;
	
	
	if(session.getAttribute("id") != null) {
		id = (String) session.getAttribute("id");
		name = (String)session.getAttribute("name");
	}
%>
<!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" /></td>
	</tr>
	<tr>
		<td>PW</td>
		<td><input type="password" name="pass" /></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="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String id = request.getParameter("id");
	String pw = request.getParameter("pass");
	
	//파일분할안하고 그냥 간단히
	Connection cn = null;
	Statement 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='"+id+"' AND password='"+pw+"'";
	
	try {
		Class.forName(driver);
		cn = DriverManager.getConnection(url, "oraclejava", "oraclejava");
		st = cn.createStatement();
		rs = st.executeQuery(sql);
		
		if(rs.next()) {
			session.setAttribute("id", id);
			session.setAttribute("name", rs.getString("name"));
			
			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"%>
<% session.invalidate(); %>
<!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>
location.href="loginform.jsp";
</script>
</body>
</html>

그런데

아이디에다가 [aaaa' –] 이런 식으로 뒤를 주석처리 해버리면 로그인 되버리지..

그래서 PreparedStatement를 사용하는게 좋다구..

 
<%@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");
	
	//파일분할안하고 그냥 간단히
	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"));
			
			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>

 

그래서 dynamic query하지말고 오라클바인드변수를 이용한 parameter query를 사용하는게 좋다구.

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

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