How to invoke a servlet API in Java?
To call the Servlet interface, you need to create a class that extends the HttpServlet class. Then, override the doGet() or doPost() method and implement the necessary business logic as needed.
Here is an example code:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置响应内容类型
response.setContentType("text/html");
// 实现业务逻辑
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
Configure Servlet mapping in the web.xml file.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
By accessing http://localhost:8080/yourWebAppName/hello in the browser, the doGet() method in the MyServlet class will be called and the result will be output to the browser.
Please note that this is just a simple example and additional logic and handling methods can be added as needed in actual applications.