在 Java Servlet 中生成 HTML 响应 [英] Generate an HTML Response in a Java Servlet
问题描述
如何在 Java servlet 中生成 HTML 响应?
How do I generate an HTML response in a Java servlet?
推荐答案
您通常将请求转发到 JSP 进行显示.JSP 是一种视图技术,它提供了一个模板来编写普通的 HTML/CSS/JS,并提供在标签库和 EL 的帮助下与后端 Java 代码/变量交互的能力.您可以使用 JSTL 等标签库来控制页面流.您可以将任何后端数据设置为任何请求、会话或应用程序范围中的属性,并在 JSP 中使用 EL(${}
事物)来访问/显示它们.您可以将 JSP 文件放在 /WEB-INF
文件夹中,以防止用户在不调用预处理 servlet 的情况下直接访问它们.
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${}
things) in JSP to access/display them. You can put JSP files in /WEB-INF
folder to prevent users from directly accessing them without invoking the preprocessing servlet.
启动示例:
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
和 /WEB-INF/hello.jsp
看起来像:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
打开 http://localhost:8080/contextpath/hello 时会显示
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
在浏览器中.
这使 Java 代码免受 HTML 混乱并大大提高了可维护性.要学习和练习 servlet 的更多信息,请继续访问以下链接.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
- 我们的 Servlets wiki 页面
- servlet 如何工作?实例化、会话、共享变量和多线程
- Servlet 中的 doGet 和 doPost
- 在页面加载时从 JSP 文件调用 servlet一个>
- 如何从提交 HTML 表单时 JSP 到 servlet
- 使用 MVC 和 DAO 模式在 JSP 页面中以 HTML 格式显示 JDBC ResultSet莉>
- 如何使用 Servlet 和 Ajax?
- Servlet 返回HTTP"状态 404 请求的资源(/servlet)不可用"
还浏览Frequent"标记为 [servlets] 的所有问题的选项卡以查找常见问题.
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
这篇关于在 Java Servlet 中生成 HTML 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!