2015-09-07 59 views
3

我試圖從類似這樣的火花框架的post方法中獲得複選框的列表。我也使用Freemarker模板。Spark框架request.body無法獲取複選框值

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> 
... 

而且在Java代碼:

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

但網址值爲空。能告訴我解決問題的方法嗎?

回答

0

首先,request.body()返回客戶端發送的請求體,而不是url。

用一個這樣的簡單例子。

模板(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()); 

    } 
} 

日誌輸出

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

看到完整的項目在這裏:https://github.com/dominicfarr/spark-framework-request-body