Servlet with html

A Servlet can contain HTML, this means the server sends output to a printwriter. Just like JSP can contain JAVA code, both methods are messy, but we’ll have to cover these to show you how it is not done, and afterwards we’ll show you how it’s done. So this tutorial will cover the “messy servlet”. And the next tutorial will cover how it’s done properly, using beans.

In this jsp tutorial we’re going to play a little dice-game. The user can roll two dice (this means the servlet generates two random numbers between one and six and shows them to the user using html).

public class DiceServlet extends HttpServlet {

public class DiceServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();

        int first = (int)((Math.random()*6)+1);
        int second = (int)((Math.random()*6)+1);

        out.println("<html>");
        out.println("<body>");
        out.println("You threw: " + first + " en " + second);
        out.println("</body>");
        out.println("</html>");

    }

}

Inside the doGet method we create a printwriter, that is located in the response object. The next thing that happens is that the servlet generates two numbers. And at the end we display these numbers.

It is very messy but it executes what we want, if we configure our web.xml file properly and if we include the right libraries.

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

The servlet-mapping inside the web.xml file:

<servlet>

<servlet-name>DiceServlet</servlet-name>

<servlet-class>servlets.DiceServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DiceServlet</servlet-name>

<url-pattern>/dice.do</url-pattern>

</servlet-mapping>

In the next tutorial we’ll cover how we delete the html from the servlet and seperate layout and logic.