There is a java servlet:

import java.io.*; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*; public class CurrentDate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Display Current Date & Time"; Date date = new Date(); String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2 align=\"center\">" + date.toString() + "</h2>\n" + "</body></html>"); } } 

When launched, the browser displays the index.jsp page, and not the result of the servlet. Netbeans IDE 8.2. In older versions of Netbeans, there was no such problem, as I recall.

web.xml:

  <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>CurrentDate</servlet-name> <servlet-class>CurrentDate.CurrentDate</servlet-class> </servlet> <servlet-mapping> <servlet-name>CurrentDate</servlet-name> <url-pattern>/CurrentDate</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app> 
  • how do you run, on which server, what's in web.xml? - Nofate
  • I run on Tomcat 8. In the web.xml package and servlet are registered. Text web.xml added to the post - user234904
  • 3
    Well, the servlet catches (url-pattern) / CurrentDate and not the site root. You need to either address the server / CurrentDate url or write something like <welcome-file-list> <welcome-file>CurrentDate</welcome-file> </welcome-file-list> - Morewind

2 answers 2

I have never seen a Servlet run when a web application starts up. By default, always starts Index.jsp or .html But still there is an option to specify in WEB.xml

 <servlet> <servlet-name>nameServlet</servlet-name> <servlet-class>nameServlet</servlet-class> <load-on-startup>0</load-on-startup> // Тут указывается порядок запуска </servlet> 

Calls the init() servlet method.

  • How then can I run Index.jsp and get the data from the database when I first start it (how to work the servlet) to insert it into the view? - Sergei R

You send html page. Therefore not performed. Initialize the servlet manager. + suffix and prefix specify. then the servlet is sent.