Servlet返回一个空页面

时间:2015-10-07 14:07:02

标签: java servlets

我是servlet的初学者。我只是按照教程创建了一个hello world servlet,但是我得到的页面是一个空白页面。

Servlet类:

public class Test extends HttpServlet {
    public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\" />");
        out.println("<title>Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>page generated from servlet servlet.</p>");
        out.println("</body>");
        out.println("</html>");
    }
}

的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
    <servlet>
        <servlet-name>Test</servlet-name>
        <servlet-class>com.Test</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/toto</url-pattern>
    </servlet-mapping>
</web-app>

我用这个网址打开了网页:http://localhost:8080/testWeb/toto 我有一个空页面,包含任何返回的异常

1 个答案:

答案 0 :(得分:2)

替换&#34; public&#34;从方法名称前面(&#34; doGet&#34;)与&#34; protected&#34;。 &#34; doGet&#34;的范围在HttpServlet类中受到保护(参见https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServlet.html#doGet%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29)。你不能扩展被覆盖方法的范围,只能缩小它,所以你实际上创建了第二个&#34; doGet&#34;方法就容器而言,但具有公共范围。当它管理传入的HTTP请求时,它将GET委托给其默认的受保护范围&#34; doGet&#34;方法,当然不向输出流返回任何内容。因此,要真正覆盖受保护的&#34; doGet&#34;,请写:

protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<meta charset=\"utf-8\" />");
    out.println("<title>Test</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<p>page generated from servlet servlet.</p>");
    out.println("</body>");
    out.println("</html>");
}

另外,我建议冲洗出来的&#39;流;添加:

out.flush();

在所有println()语句之后。容器应该在方法结束时刷新流,但我看到有时候它没有这样做的情况(取决于你正在使用的容器)。为了安全起见。