The website has been updated, checkout below websites.

https://codingvariable.com/

Wednesday, 24 June 2020

Create Lottery like thing using HTML and Servlet.

5. Write a servlet program that accepts a number and name from an HTML file, compares the number with predefined numbered returns a message "you win" or "you lose" if the user's number matches the predefined number similar to a lottery.

You will have to create two files namely Lottery.html (for Input) and Lottery.java (Contains Business Logic)

Lottery.html


<!DOCTYPE html>
<html>
  <head>
    <title>Lottery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
      <form method="post" action="Lottery">
          Enter Lottery Number from 1 - 50 : <input type="text" name="txtno"/>
          <input type="submit" value="Spin"/>
      </form>
  </body>
</html>


Lottery.java


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

/**
 *
 * @author Shubham Singh (https://shubhamsingh.dev/)
 */
@WebServlet(urlPatterns = {"/Lottery"})
public class Lottery extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<body>");

            int no = Integer.parseInt(request.getParameter("txtno"));
            if(no==16)
                out.println("<h1> You Win </h1>");
            else
                out.println("<h1> You Lose </h1>");

            out.println("</body>");
            out.println("</html>");

    } 
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}


Output 

Fig 1. Lottery.html Output


Fig 2. Lottery.java Output




No comments:

Post a Comment