在页面加载时编辑jsp页面的下拉列表中显示所选值(SpringMVC)

show the selected value in dropdown on edit jsp page on page load (Spring MVC)

本文关键字:SpringMVC 显示 下拉列表 加载 编辑 jsp      更新时间:2023-09-26

我想在页面加载时在下拉列表中显示所选值。我的编辑页面显示了一个价值,国家。现在用户属于美国,所以页面加载时应默认选择美国。我可以使用javascript或jquery。

我在网上找不到什么帮助,但它们都是关于涂鸦的(<%%>),我不想使用它们。

我正在传递一个具有Id和Value的列表。另外,我在另一个对象中有Id。我可以通过在jsp中引入for循环并显示值来编写代码,但可能是我在那里犯了一些错误。还想知道是否有更好的方法可以做到这一点。

我使用的是Spring MVC。

谢谢。

"现在用户属于美国,所以页面加载时默认应该选择美国。"。你之前就知道用户属于某个国家。

假设你有一个pojo国家作为:

    public class Country{ 
        String countryName;
        String countryId;
        //setters and getters
    }
    public class YourForm{
        List<Country> countryList;
        String selectedCountryId;
        ...
        //setters and getters
    }

在委托给jsp的控制器方法中:

    ...
    YourForm form = new YourForm();
    //set your countrylist to form 
    //set  country user belongs to - selectedCountryId - since you know before hand user belongs to some country.
    model.addAttribute("yourForm", form):
    ...

现在在jsp中访问它作为:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    </head>
    <body>
    <form:form id="yourForm" modelAttribute="yourForm" method="post">
    <tr>
        <td width="50%" class="label">
            <form:select id="countryId" path="selectedCountryId" title='Select Country'>
                <option value="">Please Select</option>
                <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/>
            </form:select>
        </td>
    </tr>
    </body>

由于selectedCountryId已经在控制器中设置,您将在jsp中看到该国家是自动选择的。