0

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?

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

hi, what should be the parameters for "?"?
Read the code: the first parameter is set with stmt.setString(1, sourceCurrency), and the second is set with stmt.setString(2, targetCurrency). Read docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.