프로그래밍/JSP Servlet

JSP/Servlet - jspInit 메소드와 jspDestroy 메소드 활용

가카리 2016. 1. 4. 22:06
반응형

 

서블릿의 init 메소드와 destroy메소드와 비슷하게 jsp에도 jspInit메소드와 jspDestroy메소드로 구현 할 수 있습니다.

 

위와 같이 DateTime.jsp 파일 하나를 구현해봅시다.

 

DateTime.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR" import="java.io.*, java.util.*"%>

<%!

    //선언문 안에 기술

    private PrintWriter logFile;

    public void jspInit(){

        String filename = "C:\\Users\\kch\\Documents\\datelog.txt";

        try{

            logFile = new PrintWriter(new FileWriter(filename, true));

        }catch(IOException e){

            System.out.printf("%TT - %s 파일 열기 필해 %n", new GregorianCalendar(), filename);

        }

        

    }

    

%>

<!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=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<%

    GregorianCalendar now = new GregorianCalendar();

    String date = String.format("%TY %Tm %Te", now, now, now);

    String time = String.format("%TI %TM %TS", now, now, now);

    

    out.println(date + "<BR>");

    out.println(time + "<BR>");

    if(logFile != null)//로그파일에 쓰기

        logFile.printf("%TF %TT 호출됨 %n", now, now);

    

%>

</body>

</html>

<%!

    //선언문 안에 기술

    public void jspDestroy(){

        if(logFile != null)

            logFile.close();

    }

 

%>

 

 

실행 화면

날짜와 시간이 잘 나옴을 알 수 있습니다.

값도 다음과 같이 들어감을 알 수 있습니다.

반응형