2가지 방법
- Servlet 에서 순수하게 Java 코드 사용
- Servlet 에서 Javascript (Jquery) 사용
(추천하지 않음, jsp를 따로 생성하여 받아오는 방법 추천)
1. Servlet 에서 Java 사용
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 3초 후에 현재 시간 생성
try {
Thread.sleep(10000);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sim = new SimpleDateFormat
("yyyy년MM월dd일HH시mm분ss초");
response.setContentType("text/html;charset=euc-kr");
String now = sim.format(cal.getTime());
PrintWriter write = response.getWriter();
write.print("<html>");
write.print("<head></head>");
write.print("<body>");
write.print(now);
write.print("</body>");
write.print("</html>");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2. Servlet 에서 Jquery 사용
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=euc-kr");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>계기서블릿</title>");
out.print("<script src='jquery-1.11.1.js'></script>");
out.print("<script type='text/javascript'>");
out.print("setTimeout(function ()" +
"{ $('h1').html(new Date().toLocaleDateString()" +
"+new Date().toLocaleTimeString())},1000);");
out.print("</script>");
out.print("<body>");
out.print("<h1></h1");
out.print("</body>");
out.print("</html>");
}
}