본 포스팅에서는 html, css, javascript를 이용하여 둥근 toggle버튼을 만들고, 버튼의 상태가 변경될 때마다 상태를 출력하는 기능까지 만들어 봅니다. 본 보스팅에 사용되는 기본코드는 w3schools에서 가지고 온 것입니다. w3schools에서는 단순히 css를 이용해서 토글버튼처럼 보이는 것을 만드는 것 까지만 보여주었는데, 저는 그렇게 토글이 될 때마다 자바스크립트를 이용해서 어떤 기능이 실행되는 부분까지 확장해서 포스팅합니다.
이번에는 자바로 1차원 배열을 만들어 보도록 하겠습니다. 자바로 배열을 만드는 방법은 여러 가지가 있습니다. 우선 용어부터 정리하고 가겠습니다. 제가 만든다라고 얘기한 것은 일반적으로 얘기하려고 한 것인데 이는 두 가지 의미를 포함하고 있습니다. 바로 "선언"과 "초기화"입니다. 여기서 "선언"이라는 것은 변수의 이름을 지어주는 것을 얘기하며, "초기화"라는 것은 그 변수에 값을 할당하는 것을 의미합니다. 이 용어들을 머릿속에 넣고 출발하도록 하겠습니다.
배열을 선언하는 방법
자바에서 배열을 선언하는 방법은 아래와 같이 3가지가 있습니다.
publicstaticvoidmain(String[] args){
// 배열을 선언하는 방법int[] intArr1;
int []intArr2;
int intArr3[];
}
위에서는 int 타입의 배열을 3가지 방법으로 선언해 보았습니다. int타입 대신 long, double, Integer, Long, Double, String 등 다른 타입을 사용할 수도 있습니다. 이렇게 선언을 해 놓아도 공간(메모리)을 차지하지는 않습니다. 배열은 초기화를 하면서 사이즈를 정해줘야 공간(메모리)을 차지하게 됩니다. 그럼 배열 초기화는 어떻게 할까요?
위 예제에서는 intArr1이라는 이름을 가진 배열을 사이즈가 3인 배열로 초기화를 하였습니다. 이렇게 초기화를 하면 int 타입의 경우 기본값 0으로 세팅이 됩니다.
배열의 선언과 초기화를 동시에 하는 방법
자바에서는 아래와 같이 배열의 선언과 초기화를 동시에 할 수도 있습니다.
publicstaticvoidmain(String[] args){
int[] intArr1 = newint[10]; // size 10, index range from 0 to 9int []intArr2 = newint[20]; // size 20, index range from 0 to 19int intArr3[] = newint[20]; // size 20, index range from 0 to 19
}
위에서 설명드린 선언문과 초기화문을 한 줄에 붙여 쓰면 동시에 선언과 초기화가 가능합니다.
자, 그런데 이렇게 하면 int 타입의 배열에는 모두 0으로 값이 세팅이 됩니다.
전, 제가 원하는 값으로 세팅을 하고 싶은데 그렇게도 할 수 있나요?
물론이죠~ 그렇게도 할 수 있습니다. 아래와 같이 하시면 됩니다.
publicstaticvoidmain(String[] args){
int[] intArr4 = {1, 2, 3, 4}; // size 4, index range from 0 to 3int[] intArr5 = {0, 0, 0, 0, 0, 0, 0}; // size 7, index range from 0 to 6
}
intArr4에는 [1, 2, 3, 4]가 저장됩니다. intArr5에는 new int[7] 로 초기화한 것과 같이 0으로 값이 들어갑니다.
배열 출력하기
그럼 이렇게 배열에 들어간 값을 출력해보고 싶을 땐 어떻게 할까요? 자바에서 콘솔창에 출력을 할 때에는 System.out.println() 메서드를 사용하는 것은 다들 알고 계시죠? Hello World를 해보셨다면 다들 알고 계실겁니다. 그럼 이 메서드를 이용해서 변수이름을 넣어주면 될까요? 아닙니다. 배열이 담긴 변수명만 넣어주면 쓰레기값이 출력이 됩니다. 이런 경우에는 Arrays.toString() 메서드를 이용하면 됩니다.
publicstaticvoidmain(String[] args){
int[] intArr1 = newint[10]; // size 10, index range from 0 to 9int []intArr2 = newint[20]; // size 20, index range from 0 to 19int intArr3[] = newint[20]; // size 20, index range from 0 to 19int[] intArr4 = {1, 2, 3, 4}; // size 4, index range from 0 to 3int[] intArr5 = {0, 0, 0, 0, 0, 0, 0}; // size 7, index range from 0 to 6
System.out.println(Arrays.toString(intArr1));
System.out.println(Arrays.toString(intArr2));
System.out.println(Arrays.toString(intArr3));
System.out.println(Arrays.toString(intArr4));
System.out.println(Arrays.toString(intArr5));
}
나는 자바를 제대로 공부하지도 않고 개발자가 되었고, 개발자가 된지 5년이 지나서야 책을 읽어봤다.
수많은 책들이 있었고 그 중 제일 유명한 남궁성님의 책과 윤성우님의 책을 사서 훑어보았다.
책은 너무 두꺼웠고 다시금 까먹고 있던 기초지식을 확인하는 기회가 되었다.
그러다가 한 학생을 가르치게 되었는데 비전공자라 책의 내용을 이해하는데 힘들어했다.
언젠간 나도 책을 내봐야지라는 생각을 가지고 있던터라 이참에 책의 기초가 될만한 강의를 여기서 해볼까 한다.
일반인들, 개발자가 되려는 비전공자들, 그리고 어린 학생들이 읽어도 쉽게 이해할 수 있는 내용으로 강의를 하려 한다.
내 아이가 나중에 커서도 자바가 많이 사용된다면 읽어보도록 추천할 수 있을 정도의 퀄리티를 갖는 내용으로 말이다.
그래서 어떻게 쉽게 전달할 수 있을지 많은 고민을 해야할 것이기에 강의가 빨리 진행되기는 어려울 수 있으나 조금씩 꾸준히 해보려고 한다.
오늘은 그 1일차로 프로그래밍이란 무엇인지에 대해 얘기를 해보겠습니다.
자바란?
세상에는 많은 언어들이 있습니다. 한국어, 중국어, 영어, 일본어, 스페인어, 불어, 독어 등등 말이죠.
한국사람들은 한국어를 사용하고, 일본사람들은 일어를 사용합니다.
어떤 사람들은 3개국어 4개국어를 하기도 합니다.
일본어는 한국어와 문법이 유사해서 쉽고, 영어는 문법이 달라 배우기 어렵다고들 합니다.
언어마다 특정 표현을 할 때 좀더 공감이 가는 문장이 있습니다.
한국어로 직역 또는 의역해도 영어의 특정 문장의 느낌을 그대로 전달하기는 힘들 때가 있는 것처럼 말이죠.
프로그래밍 언어에도 그러한 내용이 딱 들어맞습니다.
자바는수많은 프로그래밍 언어(세계 각국의 언어)들 중 하나입니다.
자바 개발자(한국인)들은 자바(한국어)로 개발을 합니다.
모국어는 한국어이지만 3개국어, 4개국어를 할 줄 아는 사람들이 있듯이,
자바 개발자들도 자바만 하는것이 아니라 파이썬, 자바스크립트, C# 등의 언어를 제2외국어처럼 하기도 합니다.
자바와 문법이 유사한 언어는 자바개발자들에게는 learning curve가 낮지만, 너무 다른 언어는 적응하기가 힘들죠.
마치 한국어와 일본어, 한국어와 영어의 차이처럼 말이죠.
자바로는 구현하기 쉬운 기능이 다른 언어에서는 구현하기 힘들 수도 있습니다.
사람들은 언어를 이용하여 다른 사람들과 소통을 합니다.
어휘력이 좋은 사람이 있고 안좋은 사람도 있죠.
대화의 논리가 확실히 잡혀있는 사람도 있고 논리는 없고 앞뒤없는 대화를 하기도 합니다.
개발자들은 소스코드를 이용하여 소통을 합니다.
자바 언어에서 제공하는 문법을 많이 알고있는 개발자도 있고 기초적인 것만 알고있는 개발자도 있죠.
동일한 문제를 풀때에도 알고리즘이 간결하고 명확한 개발자도 있고, 그렇지 않은 개발자도 있습니다.
즉, 자바라는 언어는 개발자들이 프로그래밍을 할 때 사용하는 제2외국어와 같은 존재입니다.
소스코드와 소설
제 와이프는 제가 IDE(개발툴)화면에 코딩을 하는 모습을 보고, "이게 뭐야? 도대체 뭐라고 쓰는건지 하나도 모르겠네. 이런게 이해가 되?" 라고 질문을 합니다. 당연히 그런 반응이 나올 수 밖에 없습니다. 와이프 입장에서는 제가 오지의 인디언이 사용하는 언어로 글을 쓰고있는 것처럼 느껴질 테니까요.
개발자들은 자신이 사용하는 프로그래밍 언어(제2외국어)를 이용하여 자신들만의 글을 써내려 갑니다. 같은 내용에 대해서 개발을 한다해도 개발자들 성향에 따라 1. 효율성은 조금 떨어지지만 가독성이 좋은 코드를 작성할 수도 있고, 2. 효율성은 극대화했지만 다른 개발자가 이해하기 힘든 코드를 작성할 수도 있습니다. 물론 저는 전자를 지향하고 후배들에게도 전자를 지향하도록 조언합니다.
시인, 소설작가, 수필가 등 글을 쓰는 분들이 단어 하나하나에 고심을 하듯 저도 코딩을 할 때 고민을 많이 합니다. 동일한 기능을 하더라도 좀 더 간결하고 명확하게 효율적인 코딩을 하려고 말이죠. 좋은 글을 작성하기위해 첨삭을 받는 것처럼, 개발자들도 코드리뷰 시간을 통해 고급개발자들의 조언을 듣습니다. 그래서 저는 프로그래밍을 이렇게 정의합니다. "프로그래밍이란 개발자들이 써내려가는 글이다"라고 말이죠. 내가 작성한 코드가 짧지만 이해하기 어려운 시가 될 수도 있고, 좀 길어도 술술 읽어내려갈 수 있는 판타지 소설이 될 수도 있습니다. 어떤 글을 작성하느냐는 순전히 개발자들의 몫이죠.
Wrap Up
프로그래밍 언어란 개발을 위한 언어로 일어, 중국어, 영어와 같은 제2외국어의 하나다.
프로그래밍 언어에는 여러 언어들이 존재하는데 그 중 하나가 자바(java)다.
고급내용 보충
자바는 다른 언어들과는 다르게 JVM(Java Virtual Machine)이라는 가상머신 위에서 실행이 됩니다. 이 때문에 플랫폼(OS, 운영체제)에 의존적이지 않죠. Linux계열에서도 실행이 가능하고, Windows에서도 실행이 가능합니다. 심지어 안드로이드 애플리케이션도 자바로 개발합니다(요즘은 Kotlin이라는 언어도 많이 사용하시더군요). 또한, JVM이 직접 메모리 관리를 해주기 때문에 별도로 개발자가 메모리 관리를 하지 않아도 됩니다. C언어는 개발자가 직접 메모리에 접근을 하여 사용할 수 있기 때문에 관리도 직접 해야하죠.
자바는 웹개발에 많이 사용됩니다. Python(파이썬)은 빅데이터 영역에서 많이 사용되고, C, C++은 임베디드 영역에서 많이 사용되며, C#은 게임개발에서 많이 사용됩니다.
위 코드가 뭘 하고있는지는 대충 봐도 아시겠죠? 역할을 생성하고 사용자를 만들때 역할을 부여하고 있습니다.
이제 web.xml파일에 <security-constraint> 태그를 추가하고 아래처럼 넣어보세요. 물론 url-pattern은 여러분이 가지고 있는 웹애플리케이션에 실제로 존재하는 url이어야게죠? 그래야 테스트가 가능합니다~
<web-app>
...
<security-constraint><web-resource-collection><web-resource-name> SecuredBookSite </web-resource-name><url-pattern>/secured/*</url-pattern><http-method>GET</http-method><http-method>POST</http-method></web-resource-collection><auth-constraint><description> Let only managers use this app </description><role-name>manager</role-name></auth-constraint></security-constraint><security-role><role-name>manager</role-name></security-role><login-config><auth-method>BASIC</auth-method></login-config>
...
</web-app>
위 소스코드가 의미하는 것이 무언인가 하면 다음과 같습니다.
HTTP GET 이나 POST 방식의 요청에 대해서 /secured/* URL에 대한 요청이 들어오면 보안설정의 제약을 받게됩니다.
매니저 역할을 가지고 있는 사용자에 대해서만 /secured/* 리소스에 접근이 가능합니다.
마지막으로 login-config 태그가 기본형태의 인증을 위해서 사용되었습니다.
이제 /security내부의 페이지로 접근을 하려면 사용자명과 비밀번호를 입력하라는 창이 뜨게됩니다. 접속할 수 있는 역할을 가지고 있지 않거나 인증에 실패하면 접속이 불가능하나 페이지가 되는 것이죠.
위 코드를 login.jsp에 넣어주세요. <form> 태그 안에있는 action의 값은 j_security_check 여야 합니다. POST 방식이 사용되어야 한다는 것은 알고 계시겠죠? 자 이제 web.xml의 <login-config> 태그를 FORM을 이용하도록 수정해야합니다.
<web-app>
...
<security-constraint><web-resource-collection><web-resource-name> SecuredBookSite </web-resource-name><url-pattern>/secured/*</url-pattern><http-method>GET</http-method><http-method>POST</http-method></web-resource-collection><auth-constraint><description> Let only managers use this app </description><role-name>manager</role-name></auth-constraint></security-constraint><security-role><role-name>manager</role-name></security-role><login-config><auth-method>FORM</auth-method><form-login-config><form-login-page>/login.jsp</form-login-page><form-error-page>/error.jsp</form-error-page></form-login-config></login-config>
...
</web-app>
이제 /secured/* 주소로 접속을 시도해 보세요. 사용자 ID와 패스워드를 입력하라고 할겁니다. 컨테이너가 "j_security_check" 액션을 만나면요청을 인증하기위한 내부 메카니즘을 실행합니다.
로그인이 성공하고 리소스를 조회할 수 있는 역할을 가지고 있다면 컨테이너는 사용자를 확인하기위해서 session-id 를 비교합니다. 컨테이너는 세션아이디를 가지고있는 쿠키와 함께 세션을 유지하게됩니다. 서버가 이 쿠키를 클라이언트로 되돌려보내고 이후 요청때마다 이 쿠키를 서버로 전송하게되면 컨테이너는 요청하는 클라이언트를 식별할 수 있습니다.
HttpServletRequest 객체가 보안관련해서 제공하는 메소드들은 다음과 같습니다.
SN
Method and Description
1
String getAuthType() The getAuthType() method returns a String object that represents the name of the authentication scheme used to protect the Servlet.
2
boolean isUserInRole(java.lang.String role) The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not.
3
String getProtocol() The getProtocol() method returns a String object representing the protocol that was used to send the request. This value can be checked to determine if a secure protocol was used.
4
boolean isSecure() The isSecure() method returns a boolean value representing if the request was made using HTTPS. A value of true means it was and the connection is secure. A value of false means the request was not.
5
Principle getUserPrinciple() The getUserPrinciple() method returns a java.security.Principle object that contains the name of the current authenticated user.
예를들어 매니저 권한을 갖고있는 사용자들을 위한 링크를 제공하는 JavaServer Page 를 만들려면 아래 코드를 삽입해주시면 되는거죠
이 메소드는 상태코드와 새로운 페이지 주소를 함께 response객체에 담아서 브라우저로 전송합니다. setStatus() 와 setHeader() 를 이용하여 세팅을 해주면 됩니다. 아래처럼 말이죠.
....String site ="http://www.newpage.com";
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);....
예제
JSP 로 어떻게 페이지 리디렉션을 하는지 예제를 통해 알아볼까요?
<%@ page import="java.io.*,java.util.*" %>
<html><head><title>Page Redirection</title></head><body><center><h1>Page Redirection</h1></center><%// New location to be redirectedString site =newString("http://www.naver.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body></html>
이번에는 JSP로 세션을 다루는 법에 대해서 배워보도록 하겠습니다. HTTP는 "stateless" 프로토콜입니다. 무슨 말이냐하면 말이죠, 클아이언트(웹브라우저)가 웹페이지를 불러올때마다 클라이언트는 웹서버로 별도의 커넥션을 맺습니다. 그리고 이전 클라이언트의 접속에 대한 어떠한 정보도 자동으로 기록하지는 않습니다.
어쨌든 세션이라는 것은 바로 웹브라우저가 웹서버와 연결이 될때 생기는 것인데, 이 세션을 유지하는 방법에는 여러가지가 있답니다.
1. Cookies
쿠키에 세션ID를 저장하는 식으로 세션을 관리할 수는 있겠지만 브라우저에서 쿠키사용 제한 설정이 있을 수 있기때문에 세션을 쿠키를 이용해서 관리한다는 것은 좋은방법이 아닙니다.
2. Hidden Form Fields
웹서버는 hidden HTML form field에 unique session ID를 넣어서 아래처럼 전송할 수 있습니다.
<inputtype="hidden"name="sessionid"value="12345">
form이 전송될 때 세션ID와 값을 넘겨주는거죠. 브라우저에서 이 정보를 웹서버에 보내면 이 정보를 가지고 웹서버에서는 다른 브라우저에서 접속한 것인지를 판단할 수 있게 됩니다. 하지만 이 역시 좋은 방법은 아니죠. <a> 태그를 이용해서 링크를 타고 들어오는 경우에는 저 form데이타를 전송하지 않거든요.
3. URL Rewriting
URL 끝에 세션에 대한 정보를 추가할 수도 있습니다. 그리고 서버는 그 정보를 가지고 세션을 비교할 수 있겠죠.
URL rewriting 은 세션을 관리하기위한 방법들 중에서는 그나마 좋은 방법이긴 합니다. 브라우저가 쿠키사용을 안할때도 사용가능한 방법이니까요. 하지만 역시 결점이 있습니다. 세션ID를 동적으로 매번 생성해줘야 하기 때문입니다. 정적인 HTML페이지라도 말이죠.
The session Object:
위 세가지 방법 이외에도 JSP는 HttpSession 인터페이스를 사용할 수 있습니다. 기본적으로 JSPs는 세션을 추적하게 되어있으며 새로운 HttpSession 객체가 새로운 클라이언트들이 접속할 때마다 자동으로 생성됩니다. 세션 추적 기능을 끄려면 page directive의 세션 속성을 false로 세팅해줘야 합니다. 아래 처럼 말이죠.
<%@ page session="false" %>
JSP engine은 JSP개발자들에게 HttpSession 객체를 통해서 session에 접근할 수 있도록 해줍니다. session 객체가 기본적으로 제공이 되기 때문에 개발자들은 궂이 세션객체를 생성하거나 getSession() 메소드를 이용해서 얻어올 필요가 없습니다.
웹애플리케이션을 작성하고 있다면 그냥 세션을 파라미터로 받아서 쓰면 되는 겁니다.
다음은 세션 객체가 가지고 메소드 목록입니다. 어떤 메소드들이 있는지 한번 살펴볼까요~
S.N.
Method & Description
1
public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name.
2
public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session.
3
public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
4
public String getId() This method returns a string containing the unique identifier assigned to this session.
5
public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
6
public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
7
public void invalidate() This method invalidates this session and unbinds any objects bound to it.
8
public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
9
public void removeAttribute(String name) This method removes the object bound with the specified name from this session.
10
public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified.
11
public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
Session Tracking Example:
다음 예제는 HttpSession 객체를 이용하여 세션의 생성시간과 마지막 접근시간 정보를 가져오는 방법에 대해서 설명해주고 있습니다.
<%@ page import="java.io.*,java.util.*" %>
<%// Get session creation time.Date createTime =newDate(session.getCreationTime());// Get last access time of this web page.Date lastAccessTime =newDate(session.getLastAccessedTime());String title ="Welcome Back to my website";Integer visitCount =newInteger(0);String visitCountKey =newString("visitCount");String userIDKey =newString("userID");String userID =newString("ABCD");// 처음 접속한 방문자라면 세션을 생성합니다.if(session.isNew()){
title ="Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);}
visitCount =(Integer)session.getAttribute(visitCountKey);
visitCount = visitCount +1;
userID =(String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html><head><title>Session Tracking</title></head><body><center><h1>Session Tracking</h1></center><tableborder="1"align="center"><trbgcolor="#949494"><th>Session info</th><th>Value</th></tr><tr><td>id</td><td><%out.print( session.getId()); %></td></tr><tr><td>Creation Time</td><td><%out.print(createTime); %></td></tr><tr><td>Time of Last Access</td><td><%out.print(lastAccessTime); %></td></tr><tr><td>User ID</td><td><%out.print(userID); %></td></tr><tr><td>Number of visits</td><td><%out.print(visitCount); %></td></tr></table></body></html>
Cookies 는 그냥 일반 text files 이죠. 아마 JSP를 공부하시는 분들이라면 이정도는 알고 계시겠죠?
JSP로 HTTP cookies 를 다루는 법에 대해서 한번 알아볼텐데 그 전에 하나만 짚고 넘어갈까요?
사용자가 특정 사이트에 재접속 했다는 것을 웹사이트에서 어떻게 알까요?
3초만에 답이 안나온다면 아래를 읽어봅시다.
재접속하는 사용자를 판단하는 과정은 세 단계로 나뉩니다.
서버쪽에서 쿠키를 브라우저로 보냅니다.
Browser는 서버에서 보낸 쿠키를 로컬에 저장을 하겠죠.
이제 사용자가 이 브라우저를 이용해서 특정사이트에 접속할 때 저장되어있는 쿠키의 정보가 서버쪽으로 전달되고 서버쪽에서는 이 정보를 이용해서 사용자를 판별할 수 있는 것이죠.
쿠키는 다른 정보로도 사용될 수 있으니 쿠키를 다루는 법을 한번 알아보도록 하겠습니다. 여기서는 쿠키 세팅, 리셋, 읽기, 삭제하기에 대해서 알아보도록 하겠습니다.
Cookie 해부하기
쿠키는 보통 HTTP header 안에 세팅되어있습니다. ( JavaScript 는 직접 브라우저에 쿠키를 설정할 수 있다네요 ). 쿠키를 세팅하는 JSP 는 아래와 같은 헤더를 보낼거에요.
HTTP/1.1200 OK
Date:Fri,04Feb200021:03:38 GMT
Server:Apache/1.3.9(UNIX) PHP/4.0b3Set-Cookie: name=xyz; expires=Friday,04-Feb-0722:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
이미 request 객체시간에 한번 본적이 있던 내용이죠? 그런데 추가된게 하나 있네요. Set-Cookie header 입니다. 보아하니 이름, 만료일시, 경로, 그리고 도메인정보를 가지고 있네요.
브라우저에서 쿠키를 저장하도록 설정이 되어있으면 브라우저는 이런 정보들을 만료일 전까지 저장하게 됩니다.만약 사용자가 쿠키에 설정된 경로로 접속을 하게되면 브라우저는 서버로 그 쿠키를 재전송합니다. 그 브라우저의 헤더는 다음과 같은 정보를 갖고 있을 겁니다.
GET / HTTP/1.0Connection:Keep-AliveUser-Agent:Mozilla/4.6(X11; I;Linux2.2.6-15apmac ppc)Host: zink.demon.co.uk:1126Accept: image/gif,*/*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
이제 JSP script 는 request method중 하나인 request.getCookies() 를 통해서 쿠키에 접근할 수 있습니다.
Servlet Cookies 메소드
아래 메소드들은 JSP에서 쿠키를 다룰때 사용될 수 있는 메소드목록 및 기능입니다.
S.N.
Method & Description
1
public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com.
2
public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com.
3
public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4
public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5
public String getName() This method returns the name of the cookie. The name cannot be changed after creation.
6
public void setValue(String newValue) This method sets the value associated with the cookie.
7
public String getValue() This method gets the value associated with the cookie.
8
public void setPath(String uri) This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9
public String getPath() This method gets the path to which this cookie applies.
10
public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11
public void setComment(String purpose) This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12
public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
JSP로 쿠키 설정하기
JSP로 쿠키를 설정하려면 아래와 같은 단계를 거칩니다.
(1) Cookie 객체 생성 : You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie =newCookie("key","value");
자바에서 쿠키 생성하는거랑 똑같습니다. 그런데 여기서 name과 value ( "key"가 name인거고 "value"가 value가 되겠죠)에는 절대로 스페이스(빈칸)이나 아래에 나열된 특수문자가 사용될 수 없습니다.
[]()=," / ? @ : ;
(2) Max age 설정 : 초 단위로 max age를 설정합니다. 이 쿠키가 살아있을 수 있는 시간을 설정하는거죠. 아래는 24 시간동안 존재할 수 있는 쿠키를 설정하는 예제입니다.
cookie.setMaxAge(60*60*24);
(3) Cookie를 HTTP response header에 추가하기 :response.addCookie 메소드를 이용하면 추가하 수 있습니다.
response.addCookie(cookie);
예제
<%// Create cookies for first and last names. Cookie firstName =newCookie("first_name",
request.getParameter("first_name"));Cookie lastName =newCookie("last_name",
request.getParameter("last_name"));// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html><head><title>Setting Cookies</title></head><body><center><h1>Setting Cookies</h1></center><ul><li><p><b>First Name:</b><%= request.getParameter("first_name")%>
</p></li><li><p><b>Last Name:</b><%= request.getParameter("last_name")%>
</p></li></ul></body></html>
main.jsp 파일에 위 코드를 넣어주세요. 그리고 다음 코드는 hello.jsp파일에 넣어주세요.
<html><body><formaction="main.jsp"method="GET">
First Name: <inputtype="text"name="first_name"><br/>
Last Name: <inputtype="text"name="last_name"/><inputtype="submit"value="Submit"/></form></body></html>
두 jsp파일을 <Tomcat-installation-directory>/webapps/ROOT 디렉토리에 넣어주세요.
그럼 예전에 봤던 것처럼 퍼스트 네임과 래스트 네임이 출력이 될겁니다. 그런데 여기서 이녀석이 몰래하는 작업이 또 있습니다. 눈에는 보이지 않았지만 first_name과 last_name이라는 쿠키를 생성한것입니다. 그리고 submit버튼이 또 눌리게 될 경우 방금 만들어진 쿠키들이 서버쪽으로 전송되게 되겠죠.
자, 그럼 이제 서버쪽으로 전송되는 쿠키정보를 JSP에서 읽어오는 것을 한번 해보겠습니다.
JSP를 이용하여 쿠키정보 읽어오기
쿠키를 읽으려면 HttpServletRequest 의 getCookies( ) 메소드를 호출하기만 하면 됩니다. 이 메소드는 Cookie[]를 반환합니다. 한번에 여러개의 쿠키가 전송될 수 있다는 것이죠. 그럼 루프를 돌면서 전송된 쿠키의 정보를 출력하는 예제를 한번 보도록 하겠습니다.
예제
<html><head><title>Reading Cookies</title></head><body><center><h1>Reading Cookies</h1></center><%Cookie cookie =null;Cookie[] cookies =null;// Get an array of Cookies associated with this domain
cookies = request.getCookies();if( cookies !=null){out.println("<h2> Found Cookies Name and Value</h2>");for(int i =0; i < cookies.length; i++){
cookie = cookies[i];out.print("Name : "+ cookie.getName()+", ");out.print("Value: "+ cookie.getValue()+" <br/>");}}else{out.println("<h2>No cookies founds</h2>");}
%>
</body></html>
위 코드를 main.jsp 파일에 넣고 접속해보세요. 쿠키에 설정한 값들이 나오겠죠? 아래처럼 말이죠.
Found Cookies Name and Value
Name : first_name, Value: 홍길동은 Name : last_name, Value: 플레이보이
JSP를 이용한 쿠키 삭제
이번에는 쿠키를 삭제해보도록 하겠습니다. 뭐 쿠키삭제는 브라우저에서도 할 수 있는 기능이긴 하지만 그래도 한번 읽어나 보세요. 웹개발자라면 쿠키 다루는 법은 잘 알고 있어야 할 테니까요.
쿠키를 읽어와서 쿠키객체에 저장합니다.
쿠키의 나이를 0으로 만들어버리세요. setMaxAge() 메소드를 사용하면 되는건 아시죠?
이 쿠키를 다시 response에 넣어 되돌려보내세요.
예제
아래 예제는 "first_name" 쿠키를 삭제하는 main.jsp 소스입니다. 삭제된 후에 이 쿠키를 다시 읽어오려고하면 null이 나올겁니다.
<html><head><title>Reading Cookies</title></head><body><center><h1>Reading Cookies</h1></center><%Cookie cookie =null;Cookie[] cookies =null;// Get an array of Cookies associated with this domain
cookies = request.getCookies();if( cookies !=null){out.println("<h2> Found Cookies Name and Value</h2>");for(int i =0; i < cookies.length; i++){
cookie = cookies[i];if((cookie.getName()).compareTo("first_name")==0){cookie.setMaxAge(0);
response.addCookie(cookie);out.print("Deleted cookie: "+
cookie.getName()+"<br/>");}out.print("Name : "+ cookie.getName()+", ");out.print("Value: "+ cookie.getValue()+" <br/>");}}else{out.println("<h2>No cookies founds</h2>");}
%>
</body></html>