我正在尝试运行我的简单servlet“Hello”
我已经安装了tomcat 9.0.6
比我在Idea中创建一个新的JavaEE Web项目(称为测试)...在我的src(称为servlet)中创建新包之后,在新的servlet文件“myServlet”之后。
Project Structure
这是代码:
public class myServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello my first Servlet</h2>");
out.println("<br/>");
out.println("Time on the server is: " + new java.util.Date());
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
比我打开web.xml并为servlet和servlet-mapping添加下一行:
<?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>myServlet</servlet-name>
<servlet-class>servlet.myServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>
成功运行tomcat(“Artifact已成功部署”)后,我尝试访问url:http://localhost:8080/test/myServlet
结果是第404页...
但如果我将url更改为:{{ 3}}结果是正确的
http://localhost:8080/myServlet
url有什么问题:Result ???
需要一些库或什么???
我的错误在哪里?
另外我尝试使用@WebServlet(“/ myServlet”)注释而不使用web.xml中的servlet和servlet-mapping行 - 结果相同。
答案 0 :(得分:0)
您需要在context.xml中定义上下文路径 - 请参阅此链接 http://tomcat.apache.org/tomcat-9.0-doc/config/context.html#Defining_a_context