为什么我需要 Servlet 的映射或注解,而不是 JSP?

Why I need mapping or annotation for Servlet, but not for JSP?

要向 Servlet 发出请求,我需要在 XML 文件中使用映射或为给定的 Servlet 添加注释。但是为什么我不需要对 JSP 文件也做同样的事情呢?我举个例子。

这是如何工作的?

index.html:

<html><body>
 
    <form action="result.jsp">
        <button>go</button>
    </form>
    
</body></html>

result.jsp:

<html><body>
hello
</body></html>

请注意,我不必使用任何 XML 映射或注释。它只是“找到”它。

但这怎么行不通呢?

index.html:

<html><body>
 
    <form action="com.example.MyServlet">
        <button>go</button>
    </form>
    
</body></html>

com.example.MyServlet:

public class MyServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        resp.setContentType("text/html");
 
        pw.println("hello");
 
    }
}

在这里,我收到错误消息:请求的资源 [/TestProject/com.example.MyServlet] 不可用。如何?为什么我不需要使用 XML,也不需要使用 JSP 的注释,但我需要使用 Servlet?他们不应该以同样的方式工作吗,因为 JSP 最终转向了 Servlet。那么为什么会有不同的行为呢?我知道我错过了什么,我只是不知道是什么...

Why I need mapping or annotation for Servlet, but not for JSP?

正如@SotiriosDelimanolis 在上面的评论中指出的那样,实际情况并非如此。 JSP 最终会变成一个 servlet,其行为与您自己定义的任何其他 servlet 一样。当您定义一个 servlet 时,您还需要添加一个 URL 映射,以便将 URL 路径解析为一个 servlet,该 servlet 可以响应针对该 URL.[=15 发出的请求=]

唯一的区别是,对于 JSP 文件,此映射由 servlet 容器隐式完成。对于你定义的servlet,你显然需要定义你自己的映射,因为服务器无法知道你想用你自己的应用程序中的servlet做什么。

The specifications 说了以下内容(强调我的):

A web component is either a servlet or a JSP page. The servlet element in a web.xml deployment descriptor is used to describe both types of web components. JSP page components are defined implicitly in the deployment descriptor through the use of an implicit .jsp extension mapping, or explicitly through the use of a jsp-group element.

[...] JSP page translated into an implementation class plus deployment information. The deployment information indicates support classes needed and the mapping between the original URL path to the JSP page and the URL for the JSP page implementation class for that page.

所以基本上,您的 JSP 被翻译成一个 servlet,并且从您的原始 JSP 页面位置路径到由此生成的 servlet 创建了一个映射。

JSP并没有真正执行。执行的是从 JSP 生成的 servlet。您必须意识到 JSP 是为了方便而提供的。如果你想从 servlet 生成 HTML,你必须为整个 HTML 页面做一大堆 out.write("<html>"); out.write("\r\n"); 等等。这不仅非常容易出错,而且这样做你会发疯的。因此,提供 JSP 的选项与幕后所做的事情相结合,使一切正常。