目前正在阅读 Head First Servlet Jsp。我目前停留在映射 servlet。这可能是一个愚蠢的问题,但是如何正确映射 servlet url 模式?我正在使用 eclipse mars,这是我第一次使用 jsp/servlets。创建动态 Web 项目时,我总是检查生成的 Web xml
这是默认 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"
id="WebApp_ID" version="3.1">
<display-name>HeadFirst</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
它使用这个运行
http://localhost:8080/HeadFirst/Ch2Servlet
但是当我在显示名称下方添加它时
<servlet>
<servlet-name>Ch2Servlet</servlet-name>
<servlet-class>com.test.hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ch2Servlet</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
它给了我一个 404 错误,这是 url
http://localhost:8080/HeadFirst/servlet/com.test.hello.Ch2Servlet
这是我的 servlet 类
@WebServlet("/Ch2Servlet")
public class Ch2Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
java.util.Date today = new java.util.Date();
out.println("<h1>Hello World</h1>" + "<br>");
out.println("Date today is " + today + "<br>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
顺便说一句,我读过这篇文章,但仍然很困惑 Java Servlet URL Mapping Servlet Mapping using web.xml edit added my serlvet class