Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HTML Checked Checkboxes in Java Jersey

I'm using the Jersey Java Framework to send data from a HTML form to a Java RESTful web service. I need to know what checkboxes are checked in that form (with different names and purposes). I've tried with this in the web service:

package com.myexample;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.multipart.FormDataParam;

@Path("/service")
public class MyService{

    @POST
    @Path("/formData")
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String formData(@FormDataParam("myInputbox") String myInputbox, @FormDataParam("myCheckbox") String myCheckbox){
        return "Now I get: <br/>Inputbox: " + myInputbox + "<br/>Checkbox: " + myCheckbox;
    }
}

The sender form is like this:

<html>
    <head>
        <title>Send a checkbox</title>
    </head>
    <body>
        <form method="post" action="http://localhost:8080/Example/rest/service/formData" enctype="multipart/form-data">
            <input type="checkbox" name="myCheckbox">This is my checkbox
            <input type="text" name="myInputbox" value=""/>
            <input type="submit" value="Send data"/>
        </form>
    </body>
</html>

I can successfully get the value in the input text but the checkbox name returns a null value. I need only to know if that checkbox is checked.

(Note: I use multipart/form-data because I also send files in the final version, so I need to use that format)

Thanks for helping!

like image 396
AngelBlond8 Avatar asked Aug 27 '14 17:08

AngelBlond8


1 Answers

I've found the answer to the problem. I expected to get an "OFF" or "false" value when the checkbox is unchecked, but instead it returns "null" when unchecked and returns the content of the value property if checked (or "on" if no value is set).

Then, the code above can make it. I don't delete the question if anyone else finds the same confusion or needs to do that retrieve.

like image 121
AngelBlond8 Avatar answered Nov 14 '22 09:11

AngelBlond8