A servlet is a server-side program written in the Java programming language that interacts with clients and is usually tied to a HyperText Transfer Protocol (HTTP) server. One common use for a servlet is to extend a web server by providing dynamic web content.
Servlets have an advantage over other technologies in that they are compiled, have threading capability built in, and provide a secure programming environment. Even web sites that previously did not provide servlet support, can do so now by using programs such as JRun or the Java module for the Apache web server.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("");
out.println("");
out.println("Hello, " + name);
out.println("");
}
public String getServletInfo() {
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
Methods of HttpServlet class
Let's examine the methods which this class provides one by one :
- init()Called only once during the initialization of the Servlet.
- destroy()Called only once when Servlet instance is about to be destroyed.
- service()Do not override this method.
- doGet(), doPost(), doPut(), doDelete(), doOptions, doTrace()These methods are called according to the type of HTTP request received. Override them to generate your own response.
- log()Writes messages to the Servlet's log files.
- getLastModified()Override this method to return your Servlet's last modified date.
- getServletInfo()Override this method to provide a
String
of general info about your Servlet such author, version, copyright etc. - getServletName()Override this method to return name of the Servlet.
- getInitParameter(), getInitParameterNames()First one returns value of given initialization parameter, second one returns an
Enumeration
object containing names of all initialization parameters provided
No comments:
Post a Comment