Apache Tomcat和servlet

时间:2016-06-22 16:49:08

标签: apache tomcat servlets java-ee

我已经在maven web应用程序中与servlet挣扎了好几个小时。我无法运行它。它始终返回请求的资源不可用。我使用的是Tomcat 8.这是我的servlet代码。我使用此地址http://localhost:8080/my-app/MyServlet来运行它,但我没有成功。

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MyServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  1. 使用http://localhost:8080检查tomcat是否正常工作(显示Tomcat欢迎页面)

  2. 检查您的上下文路径是否为&#34; / my-app &#34;,&#34; / &#34;或者是其他东西。例如如果您的上下文路径只是 / ,则http://localhost:8080/MyServlet应该有效。