hello servlet

Hello Servlet

1.构建maven项目

2.导入依赖

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>

3.编写一个Servlet程序

1.编写一个普通类。

2.实现Servlet接口,这里继承Servlet的实现类HttpServlet。

3.重写doGet() 和doPost() 方法。

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ai lin
 * @create 2022-01-16-0:40
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.print("<html>");
        writer.print("<head>");
        writer.print("<title>Hello word!</title>");
        writer.print("</head>");
        writer.print("<body>");
        writer.print("<h1>hello word</h1>");
        writer.print("</body>");
        writer.print("</html>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

4.在web.xml编写servlet 映射。

 <!--注册servlet-->
    <servlet>
        <servlet-name>helloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <!--一个servlet对应一个servlet—mapping :映射-->
    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <!--访问路径-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

5. 配置tomcat

注意路径

hello servlet

6.运行结果

hello servlet

上一篇:Hutool工具类的使用(一)之实现快速生成表格


下一篇:语音识别-初识