【问题标题】:Null values returned in Spring Controller following selection from Bootstrap list box从 Bootstrap 列表框中选择后在 Spring Controller 中返回 Null 值
【发布时间】:2018-05-20 15:15:57
【问题描述】:

我在这个论坛和谷歌上搜索了高低,但没有成功地从 Bootstrap 中动态生成的列表框中读取选定的值。

这是JSP页面[reports01.jsp]代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Contract-wise Report Selection</title>
<link href="<c:url value='/static/css/bootstrap.css' />"
    rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    function myFunction() {
        var selectedvalue = $("#mySelect option:selected").val();
    }
</script>
</head>

<body>
    <div class="generic-container">
        <%@include file="authheader.jsp"%>

        <div class="well lead">Contract-wise Report Selection</div>
        <form:form method="POST" modelAttribute="reports01"
            action="reportDetailed01" class="form-horizontal">
            <form:input type="hidden" path="id" id="id" />


            <div class="row">
                <div class="form-group col-md-12">
                    <label class="col-md-3 control-lable" for="contractMap">Contracts
                        to Select</label>
                    <div class="col-md-7">
                        <form:select id="mySelect" path="contractMap"
                            onChange="myFunction" items="${contractList}" multiple="true"
                            class="form-control input-sm" />
                        <div class="has-error">
                            <form:errors path="contractMap" class="help-inline" />
                        </div>
                    </div>
                </div>
            </div>

            <button type="button" onclick="myFunction()">Try it</button>

            <div class="row">
                <div class="form-actions floatRight">
                    <input type="submit" value="Print" class="btn btn-primary btn-sm" />
                    or <a href="<c:url value='/' />">Cancel</a>
                </div>
            </div>

            <div class="well">
                <a href="<c:url value='/' />">Back to Menu</a>
            </div>

        </form:form>
    </div>
</body>
</html>

这是控制器代码的一部分,我在动态填充列表框时没有问题。

/**
     * This method will list all contracts for selection.
     */
    @RequestMapping(value = { "/reportDetailed01" }, method = RequestMethod.GET)
    public String showContractsForReports01(ModelMap model) {

        ReportForm01 rf01 = new ReportForm01();

        Map<Integer, String> contractList = contractService.findAllContracts01();

        System.out.println(contractList);
        System.out.println("========= GET ================");

        model.addAttribute("reports01", rf01);
        model.addAttribute("contractList", contractList);
        model.addAttribute("loggedinuser", getPrincipal());
        return "reports01";
    }

但是,当我尝试读取从列表中选择的值时,结果输出为空。以下是我试图从 JSP 的列表框中读取所选值的代码。

/** * 此方法将获得选择后的所有合约。 */ @RequestMapping(值 = { "/reportDetailed01" }, 方法 = RequestMethod.POST) //public ModelAndView getContractsForReports01(@ModelAttribute(value = "reports01") ReportForm01 reportForm01, BindingResult bindingResult) { public String getContractsForReports01(@ModelAttribute ReportForm01 reportForm01, BindingResult bindingResult, HttpServletRequest request) {

System.out.println("=====================xxx=================");
System.out.println(reportForm01.getContractMap());


return "redirect:/reportDetailed01";

}

这是表单的域模型:

public class ReportForm01 implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer Id;


    private Map<Integer,String> contractMap = new HashMap<Integer, String>();

    private Map<Integer, String> selectedContractMap = new HashMap<Integer, String>();


    public Map<Integer,String> getContractMap() {
        return contractMap;
    }

    public void setContractMap(Map<Integer,String> contractMap) {
        this.contractMap = contractMap;
    }

    public Integer getId() {
        return Id;
    }

    public void setId(Integer id) {
        Id = id;
    }

    public Map<Integer, String> getSelectedContractMap() {
        return selectedContractMap;
    }

    public void setSelectedContractMap(Map<Integer, String> selectedContractMap) {
        this.selectedContractMap = selectedContractMap;
    }

}

我看过这些帖子: How do I get selected value from a bootstrap select drop down How to get multiple selected values from select box in JSP? Pass object from Dropdown list (.jsp) to Controller

但似乎没有任何效果。

我怀疑我可能缺少处理用户选择的脚本。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript spring-mvc bootstrap-modal


    【解决方案1】:

    在进行了更深入的搜索后,以下链接被证明是重要的:

    how to pass javascript variable to Spring mvc controller

    Pass a javascript variable value into input type hidden value

    Hidden field in spring MVC

    因此我能够解决我的问题:

    修改后的JSP页面:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ page isELIgnored="false"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <html>
    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Contract-wise Report Selection</title>
    <link href="<c:url value='/static/css/bootstrap.css' />"
        rel="stylesheet"></link>
    <link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <script>
        function getValue() {
            var x = document.getElementById("sel");
            var completeRange = "";
            for (var i = 0; i < x.options.length; i++) {
                if (x.options[i].selected) {
                    var selectedString = x.options[i].text;
                    completeRange = completeRange + ", " + selectedString;
                }
            }
            document.getElementById('contractListJS').value = completeRange
                    .substring(2);
            document.getElementById("reportDetailed01").submit();
        }
    </script>
    
    
    </head>
    
    <body>
        <div class="generic-container">
            <%@include file="authheader.jsp"%>
    
            <div class="well lead">Contract-wise Report Selection</div>
            <form:form method="POST" modelAttribute="reports01"
                action="reportDetailed01" id="reportDetailed01" class="form-horizontal">
    
                <div class="row">
                    <form:input path="contractList" type="hidden" id="contractListJS"
                        value="" />
                </div>
    
                <div class="row">
                    <div class="form-group col-md-12">
                        <label class="col-md-3 control-lable" for="contractMap">Contracts
                            to Select</label>
                        <div class="col-md-7">
                            <form:select id="sel" path="contractMap" items="${contractMap}"
                                multiple="true" class="form-control input-sm" />
                            <div class="has-error">
                                <form:errors path="contractMap" class="help-inline" />
                            </div>
                        </div>
                    </div>
                </div>
    
                <div class="row">
                    <div class="form-actions floatRight">
                        <input type="submit" value="Print" onclick="getValue()"
                            class="btn btn-primary btn-sm" /> or <a
                            href="<c:url value='/' />">Cancel</a>
                    </div>
                </div>
    
                <div class="well">
                    <a href="<c:url value='/' />">Back to Menu</a>
                </div>
            </form:form>
        </div>
    </body>
    </html>
    

    控制器:

    @Controller
    @RequestMapping("/")
    public class ReportsController01 {
    
        @Autowired
        ContractService contractService;
    
        /**
         * This method returns the principal[user-name] of logged-in user.
         */
        private String getPrincipal() {
            String userName = null;
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
            if (principal instanceof UserDetails) {
                userName = ((UserDetails) principal).getUsername();
            } else {
                userName = principal.toString();
            }
            return userName;
        }
    
        /**
         * This method will list all contracts for selection.
         */
        @RequestMapping(value = { "/reportDetailed01" }, method = RequestMethod.GET)
        public String showContractsForReports01(ModelMap model) {
    
            ReportForm01 rf01 = new ReportForm01();
    
            Map<Integer, String> contractList = contractService.findAllContracts01();
    
            System.out.println(contractList);
            System.out.println("========= GET ================");
    
            model.addAttribute("reports01", rf01);
            model.addAttribute("contractMap", contractList);
            model.addAttribute("loggedinuser", getPrincipal());
            return "reports01";
        }
    
    
    
    
        /**
         * This method will get all contracts after selection.
         */
        @RequestMapping(value = { "/reportDetailed01" }, method = RequestMethod.POST)
        public String getContractsForReports01(@ModelAttribute ReportForm01 reportForm01, BindingResult bindingResult, HttpServletRequest request) {
            System.out.println("=================== POST ===============");
            System.out.println(reportForm01.getContractList());
            System.out.println("=====================xxx=================");
            return "redirect:/";
        }
    
    }
    

    领域模型:

    public class ReportForm01 implements Serializable {
        private static final long serialVersionUID = 1L;
    
        private String contractList;
    
        private Map<Integer,String> contractMap = new HashMap<Integer, String>();
    
    
        public Map<Integer,String> getContractMap() {
            return contractMap;
        }
    
        public void setContractMap(Map<Integer,String> contractMap) {
            this.contractMap = contractMap;
        }
    
    
        public String getContractList() {
            return contractList;
        }
    
        public void setContractList(String contractList) {
            this.contractList = contractList;
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多