Question

I'm just wondering if it's possible to validate or check that at least one radio button has been selected on a form within a servlet?

Or can this type of validation only occur on the client side with JavaScript etc?

As a workaround, I can check a radio button by default, but ideally I would like no radio button initially selected and display an error message if the user tries to submit the form.

I'm only using Java servlets on the web app so it would be great if anyone has done this before using servlets only.

Thanks in advance.

Was it helpful?

Solution

In your servlet, you will get the value of the selected radio if they are in the same group. If the user has not selected any radio, you will receive null value. Let's see it in action:

<form method="POST" action="HelloWorldServlet">
    <input type="radio" name="sampleRadio" value="val1" />Value 1
    <br />
    <input type="radio" name="sampleRadio" value="val2" />Value 2
    <br />
    <input type="submit" value="Hello Servlet" />
</form>

In the servlet side:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String radio = request.getParameter("sampleRadio");
    if (radio != null)
        System.out.println("value of selected radio: " + radio);
    else
        System.out.println("no radio button was selected");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top