Search code examples
htmlcheckboxspark-java

Spark framework request.body cant obtain checkbox values


I'm trying to get a list of checkboxes from a post metho on spark framework like this. I'm using Freemarker template too.

HTML:

...
<form class="form-horizonal" name="maCreaIncidencia" action="/maCreaIncidencia" method="POST" accept-charset="utf-8">

<div class="col-lg-3"><!--CONTENEDOR-->
    <fieldset><legend><h5>Roles Asignados</h5></legend>
        <div class="checkbox" name="rolesAsignados" id="rolesAsignados"> <!--id="asignados">-->
            <#list roles as rol>
                <div class="row" name="asignados" id="asignados">
                    <input name="checkbox" type="checkbox" id="${rol.idRol}" value="${rol.idRol}" style="display:none" onClick="if(this.checked)desmarca(this);"><label for="${rol.idRol}" style="display:none">${rol.idRol} - ${rol.rol}</label>
                </div>
            </#list>
        </div>                          
    </fieldset>
</div>
<input class="btn btn-primary btn-lg active btn-block" type="submit" value="Añade Nueva Incidencia" >
</form>
...

And in java code:

...
String url = request.body();
...

But url value is null. Can show me the way to solve it?


Solution

  • First of all, request.body() returns request body sent by the client, not a url.

    With a simple example like this.

    template (car.ftl)

    <form action="/" method="POST" accept-charset="utf-8">
        <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
        <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
        <input type="submit" value="Submit">
    </form> 
    

    main.java

    import org.apache.log4j.Logger;
    import spark.ModelAndView;
    import spark.template.freemarker.FreeMarkerEngine;
    
    import static spark.Spark.get;
    import static spark.Spark.post;
    
    public class Main {
    
    private static final Logger LOG = Logger.getLogger(Main.class);
    
        public static void main(String args[]) {
    
            get("/", (request, response) -> {
                return new ModelAndView(null, "car.ftl");
            }, new FreeMarkerEngine());
    
            post("/", ((request, response) -> {
                LOG.info("------> " + request.body());
    
                return new ModelAndView(null, "car.ftl");
            }), new FreeMarkerEngine());
    
        }
    }
    

    Log output

    2015-10-13 15:34:44,889  INFO [qtp297991908-20 - /] Main: ------> vehicle=Car
    

    see full project here: https://github.com/dominicfarr/spark-framework-request-body