当前正在读取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映射使用web.xml的Servlet映射edit添加了我的serlvet类
url不是:
http://localhost:8080/HeadFirst/servlet/com.test.hello.Ch2Servlet
它将是:
http://localhost:8080/HeadFirst/HelloWorld
更具体地说,它将是您设置为<url-pattern>...</url-pattern>
的值