Monday, 14 July 2014

Hello World Servlet Application

I am using Netbeans IDE to show how to deploy a servlet. You can download Netbeans IDE from https://netbeans.org/

Creating a Web Application Project

1.Open new Project, select “Java Web” from Categories section and select “Web Application” from Projects section.


2. Give “servlet” as Project name. Press Next.


3. Select the server and press next.


4. No need to select any thing here, simply press next.


Writing Servlet Application 

1. Open new file select “Web” from Categories and Select “Servlet” from File Types. Press Next


2. Give the Class name as Hello and Press Next


3. Update the URL Pattern entry as “/HelloWorld” and press FInish


4. Update Hello.java with the below code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Hello extends HttpServlet {

   
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
       
       PrintWriter out = res.getWriter();
       res.setContentType("text/html");
       String str = "<html>" +
                    "<head>" +
                    "<title> Hello World </title>" +
                    "</head>" +
                    "<body>" +
                    "<h1> Hello World " +
                    "</h1> </body>" +
                    "</html>";
       out.println(str);
   } 
}

5. Create a jsp file and give it a name main.jsp, for time being assume jsp like simple html file.





6. Write the below code to main.jsp
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="/servlet/HelloWorld">
            <input type="submit">
        </form>
    </body>
</html>

7. Now run main.jsp You find below screen



Click on the button and you can see new html page with message “Hello World”.










Prevoius                                                 Next                                                 Home

No comments:

Post a Comment