Thursday, April 18, 2013

Introduction to Servlets - Write, Deploy & Run

Lets create the servlet.

Step1 - Create a dynamic web project in Eclipse


Step 2: Create the Servlet





doGet() should be as follows 

/**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Hello World!</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Hello World!</h1>");
            out.println("</body>");
            out.println("</html>");
    }
 

Next create the web.xml & place it inside web.xml.

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <servlet>
        <servlet-name>Hello World</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello World</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Right click on the servlet and run



Click the following url to access the page

http://localhost:8080/Hello/hello


Output :

Hello World!

No comments:

Post a Comment

Using Zotero for academic writing