【问题标题】:Can't display two dropdown box in Spring Mvc and question about ModelAndView无法在 Spring Mvc 中显示两个下拉框以及有关 ModelAndView 的问题
【发布时间】:2021-01-20 13:47:38
【问题描述】:

我正在开发一个应该有两个下拉框的 JSP,其中第二个下拉框取决于第一个下拉框。

运行应用程序,第一个下拉框填充了一些元素。 触发列表框 onChange 方法时会调用客户端 jquery ajax 方法,向控制器提供要在控制器中使用的 id 值

我的问题如下:

如何填充和显示第二个下拉框?我所有的尝试似乎都失败了。我检索了活动和文档列表的所有值,但我只能显示第一个下拉框。第二个下拉框永远不会显示。 我该如何解决这个问题? 关于模型:

模型本身只包含一些属性以及它们自己的 getter 和 setter

    private String action;
    private String activityId;
    private Integer documentId;

控制器有一个简单的调度器如下:

@RequestMapping(value = "/act", method = { RequestMethod.POST,
        RequestMethod.GET })
public String dispatcher(
    @Validated @ModelAttribute("activityForm") ActivityModel activityModel,
    BindingResult errors, HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    String methodName = activityModel == null ? null : activityModel.getAction();
    Map <String, String> map = null;
    if ("documentFilter".equals(methodName)) {
        return documentFilter(activityModel, map, errors, request, response);
    }
  
}

由于上面的代码,这个方法被调用,第一个下拉框被显示并填充了一些元素

@RequestMapping(value = "/act/index", method = {RequestMethod.GET })
    public ModelAndView act(HttpServletRequest request) {
            List<Activity> activities;
            
            try {
                activities = activitiesService.getActivities();
            } catch (DataNotFoundException e) {
                log.error("Failed to get the activities (Activity). Returning an empty list.", e);
                activities = new ArrayList<Activity>(0);
            }

            request.setAttribute("act", activities);
            request.setAttribute("activityForm", new ActivityModel());
            return new ModelAndView("act");
}

当第一个下拉框被填充时,客户端 Javascript 管理 onChange 事件,当被触发时,发送一个 post 请求如下:

$.ajax({
        url : baseUrl + "act/documentFilter",
        type : 'POST',
        data : JSON.stringify({
            'activityId' : activity.value
        }),
        dataType : 'json',
        contentType : 'application/json',

并且请求命中以下映射方法:

    @RequestMapping(value = "/act/documentFilter", method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String documentFilter(@ModelAttribute("activityForm")ActivityModel form, 
            @RequestBody Map<String,String> map, BindingResult errors,
            HttpServletRequest request, HttpServletResponse response) {
        
        form.setActivityId(map.get("activityID"));
        ActivityModel myForm = form;
        Integer sessionIdQuest = (Integer) request.getSession()
            .getAttribute("sessionIdQuest");
        
        Activity activity = null;
        Document document = null;
        
        try {
            if (myForm.getActivityId() == null) {
                document = activitiesService.getDocument(sessionId);
                myForm.setActivityId(document.getActivity().getId());
            } else {
                Integer activityCode = Integer.valueOf(myForm.getActivityId().substring(5));
                String year = myForm.getActivityId().substring(0, 4);
                activity = activitiesService.getActivity(activityCode, year);
                document = activity.getDocument().get(0);
            }
        } catch (DataNotFoundException e) {
            log.warn("Warning: ", e);
            throw new ServiceException();
        }
        
        List<Activity> activities = null;
        List<Document> documents = null;
        try {
            activities = activitiesService.getActivities();
            Integer activityCode = Integer.valueOf(myForm.getActivityId().substring(5));
            String year = myForm.getActivityId().substring(0, 4);
            documents = activitiesService.getDocument(activityCode, year);
        // here i have both activities and documents
            request.setAttribute("activities", activities);
            request.setAttribute("documents", documents);
        } catch (DataNotFoundException e) {
            log.error("Fatal Error: " , e);
            throw new IllegalStateException();
        }
        
        /* what should i return exactly?
            the page return always the first drowpdown box
        */
        return "act";
    
    }

这是jsp页面:

    <form:form action="${pathPrefix}act" enctype="multipart/form-data"
    name="activityForm" method="post" modelAttribute="activityForm">
    <form:hidden path="action" />
    <div id="contentBox">
        <div style="font-size: medium;">
            <p>Welcome</p>
            <p>${results}</p>
        </div>
    </div>
    <label for="survey">Select an activity:</label>
    <form:select path="activityId" itemValue="${actSel}" onchange="javascript:submitForm('documentFilter');" htmlEscape="false">
           
          <c:if test="${documents==null}">
            <option value="">
<%--               <spring:message code="activity.label.selectActivity" /> --%>
            </option>
          </c:if>
          <form:options items="${activities}" itemValue="id" itemLabel="description" />
    </form:select>
    <%-- Document block --%>
    <c:if test="${documents!=null}">         
        <form:select path="documentId" onchange="javascript:submitForm('FilterData');"
          htmlEscape="false">
          <form:options items="${documents}" itemValue="id" itemLabel="label" />
        </form:select>
    </c:if>     
    <br>
    <br>
Now i retrieve all the values for the Activity and Document List, but i can display the first dropdown box only. The second dropdown box is never showed.
How can i solve this?

【问题讨论】:

    标签: java spring model-view-controller modelandview


    【解决方案1】:
    • 在更改第一个下拉列表时调用的 Ajax 将给出文档列表,但这里的问题是 Ajax 调用不会重新加载您的页面,因此返回的列表不会在页面上更新。
    • 在您的情况下,一个简单的解决方案是将您的 JSP 页面的完整代码放在单个 div 标签下 div id="mainDiv"> 页面在这里

    之后,在您的 Ajax 调用中使用“成功”块作为
    成功:函数(结果){ $(“#mainDiv”).html(结果); }

    猜你喜欢
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多