含义

Servlet是一种Web动态开发技术,也是JavaEE的组件之一。

作用

处理请求和响应数据

开发步骤

  1. extends HttpServlet类
  2. 重写doGet()或doPost()方法
  3. web.xml配置

    DateServlet.class
    public class DateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String data = sdf.format(date);
        resp.getOutputStream().write(data.getBytes());
    }
    }
    web.xml
    <servlet>
    //定义servlet的名字
    <servlet-name>dateServlet</servlet-name>
    //Tomcat会根据该值反射创建servlet对象 
    <servlet-class>com.neu.day01.DateServlet</servlet-class>
    </servlet>
    //配置当前servlet能处理怎样的url请求
    <servlet-mapping>
    <servlet-name>dateServlet</servlet-name>
    <url-pattern>/dateServlet</url-pattern>
    </servlet-mapping>

    测试

    JavaWeb之Servlet