Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an HTML Response in a Java Servlet

Tags:

html

servlets

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

like image 411
ogechi nwogu Avatar asked Mar 03 '10 12:03

ogechi nwogu


People also ask

How do you write a message back to the browser from inside a servlet?

How would you write a message back to the browser from inside a servlet? "PrintWriter out = response. getWriter();

How can we retrieve data from HTML page using servlet?

The getParameter() method is used to get the data from HTML file. The getParameter() method gives a servlet access to the parameter in its query string. It returns the parameter decoded value or null if the parameter is not specified.

Which HTML tag can be used to send the request to servlet?

JSP forward action tag is used for forwarding a request to the another resource (It can be a JSP, static page such as html or Servlet).


3 Answers

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.

like image 78
BalusC Avatar answered Oct 02 '22 12:10

BalusC


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

like image 43
codaddict Avatar answered Oct 02 '22 12:10

codaddict


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();
}
like image 43
Marco Avatar answered Oct 02 '22 12:10

Marco