1. Create a Web project, the business class MyServlet class code is as follows:
package com.yoko; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * Familiar with Servlet interface * @author Yoko */ public class MyServlet implements Servlet{ ServletConfig servletConfig = null; /* * This method is a servlet life cycle method used to initialize the servlet and is called once by the web container. */ public void init(ServletConfig config) throws ServletException { this.servletConfig = config; System.out.println("Initialize servlet"); } /* * This method is a servlet life cycle method that provides responses for incoming requests and is called by each request from the web container */ public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.print("<html><body>"); writer.print("<div style=\"text-align:center;\"><h2>创建简单Servlet</h2></div>"); writer.print("</body></html>"); } /* * This method is a servlet life cycle method, indicating that the servlet is being destroyed and is only called once */ public void destroy() { System.out.println("销毁Servlet"); } /* * This method returns the ServletConfig object */ public ServletConfig getServletConfig() { return servletConfig; } /* * Returns information about the servlet, such as author name, copyright, version, etc. */ public String getServletInfo() { return "author YOKO"; } }
2. The configuration code of the web.xml file in the project is as follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- stands for servlet --> <servlet> <!-- Represents the name of the servlet, defined by the user --> <servlet-name>MyServlet</servlet-name> <!-- represents the classpath of the servlet --> <servlet-class>com.yoko.MyServlet</servlet-class> </servlet> <!-- for mapping servlets --> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <!-- Client used to call servlet --> <url-pattern>/index.jsp</url-pattern> </servlet-mapping> </web-app>
After running successfully, its page is displayed as follows: