What we need to know about Servlet:
- Servlet is one of the JavaEE specifications. The specification is the interface
- Servlet is one of the three major components of JavaWeb. The three major components are Servlet program, Filter filter, Listener listener
- Servlet is a small Java program running on the server, it can receive the request sent by the client, and respond to the data to the client
Steps to manually implement the Servlet program:
- Write a class to implement the Servlet interface
- Implement the service method to process the request and respond to the data
- Go to web.xml to configure the access address of the servlet program
First, create a Module note:
Create a class in Module, inherit Servlet, alt+insert rewrite all methods
Pay attention to the service method:
service方法是专门用来处理请求和响应的(只要访问HelloServlet程序,他就会执行这个方法)
HelloServlet:
package com.servlet1;
import javax.servlet.*;
import java.io.IOException;
public class HelloServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* service方法是专门用来处理请求和响应的(只要访问HelloServlet程序,他就会执行这个方法)
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("HelloServlet被访问了");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
Next configure web.xml:
Two points of concern:
- Write the servlet tag first, fill in the servlet-name and servlet-class
- After writing the servlet tag, I found an error was reported because the access address was not configured. Use the servlet-mapping tag to configure an access address for the servlet program, and fill in the servlet-name and url-pattern
<?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_4_0.xsd"
version="4.0">
<!-- servlet标签是给Tomcat配置Servlet程序的 -->
<servlet>
<!-- servlet-name标签给Servlet起一个别名(一般为类名) -->
<servlet-name>HelloServlet</servlet-name>
<!-- servlet-class是Servlet的全类名 -->
<servlet-class>com.servlet1.HelloServlet</servlet-class>
</servlet>
<!-- servlet-mapping标签给servlet程序配置一个访问地址 -->
<servlet-mapping>
<!-- servlet-name标签的作用是告诉服务器,我当前的配置的地址给哪个servlet程序使用-->
<servlet-name>HelloServlet</servlet-name>
<!-- url-pattern标签配置访问地址 可以自定义地址
/ 在服务解析的时候表示地址为 http://ip:port/工程路径
/hello 表示地址为 http://ip:port/工程路径/hello
-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Project path:
run:
Enter the address set in url-pattern in the browser
operation result: