Spring-无法映射Servlet。它返回404-找不到

时间:2019-03-26 11:00:47

标签: java spring tomcat

我正在尝试制作一个简单的servlet,但是错误状态为404 Not Found。

这是我的servlet代码

package servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "ServletExample", urlPatterns = "/theServlet")
public class ServletExample extends javax.servlet.http.HttpServlet {
    private String message;

    @Override
    public void init() throws ServletException {
        message = "Hello from the servlet";
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //set response type
        response.setContentType("text/html");

        //actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println("<h1>" + message + "</h1>");
    }

    @Override
    public void destroy() {
        //do nothing
    }

}

这是我的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>ServletExample</servlet-name>
        <servlet-class>servlets.ServletExample</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletExample</servlet-name>
        <url-pattern>/Example</url-pattern>
    </servlet-mapping>
</web-app>

我尝试过的网址:

http://localhost:8080/Project/Example

http://localhost:8080/Example

http://localhost:8080/theServlet

http://localhost:8080/Project/theServlet

2 个答案:

答案 0 :(得分:0)

尝试删除web.xml中有关sevlet映射..和.. balise的行,因为您已经在类中定义了此配置,并且可以通过http://localhost:8080/Project/theServlet调用servlet。

答案 1 :(得分:0)

为什么同时使用批注和web.xml。 “最佳实践”是尝试使用其中一种。如果您选择对所有Servlet配置依赖注释,则可以完全删除web.xml文件。但是,我仍然鼓励您保留该文件,或者至少保留以下示例所示的文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Servlet with Annotations Application</display-name>
</web-app>

并尝试致电http://localhost:8080/Project/theServlet