gpt4 book ai didi

JavaEE 8、Tomcat 8.5、错误状态 404

转载 作者:行者123 更新时间:2023-11-28 22:16:09 25 4
gpt4 key购买 nike

我正在尝试制作我的第一个 servlet,但我收到 404 状态代码。

网络.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>

你好.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

"Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."

我该如何解决这个问题?

最佳答案

很奇怪,我注意到你的 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>

如果这不起作用,您可以尝试的另一件事是更改您的版本。例如,将您的 web.xml 替换为这个(3.1 版):

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

关于JavaEE 8、Tomcat 8.5、错误状态 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com