exxcellent
exxcellent

Reputation: 659

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.

my 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:

...
...
...
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". My query wishes to extract the exchange rate from the "currencytable" and display result in the servlet. How do I parse the parameters of the drop down boxes?

Upvotes: 0

Views: 3758

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

Your select boxes should have a name. This name is also the name of the HTTP parameter sent when submitting the form:

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

In your servlet, you'll get the source and target currencies with 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();

Upvotes: 3

Related Questions