In order to generate a servlet-corresponding web page. We need to create a new web. XML, which will place information about the servlet.
The Web. xml file is placed under the webcontent/web-inf/directory. (When we create a new dynamic Web project in Eclipe, there will be a hint of "next", "Generate Web. XML Deployment Descriptor", and checking this option will generate a Web. xml file by default).
We need to configure two pairs of mappings, one for the servlet name and one for his corresponding servlet class, and the other for the servlet and his corresponding URL suffix. So we've got a servlet class and a URL linked together.
We include element servlet and servlet-mapping in Web. XML, as follows:
<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"ID= "webapp_id"version= "3.1"> <Display-name>WebProject</Display-name> <servlet> <Servlet-name>Moonlit</Servlet-name> <Servlet-class>Com.moonlit.MoonlitServlet</Servlet-class> </servlet> <servlet-mapping> <Servlet-name>Moonlit</Servlet-name> <Url-pattern>/page2.do</Url-pattern> </servlet-mapping> </Web-app>
You can see that the moonlit of this servlet name in the servlet is named Com.moonlit.MoonlitServlet, but this class is not yet created, so we now need to create this class.
To create this class, we first need to create a package com.moonlit and then create a class Moonlitservlet in the package com.moonlit.
The moonlit class needs to inherit the HttpServlet class as a servlet class, and because we need this setvlet class to output some of the effects we want, we also need to override the Doget and Dopost methods of this class.
We're asking this servlet to display the current date-related information on the page that corresponds to the earlier one.
Then the Moonlitservlet class is implemented as follows:
PackageCom.moonlit;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.Date;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @SuppressWarnings ("Serial") Public classMoonlitservletextendsHttpServlet {@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {printwriter out=Resp.getwriter (); Out.println ("NewDate () + "</body>" + "); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException { This. Doget (req, resp); }}
Restart the server and you will see that the/page2.do page displays the current date information.
Java Web Project--using a servlet to generate a page