Sunday, September 13, 2015

Hello World Servlet in Java

I just started how to learn how to program a Java Servlet so the basic program that I wrote is the famous hello world program with a simple math functions in Java like square root and cube root. In this program I am using Eclipse as my text editor and Apache Tomcat 8.0 as my web server.  This program is very simple yet is show you how to write a simple Java servlet that is the fundamentals of any web applications written in Java.

If you  have some questions please send me an email at jake.r.pomperada@gmail.com and jakerpomperada@yahoo.com. My mobile number here in the Philippines is 09173084360.




Sample Program Output

Program Listing

package company.helloworld.servlets;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
double sqrtvalue = Math.sqrt(144.0);
double cuberoot = Math.cbrt(8.0);
out.println("<html><body> <font color='green'>  <h1 align='center'>Hello World Servlet </h1> "
+ "The square root of 144 is "  + sqrtvalue
+ "<br>The cube root of 8 is "  + cuberoot + "</font> </body></html>");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

No comments:

Post a Comment