我正在尝试在Eclipse上使用Java Servlet,Tomcat和HTML制作Web应用程序。我的问题是,在创建动态Web项目以及web.xml和index.html文件之后,index.html页面什么都不显示。
Servlet:
@WebServlet("/index.html")
public class AppServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String HTML_START = "<html><body>";
private static final String HTML_END = "</body></html>";
public AppServlet() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="styling.css">
<title>Test page</title>
</head>
<body>
<h1 style="text-align:center;">Example text</h1>
<div align="center">
<textarea rows="12" cols="120" style="border-radius: 5px"></textarea>
</div>
</body>
</html>
当我直接打开它时(当我双击目录中的文件时),html页面显示的很好,但是当我从Eclipse启动服务器并将其重定向到localhost:8080 / MyProject / index.html时,什么都没有显示。
您抓住了那个PrintWriter,但是您什么也不做。在代码段的第一行,您已经告诉服务器要使用代码来管理/index.html,因此不应从静态内容中获取它。然后,您的代码什么也没有产生,因此您可以正确地看到自己的代码产生了什么。
尝试在PrintWriter out = response.getWriter()之后添加此内容;
out.println(HTML_START);
out.println("Hello World!");
out.println(HTML_END);
每个URL可以由单个组件处理:URL可以解析为文件[[index.html或servlet。在您的情况下,servlet具有更高的优先级,并且该servlet(不是文件index.html)创建结果。您的Servlet不会在doGet方法中创建任何内容。因此,响应自然为空。
如果要将此URL解析为文件index.html,则在servlet中使用其他URL映射,例如@ WebServlet(“ / bla”)
)。然后,当您调用...... / MyProject / index.html时,将获得文件index.html的内容。