Servlet Tutorial

Servlet Program

Write a servlet which displays current system date and time?

Answer:

Servletprogram: (Since, it's a package to compile use javac -d . DateServ.java)

package ds;

import javax.servlet.*;
import java.io.*;
import java.util.*;

public class DateServ extends GenericServlet {

    public DateServ() {
        System.out.println("SERVLET LOADED...");
    }

    public void init() {
        System.out.println("I AM FROM init METHOD...");
    }

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        Date d = new Date();
        String s = d.toString();
        pw.println("<h1> WELCOME TO SERVLETS <h1>");
        pw.println("<h2> CURRENT DATE & TIME IS : " + s + "<h2>");
    }

    public void destroy() {
        System.out.println("I AM FROM destroy METHOD...");
    }
};

web.xml:

<web-app>
    <servlet>
        <servlet-name>pskills</servlet-name>
        <servlet-class>ds.DateServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>pskills</servlet-name>
        <url-pattern>/pskills</url-pattern>
    </servlet-mapping>
</web-app>