logo头像

技术引领生活!

servlet入门

本文于652天之前发表,文中内容可能已经过时。

新版的 servlet 3.0版本遇到的坑,特此记录下

遇到的坑

先说下运行环境吧,网上的东西大多数都是过时的,导致本菜撸了几天, 运行Servlet后一直显示 HTTP状态 404 - 未找到
报错

运行环境

  • java 11.08
  • servlet 3.0
  • tomcat 7.0

步骤

  1. 下载Java EE

  2. 新建 web–> Dynamic Web Project 选择一个已有文件夹,新建一个文件夹helloservlet输入工程名 helloservlet
    新建工程

  3. 在eclipse中找到src右键new,新建一个servlet,输入class 名字,package名可以不输入
    新建Servlet

  4. 新建tomcat服务器
    请注意,如果有请先删除后重建一个tomcat服务器

新建tomcat服务

  1. 输入网址
    http://localhost:8080/工程名/映射名, 其实这里的类名为@WebServlet(“/映射名”)映射名,自动生成的话也就是类名, 可以手动修改

最终效果

验证下代码网址 同时修改,比如修改为jack,修改映射后如下图所示
修改映射名后

总结

  1. 不用写web.xml,不用写web.xml,不用写web.xml,重要的事情说三遍
  2. 网址路径为工程名+映射名
  3. 要新建一个tomcat服务器
  4. 网上的教程很多都是过时的
  5. 如果非要兼容过去的写web.xml,请把代码中的@WebServlet(“/映射名”)注释掉
    web.xml 文件如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

    <servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>
    </web-app>

    代码

    没啥可说的都是自动生成的
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * Servlet implementation class ServletDemo
    */
    @WebServlet("/ServletDemo")
    public class ServletDemo extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
    * @see HttpServlet#HttpServlet()
    */
    public ServletDemo() {
    super();
    // TODO Auto-generated constructor stub
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
    }
    }
支付宝打赏 微信打赏

您的支持是我前行的动力!