본문 바로가기

Programing/JSP

Servlet - 공지파일 예제

* 현재 날짜로 된 문서가 notice폴더에 있다면 문서의 내용을 Servlet으로 표현


사용자 삽입 이미지




NoticeServlet.java  - 2008528.txt 파일 필요(내용포함)


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 public class NoticeServlet extends javax.servlet.http.HttpServlet {

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  // 응답시 한글 처리
  response.setContentType("text/html;charset=euc-kr");
 
  //  요청 당시 날짜 구하기
  Calendar now = Calendar.getInstance();
 
  int y = now.get(Calendar.YEAR);
  int m = now.get(Calendar.MONTH)+1; //  1월이 0으로 인식된다.
  int d = now.get(Calendar.DAY_OF_MONTH);
 
  String c_day = String.valueOf(y) + String.valueOf(m) + String.valueOf(d) + ".txt"; //  2008528.txt
 
  String path = "/notice/" + c_day;
 
  //위의 상대경로를 절대 경로로 변환한다.
 
  path = getServletContext().getRealPath(path);
  //  현재 사용되고 있는 폴더(Context)에 path의 내용을 더하여 절대경로로 변환해 준다.
 
  //응답을 하기 위한 준비
  PrintWriter out = response.getWriter();
 
  out.println("<html>");
  out.println(" <BODY>");
  out.println("  <table style='border-collapse:collapse' border='1' cellspacing='0'            width='600'></table>");
  out.println("   <tr>");
  out.println("    <td width='100%' style='color:blue'>");
 
  //공지 파일로 부터 자원을 읽어 표현하기 위해 스트림 준비
  BufferedReader in = null;
 
  try{
    //  현재 날짜와 일치하는 파일이 있다면 읽어서 표현한다.
    in = new BufferedReader(new FileReader(path));
    //  이때 현재 날짜로 된 파일이 없다면 FileNotFoundException발생
   
    String msg = null;
    while((msg = in.readLine()) !=null)
     out.println(msg+ "<br>");
       
  }catch(Exception e){
    out.println("오늘은 공지된 사항이 없습니다.");
  }finally{
   try{
     if(in != null)
      in.close();
   }catch(Exception e){}
  }
 
  out.println("    </td>");
  out.println("   </tr>");   
  out.println(" </BODY>");
  out.println("</html>");
  out.close();
 
 }            
}



notice.html  자바스크립트를 활용해 창띄우기


<!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>
<script type="text/javascript">
 function ex(){
  window.open("/0528_Web/NoticeServlet" , "" , "width=604 , height=600");  
 }
</script>
</head>
<body onLoad="ex()">
<h2>Notice Servlet!!</h2>
</body>
</html>