如何在 servlet 中使用 HTML 页面中的下拉列表值?

发布于 2024-12-21 17:15:09 字数 539 浏览 0 评论 0 原文

我正在尝试使用 servlet 和 HTML 创建一个简单的计算器。对于 1 个操作,它可以工作,但是如何使用像

if (+) {
    k=i+j;
} else if (-) {
    k=i-j;
}

我想说的那样的结构,我应该在 if 条件中编写什么来获取下拉列表的值?

我的下拉列表如下所示:

<select name="select1">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
</select>

我在 Windows 上使用 Tomcat 6。

I'm trying to create a simple calculator using servlets and HTML. For 1 operation it works, but how do I use a structure like

if (+) {
    k=i+j;
} else if (-) {
    k=i-j;
}

I mean to say, what should I write in the if condition to get the drop down list's value?

My drop down list is like below:

<select name="select1">
    <option value="+">+</option>
    <option value="-">-</option>
    <option value="*">*</option>
    <option value="/">/</option>
</select>

I'm using Tomcat 6 on Windows.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆光飞翔i 2024-12-28 17:15:09

只需以通常的方式将其作为请求参数获取,就像您对所有其他 HTML 输入元素所做的那样。

String operator = request.getParameter("select1");

(为了清楚起见,我仅将

然后,要比较字符串值,请使用 String#equals() 方法(因此不是 ==!):

if ("+".equals(operator)) {
    // ...
} else if ("-".equals(operator)) {
    // ...
} else if ("*".equals(operator)) {
    // ...
} else if ("/".equals(operator)) {
    // ...
}

您可能想要考虑研究枚举或升级到 Java 7(这样您就可以使用支持字符串的 switch),这样您就不会得到丑陋的嵌套 if-else 块。要更进一步,请查看命令模式。但我认为这是家庭作业,所以没关系;)

Just get it as request parameter the usual way, like as you did for all other HTML input elements.

String operator = request.getParameter("select1");

(I'd for clarity only rename the <select name="select1"> to <select name="operator">)

Then, to compare the string values, use the String#equals() method (and thus not ==!):

if ("+".equals(operator)) {
    // ...
} else if ("-".equals(operator)) {
    // ...
} else if ("*".equals(operator)) {
    // ...
} else if ("/".equals(operator)) {
    // ...
}

You might want to consider looking into enums or upgrading to Java 7 (so that you can use a switch which supports since Java 7 also strings), so that you don't end up with an ugly nested if-else block. To get a step further, checkout the command pattern. But I assume that this is homework, so nevermind ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文