在Java Servlet中生成HTML响应

oge*_*ogu 48 html servlets

如何在Java servlet中生成HTML响应?

Bal*_*usC 102

您通常会将请求转发给JSP进行显示.JSP是一种视图技术,它提供了一个模板来编写普通的HTML/CSS/JS,并提供了在taglib和EL的帮助下与后端Java代码/变量进行交互的能力.您可以使用像JSTL这样的taglib来控制页面流.您可以将任何后端数据设置为任何请求,会话或应用程序范围中的属性,并使用${}JSP中的EL(事物)来访问/显示它们.

开球示例:

@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);
    }

}
Run Code Online (Sandbox Code Playgroud)

/WEB-INF/hello.jsp像这样:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

打开http:// localhost:8080/contextpath/hello时会显示

Message: Hello World

在浏览器中.

这使Java代码免于HTML混乱,并大大提高了可维护性.要使用servlet学习和练习更多内容,请继续以下链接.

还可以浏览标记为[servlet]的所有问题的"常用"选项卡,以查找常见问题.

  • 这仍然是一种有效的方法吗?我总是听到我们的首席架构师说根本不使用JSP,但我问自己应该如何创建所有HTML?以编程方式逐个创建每个元素?这可能需要永远. (2认同)
  • @Timo:要么你误解了你的架构师,要么你的架构师需要阅读http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files,http://stackoverflow.com/questions/2095397/jsf-servlet-and-jsp和http://stackoverflow.com/tags/servlets/info之间的区别是什么如果仍然不相信,那就开火自己并寻找另一个项目. (2认同)

cod*_*ict 35

你需要一个doGet方法:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}
Run Code Online (Sandbox Code Playgroud)

您可以看到这个简单的hello world servlet的链接

  • 不建议以这种方式从servlet生成HTML.那是1998年的老式成语.更好的解决方案是使用JSP. (13认同)
  • 或者使用一些框架/工具,如dojo,GWT等,并将客户端html与服务器端代码完全分开. (2认同)
  • @duffymo:但有时,在某些情况下,我想从 Servlet 生成正在进行的进度 html 响应。并非所有东西都适合 MVC。 (2认同)

归档时间:

查看次数:

128894 次

最近记录:

8 年,5 月 前