简体   繁体   English

从html表单获取参数的Java servlet查询

[英]java servlet query with parameters from html form

I am trying to create a servlet which can obtain the parameter of the drop down box in html and use this parameter to query a database. 我正在尝试创建一个servlet,它可以获取html下拉框的参数并使用该参数查询数据库。

my html: 我的html:

<form action="servlet/currencyservlet">
<select>
<option name="usd">United States Dollar</option>
<option name="pounds">United Kingdom Sterling Pound</option>
</select>
<select>
<option name="cad">Canadian Dollars</option>
<option name="cny">Chinese Yuan</option>
</select>
<input type="submit" value="Check Rate"/>
</form>

my java: 我的java:

...
...
...
conn = DriverManager.getConnect("jdbc:mysql://localhost:3306/currencydb", "root", "");
...
try{
string qstr = "SELECT source_currency, target_currency FROM currencytable WHERE????
}

"source_currency" can be "usd" or "pounds" where "target_currency" can be "cny" or "cad". “ source_currency”可以是“ usd”或“磅”,其中“ target_currency”可以是“ cny”或“ cad”。 My query wishes to extract the exchange rate from the "currencytable" and display result in the servlet. 我的查询希望从“货币表”中提取汇率并将结果显示在Servlet中。 How do I parse the parameters of the drop down boxes? 如何解析下拉框的参数?

Your select boxes should have a name. 您的选择框应有一个名称。 This name is also the name of the HTTP parameter sent when submitting the form: 此名称也是提交表单时发送的HTTP参数的名称:

<select name="sourceCurrency">
...
</select>
<select name="targetCurrency">
...
</select>

In your servlet, you'll get the source and target currencies with getParameter : 在您的servlet中,您将使用getParameter获取源货币和目标货币:

String sourceCurrency = request.getParameter("sourceCurrency");
String targetCurrency = request.getParameter("targetCurrency");

And you may then pass those values to your query, using a prepared statement: 然后,您可以使用准备好的语句将这些值传递给查询:

String sql = "SELECT exchange_rate FROM currencytable WHERE source_currency = ? and target_currency = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, sourceCurrency);
stmt.setString(2, targetCurrency);
ResultSet rs = stmt.executeQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM