Generate an HTML Response in a Java Servlet

前端 未结 3 1469
误落风尘
误落风尘 2020-11-22 10:20

How do I generate an HTML response in a Java servlet?

相关标签:
3条回答
  • 2020-11-22 11:04

    You need to have a doGet method as:

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

    You can see this link for a simple hello world servlet

    0 讨论(0)
  • 2020-11-22 11:05

    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.

    Kickoff example:

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

    And /WEB-INF/hello.jsp look like:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>SO question 2370960</title>
        </head>
        <body>
             <p>Message: ${message}</p>
        </body>
    </html>
    

    When opening http://localhost:8080/contextpath/hello this will show

    Message: Hello World

    in the browser.

    This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

    • Our Servlets wiki page
    • How do servlets work? Instantiation, sessions, shared variables and multithreading
    • doGet and doPost in Servlets
    • Calling a servlet from JSP file on page load
    • How to transfer data from JSP to servlet when submitting HTML form
    • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
    • How to use Servlets and Ajax?
    • Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

    Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

    0 讨论(0)
  • 2020-11-22 11:19

    Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

    public void doGet(HttpServletRequest request,
           HttpServletResponse response)
           throws IOException, ServletException {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.println("HTML from an external file:");     
       request.getRequestDispatcher("/pathToFile/fragment.html")
              .include(request, response); 
       out.close();
    }
    
    0 讨论(0)
提交回复
热议问题