PrintNamesServlet.java
:
This servlet prints the entered name of the user.
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;@WebServlet(name = "PrintNamesServlet")public class PrintNamesServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Ram Dhakal"); }}
CounterServlet.java
:Counts the number of hits or visit in the page
import javax.servlet.ServletException; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; import java.io.IOException;import java.io.PrintWriter;@WebServlet(name = "CounterServlet") public class CounterServletextends HttpServlet { int totalHits; public void init() throws ServletException{ totalHits = 0; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print("Total visit count: " + totalHits++); } public void destroy(){ } }
web.xml
:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"><servlet><servlet-name>PrintNamesServlet</servlet-name><servlet-class>PrintNamesServlet</servlet-class></servlet><servlet-mapping><servlet-name>PrintNamesServlet</servlet-name><url-pattern>/PrintNamesServlet</url-pattern></servlet-mapping><servlet><servlet-name>CounterServlet</servlet-name><servlet-class>CounterServlet</servlet-class></servlet><servlet-mapping><servlet-name>CounterServlet</servlet-name><url-pattern>/CounterServlet</url-pattern></servlet-mapping></web-app>
I am getting error:
No webpage was found for the web address: http://localhost:8080/
As, I am trying to run the servlet for the first time, I am not getting what is wrong with my code. I typed http://localhost:8080/PrintNamesServlet
in the url.