【发布时间】:2021-04-15 10:17:26
【问题描述】:
要向 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。那么为什么会有不同的行为呢?我知道我错过了什么,我只是不知道是什么......
【问题讨论】:
-
参见this 的第一个要点。简短的版本是 Servlet 容器通常在内部注册一个能够编译和服务 JSP 的 Servlet。该 servlet 已注册到类似
*.jsp的位置。这就是处理您的第一个示例的方法。
标签: java xml jsp servlets annotations