Post

반응형

18.10.20_TIL


오늘 한 일


  • JSP Cookie, Session, 예외페이지, 자바빈
  • 알고리즘 문제 풀이(SwapFunction 만들기)

오늘 느낀 점


  • markdown 문법이 틀려서 적용안되는 걸 확인했고 수정했다.

내일 할 일 (계획)


  • git + hexo 찾아보자
  • JSP 공부하기
  • 알고리즘 문제 풀이


반응형

'이전게시판 > TIL' 카테고리의 다른 글

2018.12.11_ TIL  (0) 2018.12.12
2018.12.10_TIL  (0) 2018.12.10
2018.12.08_TIL  (0) 2018.12.08
2018.12.07_TIL  (0) 2018.12.08
18.10.20_TIL  (0) 2018.10.20
18.10.19_TIL  (0) 2018.10.19
18.10.18_TIL  (0) 2018.10.18
18.10.17_TIL  (0) 2018.10.17

Post

반응형

JSP 쿠키, Session, 예외 페이지, 자바빈


JSP 쿠키


  • client <-> server 은 request, respone 후 연결을 끊는다.(http의 특징)
  • 연결이 끊겼을 때 어떤 정보를 유지하기 위해서 쿠키 사용.
  • 예를들어 로그인 후 다른 페이지로 이동하면, 로그인 정보를 가지고 있어야 한다. 이 때 쿠키를 사용.
  • 서버에서 쿠키를 생성한 후 클라이언트가 쿠키 정보를 저장.
  • 쿠키는 보안상의 문제가 있기 때문에(text파일로 id, pass 저장) 점점 사용하지 않음.

JSP 쿠키 함수


  • setMaxAge() : 쿠키 저장시간 설정(초단위)
  • setPath() : 쿠키 유효 디렉터리 설정(잘 쓰이지 않는다고 함)
  • setValue() : 쿠키 값 설정
  • setVersion() : 쿠키 버전 설정

JSP 쿠키 생성


  • Cookie cookie = new Cookie("CookieName", CookieValue");
  • Cookie class로 쿠키 생성
  • Cookie class의 첫번째 인자는 쿠키 이름, 두번째 인자는 쿠키 값이다. 
  • 쿠키 유지 시간 설정
    • cookie.setMaxAge(60*60); // 1시간
  • 응답객체에 쿠키 저장
    • response.addCookie(cookie);

JSPExample.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie cookie = new Cookie("name""value");
cookie.setMaxAge(60*60); // 1 hour
response.addCookie(cookie);
%>
<a herf="CookieEx.jsp">cookie get</a>
</body>
</html>
cs


JSP 쿠키 정보 Client 출력


  • Cookie[] cookies = request.getCookies();
  • request 객체로 Cookie 정보를 가져온다.
  • cookies[i].getName(), cookies[i].getValue() 로 Cookies 이름, 값을 알 수 있다.

CookieEx.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(int i =0; i <cookies.length++i)
{
       String str = cookies[i].getName();
       if(str.equals("name"))
       {
              out.println("cookies["+i+"]name:"+ cookies[i].getName()+"<br />");
              out.println("cookies["+i+"]value:"+ cookies[i].getValue()+"<br />");
       }
}
%>
<a href="CookieDel.jsp">쿠키확인</a>
</body>
</html>
cs

JSP 쿠키 삭제


  • request 객체에서 Cookies 정보를 가져온다.
  • 삭제할 쿠키를 이름으로 찾은 후 쿠키 저장시간을 0으로 초기화해서 쿠키를 지운다.
  • cookies[i].setMaxAge(0)
  • 이 전 페이지로 돌아가면 쿠키 정보를 더 이상 출력하지 않는다.

CookieDel.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length++i)
{
       String str = cookies[i].getName();
       if(str.equals("name"))
       {
              out.println("name:"+cookies[i].getName()+"<br />");
              cookies[i].setMaxAge(0);
              response.addCookie(cookies[i]);
       }
}
%>
</body>
</html>
cs


JSP 쿠키 로그인 예제


  • id, pass 를 입력받아서 로그인이 성공하면 Admin.jsp 페이지로 이동한다.
  • 만약 로그아웃하려면 Cookie 시간을 0으로 설정하면 된다.

login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="SignIn.jsp" method="post">
아이디:<input type="text" name="id" size="10"><br />
비밀번호 : <input type="password" name="pw" size="10"><br />
<input type="submit" value="로그인">
</form>
</body>
</html>
Admin.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
       String id, pw;
%>
<%
       id = request.getParameter("id");
       pw = request.getParameter("pw");
       
       if(id.equals("admin") && pw.equals("1234"))
       {
              Cookie cookie = new Cookie("id", id);
              cookie.setMaxAge(60);
              response.addCookie(cookie);
              response.sendRedirect("Admin.jsp");
       }
       else
       {
              response.sendRedirect("login.html");
       }
%>
</body>

</html>


JSP Session


  • Cookies와 달리 Session은 Server에 저장된다.
  • Cookies는 1.2mb까지 저장할 수 있지만 Session은 제한이 없다.
  • Session은 Client 요청이 들어올 때 자동 생성.
  • Cookies는 요즘 사용못하게 막는 경우가 있어 Session이 많이 사용된다.

Session 메소드


  • setAttribute() : 세션에 데이터 저장.
  • getAttribute() : 세션에서 데이터 얻음.
  • getAttributeNames() : 세션의 모든 데이터의 이름을 얻음.
  • getId() : 자동 생성된 세션의 유니크한 아이디를 얻음.
  • isNew() : 세션이 최초 생성되었는지, 이전에 생성된건지 구분
  • getMaxInactiveInterval() : Session의 유효시간을 얻음. 가장 최근 요청 시점을 기준으로 카운트.
  • D:\apache-tomcat-8.5.34\conf\web.xml web.xml에 Session 유효시간이 적혀있음.
  • 30분이 설정되어있음.

<session-config>

    <session-timeout>30</session-timeout>
</session-config>
  • removeAttribute() : 세션에서 특정 데이터 제거.
  • Invalidate() : 세션의 모든 데이터를 삭제.
login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="SignIn.jsp" method="post">
아이디:<input type="text" name="id" size="10"><br />
비밀번호 : <input type="password" name="pw" size="10"><br />
<input type="submit" value="로그인">
</form>
</body>
</html>
cs


SignIn.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
       String id, pw;
%>
<%
       id = request.getParameter("id");
       pw = request.getParameter("pw");
       
       if(id.equals("admin"&& pw.equals("1234"))
       {
              session.setAttribute("id", id);
              response.sendRedirect("Admin.jsp");
       }
       else
       {
              response.sendRedirect("login.html");
       }
%>
</body>
</html>
cs


Admin.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
Enumeration<String> enumeration = session.getAttributeNames();
while(enumeration.hasMoreElements())
{
       String sName = enumeration.nextElement().toString();
       String sValue = (String)session.getAttribute(sName);
       
       if(sValue.equals("admin"))
       {
              out.println(sValue+"님 안녕하세요"+"<br/>");
       }
       
}
%>
</body>
</html>
cs


JSP 예외 페이지


  • 기본 예외 페이지는 tomcat 페이지이므로 친숙한 디자인의 예외 페이지가 필요하다.

age지시자를 이용한 예외처리


  • 현재 Page에서 error 발생 시 errorPage.jsp 로 이동하라.
    • <%@ page errorPage="errorPage.jsp" %>
  • erroPage.jsp 에러페이지에서 page지시자를 통해 에러페이지라는 것을 명시.
    • Defaul가 false이므로 반드시 명시.
    • <%@ page isErrorPage="true"%>
  • 에러 Status 값을 준다.
    • 200은 정상적인 페이지라는 뜻. 에러 표시 페이지는 정상이므로 200으로 setting.
    • <% response.setStatus(200); %>
  • 에러 메시지 출력
    • <%= exception.getMessage() %>
ExceptionEx.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="Error.jsp" %>>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
int i = 40/0;
%>
</body>
</html>
cs


Error.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%@ page isErrorPage="true" %>
    <% response.setStatus(200); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
Error가 발생했습니다<br>
<%= exception.getMessage() %>
</body>
</html>
cs


web.xml 파일을 이용한 예외 처리


  • web.xml 파일로 예외처리를 할 수 있다.
  • web.xml 파일 위치
  • Project\WebContent\WEB-INF\web.xml
  • <error-page> 안에 에러페이지 정보를 기술한다.
  • <error-page> 안에 errorcode, 이동할 예외처리 페이지를 적는다
1
2
3
4
<error-page>
    <error-code>500</error-code>
    <location>/error500.jsp</location>
</error-page>
cs


JSP 자바 빈


  • JAVA언어의 속성, 메소드로 이루어진 클래스.
  • JSP페이지 안에서 액션태크를 사용해 빈을 사용.
  • 자바 빈이란 jsp에서 Java 객체를 가져와 쓸 수 있도록 해주는 것.

자바 빈 액션 태그


  • 빈을 사용한다는 선언
  • scope value
    • page일 때 : 생성된 페이지 내에서만 사용.
    • request일 때 : 요청된 페이지 내에서 사용.
    • session일 때 : 웹브라우저의 생명주기와 동일하게 사용 가능.
    • application일 때 : 웹 어플리케이션 생명주기와 동일하게 사용 가능.
    • <jsp:useBean id = "자바빈 name" class="pakage.classname" scope="area" />
  • 객체 값 설정
  • player 객체에 id속성 값을 1로 설정.
<jsp:setProperty name="player" property="id" value="1"/>

  • 객체 값 가져오기
<jsp:getProperty name="player" property="id"/><br />


BeanEx,.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="player" class="w.Player" scope="page" />
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<jsp:setProperty name="player" property="id" value="1"/>
<jsp:setProperty name="player" property="name" value="gosu" />
<jsp:setProperty name="player" property="level" value="20" />
id:<jsp:getProperty name="player" property="id"/><br />
name:<jsp:getProperty name="player" property="name"/><br />
level:<jsp:getProperty name="player" property="level"/><br />
</body>
</html>
cs


Player.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package w;
public class Player {
       private int          id;
       private String       name;
       private int   level;
       
       public Player()
       {
       
       }
       
       public void setId(int _id)
       {
              id = _id;            
       }
       
       public int getId()
       {
              return id;
       }
       
       public void setName(String _name)
       {
              name = _name;
       }
       
       public String getName()
       {
              return name;
       }
       
       public void setlevel(int _level)
       {
              level = _level;            
       }
       
       public int getlevel()
       {
              return level;
       }
}
cs


반응형

'이전게시판 > JSP' 카테고리의 다른 글

JDBC로 OLACLE 접속  (0) 2018.10.22
JSP 태그, request, response, 지시자, 액션태그  (0) 2018.10.20
Servlet 값 초기화, 리스너  (0) 2018.10.20
Servlet Get,Post 동작  (0) 2018.10.19
Servlet 설정, 예제  (0) 2018.10.18
JSP 설치, 설정, 실행  (0) 2018.10.18
▲ top