Java Servlet Example 3

3. Develop a servlet that displays the number of visits on the servlet. Also display the client’s hostname and IP address, as shown in Figure. Use an instance variable to store count. When the servlet is created for the first time, the count is 0. count is incremented every time the servlet’s doGet method is invoked. When the Web server stops, the count is lost.

getRemoteHost()

getRemoteAddr()

Screen Shot 2018 03 09 at 3.56.54 PM - Java Servlet Example 3

  • VisitorServlet.java (put it in the “src” folder)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/VisitorServlet") public class GreetingServlet extends HttpServlet {
static int count = 0;     
protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");         
PrintWriter out = response.getWriter();         
// client's IP address         
String remoteAddr = request.getRemoteAddr();         
// client's hostname         
String remoteHost = request.getRemoteHost();         
if (count == 0){             
out.print("<h3>");             
out.print("Welcome to the fist Time </h3>");             
count++;         
} else {            
 out.print("<h3>You have visited " + count + " times");         
    count++;             
out.print("</h3>");      
   }         
out.println("Host name: ");         
out.print(remoteAddr);       
  out.println("<br>");         
out.println("IP address:");         
out.print(remoteHost);        
 out.close();    
 } }
  • index.jsp(put it in the “web” folder) 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
   <head>
     <title></title>
   </head>
   <body> </body>
 </html>
  • web.xml(put it in the “WEB-INF” folder which resides inside the “web”.) 

      Note: This step is not mandatory. You may choose not to do it. And the program will still run. 

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, 
Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> 
<web-app> 
    <display-name>myweb</display-name> 
    <!-- Servlet Definitions  --> 
   <servlet> 
      <servlet-name>VisitorServlet</servlet-name> 
      <servlet-class>VisitorServlet</servlet-class>  
  </servlet> 
<!--   Servlet Mappings   --> 
   <servlet-mapping> 
      <servlet-name>VisitorServlet</servlet-name> 
       <url-pattern>/VisitorServlet</url-pattern>  
  </servlet-mapping> 
</web-app>  

Note: To run this program, type inlocalhost:8080/VisitorServlet the browser URL. Click here if you don’t know how to set up a servlet project in NetBeans.

 

 

Java Servlet Example 2

HTML Form

Screen Shot 2018 03 09 at 4.00.55 PM - Java Servlet Example 2 Screen Shot 2018 03 09 at 4.01.09 PM - Java Servlet Example 2

  • index.jsp (put it in the “web” folder) 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Calculator</title>
</head>
<body bgcolor="aqua">

<form method="post" action="GreetingServlet">


  <h3 style="text_align:center;">Choose an operation:
    <input type="radio" name="r1" value="add" />addition
    <input type="radio" name="r2" value="sub" />subtraction
    <input type="radio" name="r3" value="mul" />multiplication
    <input type="radio" name="r4" value="div" />division
  </h3>

  </label>
  <label>Choose 1<sup>st</sup> number:</label>
  <input type="text" name="n1" />
  <br>
  <label>Choose 2<sup>nd</sup> number:</label>
  <input type="text" name="n2" />
  <br>
  <label>
      <input type="submit" value="Submit" style="background-color: hotpink">
  </label>

</form>
</body>
</html>

  • FormServlet.java (put it in the “src” folder) 

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


@WebServlet("/FormServlet")
public class GreetingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try
        {
            response.setContentType("text/html");
            PrintWriter out= response.getWriter();
            out.println("<body style='background-color:black;color:yellow;'>");
            out.println("<h3 style='color:red;'>Output of your inputs </h3>");
            int a1= Integer.parseInt(request.getParameter("n1"));
            int a2= Integer.parseInt(request.getParameter("n2"));
            if(request.getParameter("r1")!=null)
            {
                out.println("<p>Addition</p>"+(a1+a2));
            }
            if(request.getParameter("r2")!=null)
            {
                out.println("<p>Subtraction</p>"+(a1-a2));
            }
            if(request.getParameter("r3")!=null)
            {
                out.println("<p>Multiplication</p>"+(a1*a2));
            }if(request.getParameter("r1")!=null)
        {
            out.println("<p>Division</p>"+(a1/a2));
        }
        }
        catch(Exception e)
        {
            System.out.println("error" + e.getMessage());

        }
    }
}

Note: To run this program type: localhost:8080 in the browser URL. 

Click here if you don’t don’t how to set up a NetBeans servlet project. 

java servlet

What the fuck is a java servlet?

 

Remember Java’s write once, run anywhere bullshit? Run anywhere…  Yeah, well Java programs can run on anything that has JVM. A toaster with JVM can run Java. An iPhone without it cannot. TAKE THAT JAVA! Well, it hasn’t stopped java developers to develop apps on iPhone using Java though. You see, this magical JVM thingy works and is fast enough because it is written in C/C++ for that specific OS. But the fucking pointers suck the life out of you so let’s stick to Java for now. 

 

WHAT THE FUCK IS A JAVA SERVLET THEN? 

As you’ve noticed I’ve just beat around the bush and haven’t still answered what the fuck Java Servlet is till now. Well, what if you wanted to leave the comfort of your desktop and mobile phone and wanted to develop apps for the good OL‘ web. Could you still do that? Now, what fun is it … if a language claims to run everywhere and can’t even run on the web. That would suck, right? 

Well for all the Java evangelists, the good news is that Java comes with full-fledged Servlet API which lets you build web apps without much hassle, unlike non-standard CGI thingy that Java used to have which we are not going to talk about because fuck it. 

 

WHAT? HOW THE HELL, DOES IT DO THAT? 

Think of a Servlet as a Java program or a Java class that is executed within the scope of Servlet containers (or web containers). You must be thinking, hold on their chief? What the fuck is a Web container now? Shit like Tomcat, Jetty etc. allow handling client requests and server responses and they are Web containers. 

Servlets use GET and POST request thingies to be able to snatch data from users. They can handle session and cookies thingies. They can process the motherfucking data and output the data in both text and binary formats such as XML, HTML, pdf, gif etc. They may use a thingy called JSP in many cases which we’ll talk about some other time.