JavaEE 8,Tomcat 8.5,错误状态404

时间:2018-05-21 16:12:09

标签: java tomcat servlets

我正在尝试创建我的第一个servlet,但是我得到了404状态代码。

的web.xml

<?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>Hello</servlet-name>
        <servlet-class>Test.Hello</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>

Hello.java

 package Test;

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;


public class Hello extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
        PrintWriter pw = res.getWriter();
        pw.println("Hello World");
    }
}

我想要运行它: 本地主机:8080 /你好

现在它的状态为404

  

“描述原始服务器未找到当前表示   对于目标资源或不愿意披露该资源   存在“。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

很奇怪,我注意到你的web.xml是4.0版本。你应该能够通过注释使用你的Servlet的url映射。

尝试添加WebServlet注释@WebServlet("/hello"),如下所示:

 package Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet; //IMPORT THIS ALSO
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello") //try adding this here
public class Hello extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
        PrintWriter pw = res.getWriter();
        pw.println("Hello World");
    }
}

然后删除web.xml中的任何映射,如果使用注释则不需要。

<?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">

//remove servlet and mapping    

</web-app>

如果这不起作用,您可以尝试更改您的版本。例如,用这个(版本3.1)替换你的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

</web-app>
相关问题