1

我正在填充我的数据库数据作为下拉列表中的选项

<select name="AccountType">
                    <option value = "1">Please Select</option>
                        <c:forEach items="${UserItem}" var="AccountType">
                            <option value="${AccountType.getRoleId()}">${AccountType.getRoleName()}</option>
                        </c:forEach>
                    </select>

<%
                                if (errors.containsKey("AccountType"))
                                {
                                    out.println("<span class=\"warning\">" + errors.get("AccountType") + "</span>");
                                }
                            %>

在我的 servlet 中,这是代码

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {

        logger.debug("Add User page requested");
        List<User> UserItems = new UserDAO().RoleTypeList();
        req.setAttribute("UserItem", UserItems);
        jsp.forward(req, resp);
    }

现在确定用户是否忘记在下拉列表中选择第一个选项(请选择)我尝试了这段代码

long AccountType = Integer.parseInt(req.getParameter("AccountType"));
        if ("1".equals(AccountType))
        {
            errors.put("AccountType", "Required");
        }
        else if (req.getParameter("AccountType") != null && !"".equals(req.getParameter("AccountType")))
        {
            long RoleId = Integer.parseInt(req.getParameter("AccountType"));
            emsItem.setRoleId(RoleId);
        }

当我单击提交按钮时,什么也没发生。我的下拉列表的项目也不见了,所以我只需要返回页面即可。我该如何解决这个问题?

4

1 回答 1

1

问题在于这两行:

long AccountType = Integer.parseInt(req.getParameter("AccountType"));
if ("1".equals(AccountType))

Integer.parseInt()返回一个整数。你为什么把它存储成一个长的?然后,一旦你有这个 long,你测试 long 是否等于 String "1"。long 永远不会等于 String,因为它们甚至不是同一类型。

要么使用

int accountType = Integer.parseInt(req.getParameter("AccountType"));
if (accountType == 1)

或者

String accountType = req.getParameter("AccountType");
if ("1".equals(accountType))

请尊重 Java 命名约定:变量以小写字母开头。

于 2013-01-30T14:11:52.130 回答