This question already has an answer here:
Change root context for a servlet in an IntelliJ IDEA project
                                
                                    (1个答案)
                                
                        
                                去年关闭。
            
                    
我正在尝试运行我的简单servlet“ Hello”。
我已经安装了tomcat 9.0.6
在新的servlet文件“ myServlet”之后,在src中创建了新包(称为servlet)之后,我在Idea中创建了一个新的JavaEE Web项目(称为测试)。
Project Structure
这是代码:

public class myServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("<html><body>");

    out.println("<h2>Hello my first Servlet</h2>");
    out.println("<br/>");
    out.println("Time on the server is: " + new java.util.Date());

    out.println("</body></html>");
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}


比我打开web.xml并为servlet和servlet映射添加下一行:

<?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>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>servlet.myServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>


成功运行tomcat(“工件已成功部署”)后,我尝试访问URL:http://localhost:8080/test/myServlet结果是第404页...但是,如果我将URL更改为:http://localhost:8080/myServlet结果是正确的。
Result

url有什么问题:http://localhost:8080/test/myServlet ???
需要一些图书馆或什么???
我的错误在哪里?

我也尝试使用@WebServlet(“ / myServlet”)批注,而在web.xml中没有servlet和servlet映射行-结果相同。

最佳答案

您需要在context.xml中定义上下文路径-请参见此链接
http://tomcat.apache.org/tomcat-9.0-doc/config/context.html#Defining_a_context

07-27 18:21