Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an HTML/XHTML file from servlet

I've seen servlets examples, they're something like this:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
        ...
    }

My question is, instead of the code, can I return an HTML page? I mean, something like this:

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

            SHOW(FILE.HTML);

        }

Thanks!!! ;)

like image 698
dak Avatar asked Jun 06 '13 14:06

dak


People also ask

How send data from servlet to HTML?

First create a PrintWriter object, which will produce the output on HTML page. Here response is HttpServletResponse object from doGet or doPost method. out. println("<html><body><table>...

Can we write HTML code in servlet?

The most common use for a servlet is to extend a web server by providing dynamic web content. Web servers display documents written in HyperText Markup Language (HTML) and respond to user requests using the HyperText Transfer Protocol (HTTP). HTTP is the protocol for moving hypertext files across the internet.

How does servlet read HTML form data?

Reading Form Data using Servlet getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames() − Call this method if you want a complete list of all parameters in the current request.


1 Answers

There are a few different ways you could do this:

  1. Forward the servlet to the path where the HTML file is located. Something like:

    RequestDispatcher rd = request.getRequestDispatcher("something.html"); rd.forward(request, response);

  2. Send a redirect to the URL where the HTML is located. Something like:

    response.sendRedirect("something.html");

  3. Read in the contents of the HTML file and then write out the contents of the HTML file to the servlet's PrintWriter.

like image 81
worpet Avatar answered Nov 09 '22 02:11

worpet