Request Parameters

PHOTO EMBED

Sun Nov 03 2024 18:32:21 GMT+0000 (Coordinated Universal Time)

Saved by @signup_returns #html

//Request Parameters

//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Check Voting Credentials</title>
    <style>
        div {
            background-color: lightgreen;
            color: Red;
            padding: 20px;
            margin: 20px;
            border: 2px solid yellow;
        }
    </style>
</head>
<body>
    <div>
        <h1>Checking Voting Credentials</h1>
        <form action="Voting" method="get">
            <label>Username:</label>
            <input type="text" name="Name">
            <br>
            <label>Age:</label>
            <input type="text" name="Age">
            <br>
            <input type="submit" name="submit">
        </form>
    </div>
</body>
</html>


//VotingServlet.java


// program on request parameters

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class VotingServlet
 */
@WebServlet("/Voting")
public class VotingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public VotingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Init method is called");
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        System.out.println("I'm done with work, Destroy method is called");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        String name = request.getParameter("Name");
        String age = request.getParameter("Age");
        
        int a = Integer.parseInt(age);
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        
        if (a < 18) {
            pw.println("<h1>You " + name + " are not eligible for casting vote! Wait until you are 18 years old.</h1>");
        } else {
            pw.println("<h1>Congrats!!! " + name + ", you are eligible for casting vote!</h1>");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
content_copyCOPY