java 带有 JSP 和 Spring MVC 的多个复选框,如何获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26149822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:22:35  来源:igfitidea点击:

Multiple checkbox with JSP and Spring MVC, how to get values

javaspringjspspring-mvcservlets

提问by Cooler

Guys could you help me please, i stuck with the problem, i have a form, where i'm choosing different services, which should be added to the order. The problem is i can't get these values of chosen checkboxes, there is even no any errors in a console. Looks like my servlet never runs for now, i tried difference ways to fix this issue, but nothing helped me.

伙计们,你们能帮我吗,我遇到了这个问题,我有一个表格,我在那里选择不同的服务,应该添加到订单中。问题是我无法获得所选复选框的这些值,控制台中甚至没有任何错误。看起来我的 servlet 现在永远不会运行,我尝试了不同的方法来解决这个问题,但没有任何帮助。

Here is for in jsp page:

这是在jsp页面中:

<!-- SERVICE TABLE -->
    <form class="form-horizontal" action="/clients/addOrder/${client.id}" method="POST" >
    <table class="table table-striped table-bordered table-condensed" >
        <tr>
            <th><spring:message code="label.serviceId" /></th>
            <th><spring:message code="label.serviceName" /></th>
            <th><spring:message code="label.servicePrice" /></th>
            <th><spring:message code="label.actions" /></th>

        </tr>
        <c:forEach var="service" items="${servicesList}">
            <tr id="${service.service_id}">
                <td><c:out value="${service.service_id}" /></td>
                <td><c:out value="${service.service_name}" /></td>
                <td><c:out value="${service.service_price}" /></td>
                <td><input type="checkbox" name="serviceBox"
                    value="${service.service_id}" /></td>
            </tr>
        </c:forEach>
    </table>
    <div class="form-group form-group-sm">
        <div class="col-sm-offset-2 col-sm-10">
         <a class="pull-right">
            <button class="btn btn-primary" type="submit"><c:out value="Add order"/></button>
         </a>
        </div>
    </div>
    <input type="hidden" name="clientId" value="${client.id}">
    </form>

servlet

小服务程序

    @RequestMapping(value = "/addOrder/{clientId}", method = RequestMethod.POST)
    public String addOrder(@Valid @PathVariable("clientId") Long clientId,  @ModelAttribute("serviceBox") String[] services, BindingResult result,
            Model model) {
        System.out.println("IN addOrder POST");

        if (result.hasErrors()) {
            AllServicesEvent ase = servicesService
                    .requestAllServices(new RequestAllServicesEvent());
            model.addAttribute("servicesList", ase.getServices());
            return "addOrderForm";
        }
        System.out.println("NO MISTAKES");
        List<Services> servicesList = servicesService.requestService(new RequestServiceEvent(services)).getServicesList();
        System.out.println("Service List size: " + servicesList.size());
        if (servicesList != null && servicesList.size() > 0) {
            // update orders amount and total price
            System.out.println("IN IF METHOD");
            ClientUpdatedEvent cue = clientsService.updateClient(new UpdateClientEvent(clientId, servicesList));
            System.out.println("AFTER UPDATING CLIENTS");
            // add order to orders table, add order id, service id to order_service table
            OrderCreatedEvent oce = ordersService.addOrder(new CreateOrderEvent(clientId, servicesList));
            System.out.println("AFTER ADDING ORDERS");
            return "redirect:/clients";
        } else {
            return "addOrderForm";
        }
    }

In console:

在控制台中:

Oct 01, 2014 11:07:34 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Oct 01, 2014 11:07:34 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Oct 01, 2014 11:07:34 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 4926 ms
Oct 01, 2014 11:07:34 PM org.apache.jasper.compiler.TldLocationsCache tldScanJar
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Hibernate: select clients0_.client_id as client_i1_3_, clients0_.birthdate as birthdat2_3_, clients0_.city as city3_3_, clients0_.country as country4_3_, clients0_.email as email5_3_, clients0_.first_name as first_na6_3_, clients0_.gender as gender7_3_, clients0_.last_name as last_nam8_3_, clients0_.orders as orders9_3_, clients0_.phone as phone10_3_, clients0_.total_income as total_i11_3_ from clients clients0_
Hibernate: select clients0_.client_id as client_i1_3_0_, clients0_.birthdate as birthdat2_3_0_, clients0_.city as city3_3_0_, clients0_.country as country4_3_0_, clients0_.email as email5_3_0_, clients0_.first_name as first_na6_3_0_, clients0_.gender as gender7_3_0_, clients0_.last_name as last_nam8_3_0_, clients0_.orders as orders9_3_0_, clients0_.phone as phone10_3_0_, clients0_.total_income as total_i11_3_0_ from clients clients0_ where clients0_.client_id=?
Hibernate: select services0_.service_id as service_1_4_, services0_.service_name as service_2_4_, services0_.service_price as service_3_4_ from services services0_

And instead of the result i have only a web page with:

而不是结果我只有一个网页:

HTTP Status 404 - /clients/addOrder/1

--------------------------------------------------------------------------------

type Status report

message /clients/addOrder/1

description The requested resource is not available.

upd: in this way it works:

更新:以这种方式工作:

@RequestMapping(value = "/addOrder/{clientId}", method = RequestMethod.POST)
public String addOrder(@PathVariable("clientId") Long clientId) {
    System.out.println("IN addOrder POST, id" + clientId);
    return "addOrderForm";
}

So the only problem how in right way get checkboxed values in servlet.

所以唯一的问题是如何以正确的方式在 servlet 中获得复选框值。

回答by Serge Ballesta

Well it is generally considered as bad practice to give a link only answer on StackOverflow, but really, RTFM! Spring reference manual has a paragraph on usage of checkboxes.

好吧,通常认为在 StackOverflow 上只给出链接答案是不好的做法,但实际上,RTFM!Spring 参考手册有一段关于复选框的使用

Here are some extracts :

以下是一些摘录:

<form:form>
      <table>
          <tr>
              <td>Interests:</td>
              <td>
                  <%-- Approach 2: Property is of an array or of type java.util.Collection --%>
                  Quidditch: <form:checkbox path="preferences.interests" value="Quidditch"/>
                  Herbology: <form:checkbox path="preferences.interests" value="Herbology"/>
                  Defence Against the Dark Arts: <form:checkbox path="preferences.interests"
                      value="Defence Against the Dark Arts"/>
              </td>
          </tr>
      </table>
  </form:form>

The associated model is :

相关模型是:

public class Preferences {

  private String[] interests;

  public String[] getInterests() {
      return interests;
  }

  public void setInterests(String[] interests) {
      this.interests = interests;
  }
}

So use <form:checkbox/>with a pathunless you have a good reason not to do so, and use a model that containsan array, not one that isan array

因此,使用<form:checkbox/>路径,除非你有一个很好的理由不这样做,并使用该模型包含一个数组,而不是一个数组

回答by vishal thakur

<script>
$(function() {
    $("#selectAll").click(function(){
       $('input:checkbox:not(:disabled)').prop('checked', this.checked); 
  });  
 })
</script>
<table class="noborder" cellspacing="0" border="0" width="100%">
   <tr>
   <td><form:label path="selectAll" id="h1"></form:label></td>
   <td><form:checkbox path="selectAll" id="selectAll" onclick="selectall(this);"/></td>
   <td id="h2">Sr. No.</td>
   <td id="h3">Login Name</td>
   </tr>
     <c:forEach var="loginNameList" items="${loginNameList}" varStatus="status">
    <tr>
     <td><form:label path="selectAll" id="h1"></form:label></td>
     <td><form:checkbox path="lockedItems" value="${loginNameList.uId}" id="lockedItems${status}"/></td>
     <td>${status.count}</td>
     <td>${loginNameList.loginName}</td>
    </tr>
   </c:forEach>
   <tr>
   <td></td>
   <td><input type="submit" value="Unlock"></td>
   <td></td>
   <td></td>
   </tr>
   </table>