简体   繁体   English

如何使用硬编码的HTML页面发送servlet响应?

[英]How to send servlet response with hardcoded html page?

I'd like to response to a url request with a hardcoded but dynamic html response. 我想使用硬编码但动态的html响应来响应url请求。

Are there better ways than doing following way? 有没有比跟随方式更好的方式?

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

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    //
}

?

一种方法是仅在servlet中转发响应:

getServletContext().getRequestDispatcher("mypage.html").forward(request, response);

It's unclear what you mean by "a hardcoded but dynamic html response." 不清楚“硬编码但动态的html响应”是什么意思。

If you mean that you have some number of existing HTML files, and want to pick one based on request parameters, then your servlet can use Class.getResourceAsStream() to load the files. 如果您的意思是您已有一定数量的现有HTML文件,并且希望根据请求参数选择一个HTML文件,则您的servlet可以使用Class.getResourceAsStream()加载文件。 You'll need to package the files on the classpath, which is easy if you use a tool like Maven, little more difficult with a tool like Ant, and hard to maintain if you're just making builds from Eclipse or the command line. 您需要将文件打包在类路径上,如果您使用Maven之类的工具则很容易,而使用Ant之类的工具则更加困难,并且如果仅从Eclipse或命令行进行构建,则很难维护。

If you mean that you have a single template file and want to change the content in some way, use JSP . 如果您意味着只有一个模板文件,并且想要以某种方式更改内容,请使用JSP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM