JSP 2020. 4. 13. 18:53

어떤 데이터를 서버가 아닌 클라이언트에 서버의 명령에 의해서 저장된 것을 쿠키(Cookie)라고 한다.
데이터를 클라이언트의 로컬에 저장하여 보안상 문제가 있기 때문에, 요즘에는 잘 사용하지 않는 기술이다.

데이터가 별로 중요하지 않고, 서버의 자원을 절약해야 할 경우에 사용할 수 있는 기법이다.

[Make Cookie]

<%
Cookie cookie= new Cookie("CookieName", "CookieValue");

// set valid time of cookie
// parameter is second.
cookie.setMaxAge(60*60);

// add cookie to response object
response.addCookie(cookie);
%>

쿠키 객체를 만들고, 쿠키의 유효 기간을 설정한다.

쿠키의 속성이 모두 정의되면 response객체에 쿠키를 추가한다.

[Get Cookies]

<%
Cookie[] cookies= request.getCookies();
  if(cookies!= null){
for(int i=0; i<cookies.length; i++){
out.println("cookies["+i+"] Name= "+ cookies[i].getName()+ "<br/>");
out.println("cookies["+i+"] Value= "+ cookies[i].getValue()+"<br/>");
out.println("================================"+"<br/>");
}
   }
%>

Cookie 객체를 가져올 때는 만들 때와는 반대로 request객체에서 받아온다.

Cookie는 여러 개일 수도 있으므로, Array type으로 받는다.

모든 쿠키를 탐색하기 위해 for문을 이용해 모든 Cookie 객체를 탐색한다.

getName()은 쿠키의 이름을, getValue()는 쿠키의 값을 반환한다.


[Delete Cookie]

<%
Cookie[] cookies= request.getCookies();
for(int i=0; i<cookies.length; i++){
String cookieName=cookies[i].getName();
if(cookieName.equals("CookieName")){
out.println("cookies["+i+"] Name= "+ cookies[i].getName()+ "<br/>");
out.println("cookies["+i+"] Value= "+ cookies[i].getValue()+"<br/>");

out.println("This Cookies will be deleted"+ "<br/>");

// This process that set valid period of cookie and save cookie means targetCookie is deleted.
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);

out.println("================================"+"<br/>");
}
}
%>

쿠키를 직접 삭제하는 어떤 특정 메소드가 존재하지 않는다.

그래서 특정 쿠키의 유효시간을 0으로 만들어 유효하지 않은 쿠키로 만들어 간접적으로 삭제하는 방법을 이용한다.

cookes[i].setMaxAge메소드의 인자값을 0으로 만들고 
유효시간이 만료된 쿠키를 response.addCookie()로 다시 추가해줌으로써 쿠키를 삭제하는 효과를 얻는다.

'JSP' 카테고리의 다른 글

[JSP] 기초 간단하게 정리  (0) 2020.04.13
posted by 핵커 커뮤니티
:
JSP 2020. 4. 13. 18:49

web page에서 java code를 사용하려면 기본적으로 .html이 아닌 .jsp파일을 이용한다.

[Java Code 사용을 Declare]

<% JavaCode.... %> 형식을 따른다.

예를 들어 <% int i=0; System.out,.println(i); %> 와 같은 형식으로 한다.
jsp파일에는 자바 코드가 드러나지만, 실제로 실행시키면 사용자에겐 html문서 형식으로 보여지며
JavaCode는 해당 요소로 변환되어 JavaCode는 보이지 않게 된다.

[Variable Print]

단순히 변수의 출력만을 원할 경우에는 <%= Variable %> 와 같은 형식으로 한다.
<% out,println(Variable); %>처럼 쓸 수도 있지만 코드가 길어질 염려가 있다.

[Import Other Class or Package]

<%@page import="Package or Class" %> 처럼 한다.
일반적인 자바의 import [package or class]; 문법과 같다.
효력은 이 태그가 사용된 페이지에 한해 import된다.

예를 들어 <%@page import="java.util.Arrays"%> 했다면


<%
int[] arr= {10,20,30};
out.println(Arrays.toString(arr));
%>

처럼 Arrays Class를 사용할 수 있다.

[Page in Page]

include Attribute를 이용하여 페이지에서 다른 페이지를 포함시킬 수도 있다.
홈페이지의 카테고리와 같이, 여러 페이지에서 공통되게 사용하는 부분들은 따로 만들어서 include하는 방식을 취한다.

<%@ include file="IncludedJSP.jsp" %>

[주석(Comment)]

<%-- --> 또는 자바에서와 같이 //나 /* */ 를 사용한다.

[페이지 속성 정의]
<%@ page language="java" contentType="text/html; charset="EUC-KR"
    pageEncoding="EUC-KR"%>

JSP파일을 만들면 이 태그는 자동으로 생성된다.

어떤 언어를 사용하고, 언어 인코딩 방식은 어떤 것으로 할지 정의하는 부분이다.

EUC-KR을 사용하지 않으면, 영어는 관계없지만 한국어는 문자가 깨져서 출력되게 되므로 반드시 설정한다.

'JSP' 카테고리의 다른 글

[JSP] 쿠키(Cookle) 클라이언트 서버 명령 소스  (0) 2020.04.13
posted by 핵커 커뮤니티
:
C샵 2020. 4. 13. 18:45

 //열기창 생성
OpenFileDialog oDialog = new OpenFileDialog();
oDialog.Filter = "텍스트 파일|*.txt";
//열기창 띄우고 내용 반환
if (oDialog.ShowDialog() == DialogResult.OK)
{
    string a = System.IO.File.ReadAllText(oDialog.FileName, Encoding.Default);
}

posted by 핵커 커뮤니티
:
C샵 2020. 4. 13. 18:42

// 상단에 using지시문 추가
using WinHttp; // 오류가 뜰 경우 참고 추가로 winhttp.dll 추가하시면 됩니다.
// 추가 방법은 찾아보기 - C:\windows\System32 에서 저 winhttp 검색하시면 됩니다. (32비트 기준)
 
// 네이버 계정 및 카페 인증
bool NaverLogin(string ID, string PW)
        {
            WinHttpRequest WinHttp = new WinHttpRequest();
            WinHttp.Open("POST", "https://nid.naver.com/nidlogin.login", false);
            WinHttp.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            WinHttp.SetRequestHeader("Referer", "https://nid.naver.com/nidlogin.login");
            WinHttp.Send("enctp=2&url=http://www.naver.com&enc_url=http://www.naver.com&postDataKey=&saveID=0&nvme=0&smart_level=1&id=" + ID + "&pw=" + PW);
            WinHttp.WaitForResponse();
            WinHttp.Open("GET", "http://cafe.naver.com/"); // 해당 카페 주소 입력
            WinHttp.Send("");
            WinHttp.WaitForResponse();
            string result = Encoding.Default.GetString(WinHttp.ResponseBody);
            if (result.IndexOf("카페멤버") == -1) // 이건 WinHttp.ResponseText.IndexOf("카페멤버") 이렇게 사용하면 오류가 뜨더라구요
            {
                return false; // 카페 가입이 되어있으면 저 "카페멤버" 라는 글자가 표시되지 않습니다.
            }
            else
            {
                return true; // 카페 가입이 되어있지않으면 저 "카페멤버" 라는 글자가 표시됩니다.
            }
        }
 
이렇게 하시고 버튼 이벤트에
 
// NaverLogin 이 false 값일 경우 (가입 되어있을 경우)
// NaverLogin 이 true 값일 경우 (가입 되어있지 않을 경우)
 if (NaverLogin(textBox1.Text, textBox2.Text) == false)
            {
                // false 값이면 성공
                MessageBox.Show("네이버 인증에 성공하였습니다.", "성공!", MessageBoxButtons.OK);
            }
            else
            {
                // true 값이면 실패
                MessageBox.Show("네이버 인증에 실패하였습니다.", "실패!", MessageBoxButtons.OK);
            }

'C샵' 카테고리의 다른 글

[C#] C# 데이터 타입 배워보기 (종류)  (1) 2020.04.16
[C#] C#의 버전 알아보자  (0) 2020.04.16
[C#] C#이란 무엇일까? 기초알아보기 (1)  (0) 2020.04.16
[C#] TXT 불러오기 소스  (0) 2020.04.13
posted by 핵커 커뮤니티
:
C언어 2020. 4. 13. 18:38

기본적인 C언어란 프로그래밍 언어이다.

컴퓨터와의 대화에 사용하기 위해 일종의 의사소통이다.

ex) 한국인 영어> 통역사(컴퓨터 본체) > 일본인
ex) > 한국말 영어> 통역사 > 일본말 > 일본인
이런식으로 가능한 조건이 C언어이다.
하지만 컴퓨터에서는 의사소통이 불가능이므로  C언어로 의사소통 할수있다.
ex) 한국어 C언어 > 컴파일러(C언어 기계어) > 컴퓨터
*컴파일러이란? > 프로그래밍 언어로 작성한 프로그램을 컴퓨터가 이해할 수 있도록 기계어로 번역하는역할을합니다. (Compile)
*기계어란? 컴퓨터가 이해할 수 있도록 0과1로 구성된 언어체계입니다.

posted by 핵커 커뮤니티
:
DelPhi 2020. 4. 12. 14:00

{ 여기서 부터 dll 작성부분이다 }

{ 여기서 두함수가 DLL 함수가 된다 }

library Firstdll;

uses

Windows;

 

function Triple( N : Integer) : Integer; stdcall;

begin

MessageBox(0,'Triple function called',

'First Dll',mb_Ok);

Result := N * 3;

end;

function Double( N : Integer) : Integer; stdcall;

begin

MessageBox(0,'Double function called',

'First Dll',mb_Ok);

Result := N * 2;

end;

exports

Triple , Double;

begin

end.

{ 여기까지가 Dll 작성 루틴이다 }

{ 여기서 부터는 DLL 에 있는 함수를 호출하는것을 보여주는 예이다.}

unit dllcall;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

StdCtrls, Spin;

type

TForm1 = class(TForm)

Button1: TButton;

Button2: TButton;

SpinEdit1: TSpinEdit;

SpinEdit2: TSpinEdit;

procedure Button1Click(Sender: TObject);

procedure Button2Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

{ DLL 함수를 선언한다 }

function Double( N : Integer) : Integer;

stdcall; external 'FirstDll.dll';

function Triple( N : Integer) : Integer;

stdcall; external 'FirstDll.dll';

implementation

{$R *.DFM}

{DLL 함수의 호출}

procedure TForm1.Button1Click(Sender: TObject);

begin

SpinEdit1.Value := Double(SpinEdit1.Value);

end;

procedure TForm1.Button2Click(Sender: TObject);

begin

SpinEdit2.Value := Triple(SpinEdit2.Value);

end;

end.

----- Dfm 파일 -----

object Form1: TForm1

Left = 200

Top = 108

Width = 328

Height = 156

Caption = 'Form1'

Font.Charset = DEFAULT_CHARSET

Font.Color = clWindowText

Font.Height = -11

Font.Name = 'MS Sans Serif'

Font.Style = []

PixelsPerInch = 96

TextHeight = 13

object Button1: TButton

Left = 24

Top = 24

Width = 75

Height = 25

Caption = 'Double'

TabOrder = 0

OnClick = Button1Click

end

object Button2: TButton

Left = 24

Top = 80

Width = 75

Height = 25

Caption = 'Triple'

TabOrder = 1

OnClick = Button2Click

end

object SpinEdit1: TSpinEdit

Left = 144

Top = 24

Width = 121

Height = 22

MaxValue = 0

MinValue = 0

TabOrder = 2

Value = 0

end

object SpinEdit2: TSpinEdit

Left = 144

Top = 80

Width = 121

Height = 22

MaxValue = 0

MinValue = 0

TabOrder = 3

Value = 0

end;

end;

posted by 핵커 커뮤니티
:
DelPhi 2020. 4. 12. 13:56

// 컴포넌트를 Install 한다음 Samples 디렉토리에 가서

// EditButton 을 한번 시험해 보는 것도 재미 있을듯..

unit ButtonEdit;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

StdCtrls;

type

TButtonEdit = class(TEdit)

private

//FCanvas: TCanvas; //commented out - see below!

//do you want to 'click' when the up or down arrow key pressed as well?

FClickOnArrow: boolean;

//do you want to 'click' when the Return key pressed as well?

FClickOnReturn: boolean;

//flag - is the button pressed or not

FPressed: boolean;

procedure Click; override;

procedure CreateWnd; override;

procedure WMPAINT(var Message: TMessage); message WM_PAINT;

procedure WMLBUTTONDOWN(var Message: TWMMouse); message WM_LBUTTONDOWN;

procedure WMLBUTTONUP(var Message: TWMMouse); message WM_LBUTTONUP;

procedure WMMOUSEMOVE(var Message: TWMMouse); message WM_MOUSEMOVE;

//procedure WMSETFOCUS(var Message: TMessage); message WM_SETFOCUS;

protected

procedure KeyDown(var Key: Word; Shift: TShiftState); override;

public

constructor Create(AOwner: TComponent); override;

published

property ClickOnArrow: boolean read FClickOnArrow write FClickOnArrow;

property ClickOnReturn: boolean read FClickOnReturn write FClickOnReturn;

end;

procedure Register;

implementation

const

BUTTONWIDTH = 17;

{----------------------------------------------------------------------}

{----------------------------------------------------------------------}

procedure Register;

begin

RegisterComponents('Samples', [TButtonEdit]);

end;

{----------------------------------------------------------------------}

constructor TButtonEdit.Create(AOwner: TComponent);

begin

inherited Create(AOwner);

FPressed := false;

FClickOnArrow := true;

FClickOnReturn := false;

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.CreateWnd;

begin

inherited CreateWnd;

//this is crucial to stop text disappearing under the button...

perform(EM_SETMARGINS,EC_RIGHTMARGIN,(BUTTONWIDTH+2) shl 16);

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.WMLBUTTONDOWN(var Message: TWMMouse);

begin

inherited;

//draw button in pressed state...

if message.xpos >= clientwidth-BUTTONWIDTH+1 then begin

FPressed := true;

Refresh;

end;

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.WMLBUTTONUP(var Message: TWMMouse);

begin

inherited;

//draw button in non-pressed state...

if FPressed then begin

FPressed := false;

Refresh;

end;

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.WMMOUSEMOVE(var Message: TWMMouse);

begin

inherited;

//change cursor when over the button to an arrow (not the default I-beam)...

if message.xpos >= clientwidth-BUTTONWIDTH+1 then cursor := crArrow

else cursor := crDefault;

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.Click;

var

pt: TPoint;

begin

//fix a minor cosmetic problem...

if FPressed then begin

FPressed := false;

Repaint;

end;

//Only process an OnClick method if the button is clicked,

//NOT if the text is clicked!

GetCursorPos(pt);

if PtInRect(Rect(clientwidth-BUTTONWIDTH+1,0,clientwidth,clientheight),

ScreenToClient(pt)) then inherited Click;

end;

{----------------------------------------------------------------------}

procedure TButtonEdit.KeyDown(var Key: Word; Shift: TShiftState);

begin

//respond to up or down arrow keys or Return key with OnClick event if

//"ClickOnArrow" or "ClickOnReturn" property set...

inherited KeyDown(Key, Shift);

if ((Key = vk_Down) or (Key = vk_Up))

and (Shift = []) and FClickOnArrow then begin

Key := 0;

inherited Click;

end

else if (Key = vk_return) and FClickOnReturn then begin

Key := 0;

inherited Click;

end;

end;

{----------------------------------------------------------------------}

//This no longer seems to be necessary ... I've left it here just in case!

{procedure TButtonEdit.WMSETFOCUS(var Message: TMessage);

begin

inherited;

repaint;

end;}

{----------------------------------------------------------------------}

procedure TButtonEdit.WMPAINT(var Message: TMessage);

var

dc: HDC;

CntrPt: TPoint;

pic: array [0..3] of TPoint; //arrow 'picture' points

begin

// let windows draw the text!

// I don't really want to struggle with all the scrolling issues etc!

inherited;

//NOW DRAW THE BUTTON ... (not as bad as it looks if you take out the comments!)

//find the centre of the button...

CntrPt := point(clientwidth - BUTTONWIDTH div 2, clientheight div 2);

//offset CntrPt by 1 if pressed...

if FPressed then CntrPt := point(CntrPt.x+1,CntrPt.y+1);

//get button arrow drawing coordinates from CntrPt...

pic[0] := point( CntrPt.x-5,CntrPt.y);

pic[1] := point( CntrPt.x,CntrPt.y-5);

pic[2] := point( CntrPt.x+5, CntrPt.y);

pic[3] := point( CntrPt.x, CntrPt.y+5);

//Notes:

//1. As I'm calling the inherited WMPAINT method before drawing the button -

// I have to use getDC(handle) instead of beginpaint(handle,paintstruct)

// otherwise I don't see the button! (I think due to clipping.)

//2. If I wanted to draw the text as well as the button (without calling

// the inherited method) then I would have to use beginpaint(handle,paintstruct).

dc := getDC(handle);

//To make this method a little more efficient you could add a private Canvas field

// to the component and create it once only in TButtonEdit.create and free it in

//TButtonEdit.destroy. I've kept it all here for simplicity.

//(Don't use TControlCanvas instead of TCanvas in TButtonEdit.create -

//It doesn't work! - Someone might explain TControlCanvas to me.)

with TCanvas.create do begin

Handle := dc;

Brush.Color := clBtnFace;

//Brush.style := bsSolid;

//paint the button surface...

FillRect(rect(clientwidth-BUTTONWIDTH+1,0,clientwidth,clientheight));

//draw the button edges...

if FPressed then Pen.color := clBtnShadow else Pen.color := clBtnHighlight;

Moveto(clientwidth-BUTTONWIDTH+2,clientheight-1);

Lineto(clientwidth-BUTTONWIDTH+2,1);

Lineto(clientwidth-1,1);

if FPressed then Pen.color := clBtnHighlight else Pen.color := clBtnShadow;

Lineto(clientwidth-1,clientheight-1);

Lineto(clientwidth-BUTTONWIDTH+2,clientheight-1);

//draw the arrows...

Brush.Color := clGreen;

Pen.color := clBlack;

polygon(pic);

Pen.color := clBtnFace;

Moveto(CntrPt.x-5,CntrPt.y);

Lineto(CntrPt.x+6,CntrPt.y);

Handle := 0;

free; //the canvas.

end;

ReleaseDC(handle,dc);

end;

{----------------------------------------------------------------------}

(*

//Old WMPAINT Method (not using TCanvas)...

procedure TButtonEdit.WMPAINT(var Message: TMessage);

var

dc: HDC;

SilverBrush, ArrowBrush, Oldbrush: HBrush;

WhitePen, GrayPen, SilverPen, OldPen: HPen;

CntrPt: TPoint;

pic: array [0..3] of TPoint; // for arrow 'picture'.

begin

inherited;

//NOW DRAW BUTTON ...

//find the centre of the button...

CntrPt := point(clientwidth - BUTTONWIDTH div 2, clientheight div 2);

//offset by 1 if pressed...

if FPressed then CntrPt := point(CntrPt.x+1,CntrPt.y+1);

//get button arrow coordinates...

pic[0] := point( CntrPt.x-5,CntrPt.y);

pic[1] := point( CntrPt.x,CntrPt.y-5);

pic[2] := point( CntrPt.x+5, CntrPt.y);

pic[3] := point( CntrPt.x, CntrPt.y+5);

//create handles ...

dc := getDC(handle);

SilverBrush := CreateSolidBrush(GetSysColor(COLOR_BTNFACE));

ArrowBrush := CreateSolidBrush(clGreen);

WhitePen := CreatePen(PS_SOLID,1,clWhite);

GrayPen := CreatePen(PS_SOLID,1,clGray);

SilverPen := CreatePen(PS_SOLID,1,GetSysColor(COLOR_BTNFACE));

//draw button surface and outline...

OldBrush := SelectObject(dc, ArrowBrush);

FillRect(dc,rect(clientwidth-BUTTONWIDTH+1,0,clientwidth,clientheight),SilverBrush);

if FPressed then OldPen := SelectObject(dc,GrayPen)

else OldPen := SelectObject(dc,WhitePen);

MovetoEx(dc,clientwidth-BUTTONWIDTH+2,clientheight-1,nil);

Lineto(dc,clientwidth-BUTTONWIDTH+2,1);

Lineto(dc,clientwidth-1,1);

if FPressed then SelectObject(dc,WhitePen)

else SelectObject(dc,GrayPen);

Lineto(dc,clientwidth-1,clientheight-1);

Lineto(dc,clientwidth-BUTTONWIDTH+2,clientheight-1);

//draw up&down arrows...

SelectObject(dc,OldPen);

polygon(dc,pic,4);

SelectObject(dc,SilverPen);

MovetoEx(dc,CntrPt.x-5,CntrPt.y,nil);

Lineto(dc,CntrPt.x+6,CntrPt.y);

//clean up ...

SelectObject(dc,OldPen);

SelectObject(dc, OldBrush);

DeleteObject(WhitePen);

DeleteObject(SilverPen);

DeleteObject(GrayPen);

DeleteObject(SilverBrush);

DeleteObject(ArrowBrush);

ReleaseDC(handle,dc);

end;

*)

{----------------------------------------------------------------------}

end.

posted by 핵커 커뮤니티
:
DelPhi 2020. 4. 12. 13:54

1.Classes 추가

 

 uses 

 Classes;

2.값을 저장하고 불러올 Packed record를 만듭니다!

 type

 TPerson = Packed record 

 sName : Array[1..50] of Char;

 nAge   : Integer; 

 end;

 //저장할 데이터의 크기를 고정시켜줍니다.

 

 var

 Person : TPerson;

 

 3. dll 저장!

  procedure WriteDll;

 

  var

  sFilePath : string;

  Stream   : TMemoryStream;

 

  begin

  sFilePath := '저장될 경로명' + '파일명.dll';

  Stream := TMemoryStream.Create;

 

  try

  Stream.Clear;

  Stream.Write(Person, SizeOf(TPerson))

   Stream.SaveToFile(sFilePath);

   finally

   Stream.Free;

   end;

  4.dll 불러옵니다

  procedure ReadDll;

  var

 sFilePath : string;

  Stream   : TMemoryStream;

begin

  sFilePath := '불러올 경로명' + '파일명.dll';

   Stream := TMemoryStream.Create;

   FillChar(Person, Sizeof(TPerson), #0); //공백으로 채워줍니다.  

  try

  Stream.LoadFromFile(sFilePath); 

  Stream.Position := 0;

  Stream.Read(Person, SizeOf(TPerson)); 

  finally

  Stream.Free;

  //공백으로 채웠기 때문에 Trim을 사용해 문자열의 양쪽 공백을 제가한뒤 사용

 ShowMessage(Trim(Person.sName));

  end;

posted by 핵커 커뮤니티
: