Wednesday, July 16, 2014

Simple example of SERVLET !

Below is the sample program of SERVLET which is taken from known J2EE book ! You can start this example by simply craeting new project in Netbeans and again do right click and select Servlet option and when you do next, make sure you tick on create XML file. 

Don't worry if you feeling tense after see this coding but I just want to inform the new guys who are new to the J2EE, the syntax of the coding is fixed and it's already ready for you by netbeans, you just have to do your part of coding in the middle of this.

In this example, this is just the simple small random number program that we see in core java but the difference is, this is ruining on web browser. Here, I have write the name of the servlet is GuessWhat but you can name it whatever you like so don't worry about that.




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 GuessWhat extends HttpServlet {

  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
           
            String d1=Integer.toString((int)((Math.random()*99)));
            String d2=Integer.toString((int)((Math.random()*99)));
            
            
            out.println("<html> <body> "+ "<h1 align=centre>Let's guess the number by pressing F5</h1>"+
                    "<h2> This time " + d1 + " and "+ d2 +" are the right answer, now time to guess another numbers !</h2>"+"</body>"+"</html>");
            
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    
    @Override
    public String getServletInfo() {
        return "Short description";
    }

}