【问题标题】:URL localhost:8080/<project_name>/Servlet don't works [duplicate]URL localhost:8080/<project_name>/Servlet 不起作用 [重复]
【发布时间】:2018-04-05 12:23:04
【问题描述】:

我正在尝试运行我的简单 servlet“Hello”。
我已经安装了tomcat 9.0.6
比我在 Idea(称为测试)中创建一个新的 JavaEE Web 项目...在我在 src(称为 servlet)中创建新包之后,在新的 servlet 文件“myServlet”之后。
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-mapping 添加下一行:

<?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
网址有什么问题:http://localhost:8080/test/myServlet ???
需要一些图书馆还是什么???
我的错在哪里???

我也尝试使用 @WebServlet("/myServlet") 注释而不使用 web.xml 中的 servlet 和 servlet-mapping 行 - 结果相同。

【问题讨论】:

标签: java tomcat servlets localhost servlet-3.0


【解决方案1】:

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

【讨论】:

  • 谢谢,现在我可以更改上下文路径了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 2018-07-24
  • 2013-06-29
  • 2019-11-19
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多