简体   繁体   中英

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.

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."

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. 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.

If you mean that you have a single template file and want to change the content in some way, use JSP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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