0
votes

I have searched high and low on this forum and in Google without any success on how to read selected values from a dynamically generated list box styled in Bootstrap.

This is the JSP page [reports01.jsp] code:

<%@ 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>

And this is part of the code the controller from where I have no problems in dynamically populating the list box.

/**
     * 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";
    }

However, when I try to read the values chosen from the list, the resultant output is null. The following is the code with which I am trying to read the selected values from the list box in the JSP.

/** * This method will get all contracts after selection. */ @RequestMapping(value = { "/reportDetailed01" }, method = 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";

}

This is the domain model for the form:

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;
    }

}

I have looked at these posts: 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

But nothing seems to be working.

I suspect that I may be lacking a script to handle user selection. Any help will be much appreciated.

1

1 Answers

0
votes

After having made a more intensive search, the following links proved to be of significance:

how to pass javascript variable to Spring mvc controller

Pass a javascript variable value into input type hidden value

Hidden field in spring MVC

I was able to solve my problem thus:

The revised JSP page:

<%@ 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>

The controller:

@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:/";
    }

}

The domain model:

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;
    }


}