我在Java(Eclpise EE)中使用Webservlet,它按如下方式动态打印文本:
@WebServlet("/test")
public class MyApp extends HttpServlet
{
HttpSession session = request.getSession(true);
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println(ProcessEvent());
}
我设计了一个简单的模板(default.html
)文件,其中一面带有彩色背景和图像。 html是Eclipse中项目的一部分。
如何让应用程序在此default.html文件上打印,而不是通过out.println()
在空白页上打印纯文本?
答案 0 :(得分:1)
如果您想要一个超级简单的Web应用程序,其中JSP
页面将用作视图技术而Servlet
将提供业务逻辑,以下示例可能对您有所帮助:
第1步:在Eclipse sample.jsp
的{{1}}中创建以下/WebContent/WEB-INF/templates
Dynamic Web Project
第2步:创建以下<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Page</title>
</head>
<body>
<b>Time Now:</b> ${requestScope["time"]}
</body>
</html>
以提供Servlet
页面的业务逻辑:
JSP
第3步:点击以下网址调用上述import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test")
public class MyApp extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyApp() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("time", new Date()); // 'time' would be shown on JSP page
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/templates/sample.jsp");
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
:
Servlet
输出如下所示: