Java Reference
In-Depth Information
The above steps are normally carried out by doGet or doPost . Note that these
methods may generate IOException s and ServletException s, which are checked
exceptions (and so must be either thrown or handled locally). Note also that step 4
involves a lot of tedious outputting of the required HTML tags.
Finally, as of Tomcat 7, a WebServlet annotation tag is required before the open-
ing line of the servlet class. This tag indicates the name of the servlet and the path
to it (relative to the classes folder) and has the following format:
@WebServlet(“/<Path>/<ServletName>”)
Example
This fi rst servlet simply displays the message 'A Simple Servlet'.
[In passing, note that CSS scripts will not work with servlets , and so the con-
ventional HTML tag <CENTER> (not supported in HTML 5) has had to be used
below! The same comment applies to the <FONT> tag in later examples.]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException
{
response.setContentType("text/HTML");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Simple Servlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><BR>");
out.println(
"<CENTER><H1>A Simple Servlet</H1></CENTER>");
out.println("</BODY>");
out.println("</HTML>");
out.fl ush();
}
}
Note the use of method fl ush of the PrintWriter object to send data out of the
object's buffer.
Search WWH ::




Custom Search