Accessing selected dropdown items using Java - java

I have a dropdown which consist the language names. I am setting the value and displaying name of the dropdown by using a hashmap.
<form action="TextTranslation" method="post" class="form" role="form" >
<div class="row">
<div id = "imageView" class="col-lg-8 center-block ">
<div class="btn-group">
<select name="country">
<%
Map<String,String> langCode = x.getCountryList();
for( Object key :langCode.keySet() )
{%>
<option value="<%=(String)key%>"><%=langCode.get(key) %> </option>
<%
System.out.println((String)key);
}
String name = request.getParameter("country");
request.setAttribute("code", name);
%>
</select>
</div>
<input type="submit" class= "btn btn-image" value="Translate">
Search Text
</div>
</div>
</form>
Values are passed correctly to dropbox as it print all the values in console. the set attribute is accessed in the particular servlet. But it gives a null value. Do you have any idea?Thank you in advance
UPDATED
<select name="country">
<%
Map<String,String> langCode = x.getCountryList();
for( Object key :langCode.keySet() )
{%>
<option value="<%=(String)key%>"><%=langCode.get(key) %> /option>
<% System.out.println((String)key);
}
String name = request.getParameter("country");
%>
</select>
<input type="hidden" name="code" value = <%= name%>/> .
In the servlet I used,
request.getParameter("code");

update your jsp likewise,
<form...>
...
<input type="hidden" name="code" value = <%= name%>/>
....
</form>
then get it from your servlet likewise,
request.getParameter("code"); // will return value of code
NOTE :
Remove from your jsp-code if above solution you gonna implement then,
request.setAttribute("code", name);

Related

servlet can't get option value from jsp

I'm doing a java web application using jsp and servlets.
I have a form and I retrieve different values from my db to populate an option. This is my form:
<form class="form" action ="<%=request.getContextPath()%>/aggiungiLibro" method ="post">
<div class="form__group">
<input type="text" placeholder="Titolo" class="form__input" name = "titolo"/>
</div>
<div class="form__group">
<input type="text" placeholder="Quantità disponibile" class="form__input" name="quantita" />
</div>
<div class="form__group">
<select class="form__input" name="autore">
<c:forEach items="${listaAutori}" var = "autore" >
<option value="${autore.idAutore}"><c:out value="${autore.nome} ${autore.cognome}" /></option>
</c:forEach>
</select>
</div>
<button class="btn btn-light" type="submit">Inserisci nuovo libro</button>
</form>
In the servlet I retrive my data with
String titolo = request.getParameter("titolo");
int quantita = Integer.parseInt(request.getParameter("quantita"));
int autore = Integer.parseInt(request.getParameter("autore"));
I get right values for 'titolo' and 'quantita' but I get the string '${autore.nome}' for 'autore'.
It seems like it doesn't replace the string with the actual value.
The field idAutore is spelt right.
(In the jsp page I see the correct values for ${autore.nome} ${autore.cognome})
Anyone can help me please? What I'm doing wrong?
I solved replacing this:
<option value="${autore.idAutore}">
with this:
<option value="<c:out value='${autore.idAutore}' />">

Why random checkbox choosing giving error,not in serial-wise in JSP page?

I am trying to make a basic shop-billing JSP project. now when i type random product quantity with checkbox it giving error like below image. but when i checked-value with serial wise, it is not giving the error, it giving me the result what i desiring. I have also check it is empty or not. but can't able to get out of this error. how can i get rid out of it?
Code:
<%--
Document : order
Created on : Jun 15, 2019, 3:11:06 PM
Author : Riddhi
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html>
<html lang="en">
<%# include file="header.jsp" %>
<h2 class="text-center"> ShopBilling </h2>
<p><br/></p>
<%
String Host = "jdbc:mysql://localhost:3306/shopbilling";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
PreparedStatement ps=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(Host, "root", "");
StringBuilder sb = new StringBuilder();
%>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="row">
<div class="col-md-6"><h3>Product Details</h3></div>
<div class="col-md-6 text-right">
Back to Home
</div>
</div>
<p></p>
<form action="" method="post">
<%
String products[] = request.getParameterValues("products");
String items[] = request.getParameterValues("item_no");
int sum=0;
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
%> <%
statement = connection.createStatement();
String u=request.getParameter("u");
int num=Integer.parseInt(products[i]);
String Data = "select * from products_tbl where id='"+num+"'";
rs = statement.executeQuery(Data);
while (rs.next()) {
%>
<input type="hidden" name="id" value='<%=rs.getString("id")%>'/>
<div class="form-group">
<label for="product_name">Product Name: <%=rs.getString("product_name")%></label>
<input type="hidden" class="form-control" id="product_name" name="product_name" value='<%=rs.getString("product_name")%>'>
</div>
<div class="form-group">
<label for="product_price">Product Single Price: <%=rs.getString("product_price")%></label>
<input type="hidden" class="form-control" id="product_price" name="product_price" value='<%=rs.getString("product_price")%>'>
</div>
<div class="form-group">
<label for="product_name">Item Quantity: <% out.println(items[i]); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<div class="form-group">
<label for="product_name">Product Total Price: <%
int num1=Integer.parseInt(items[i]);
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<hr>
<% sum= sum + gtotal; %>
<%
}
}
}
%>
<div class="form-group">
<label for="product_name">Grand Total: <%
out.println(sum); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<button type="print" onclick="window.print();" class="btn btn-warning">Print</button>
</form>
</div>
</div>
<%# include file="footer.jsp" %>
</html>
I think the problem in your code is with <input type="text" name="item_no" /> because every row in your above code has checkbox , when you submit your form only selected checkbox is passed , but all <input type="text" name="item_no" /> is passed even the null where you didn't give any value , so when you iterate you get null value with that as well .Now ,to solve this do like below :
//give value to your check-box i.e id of that row
<input type="checkbox" name="products" value ='<%=rs.getString("id")%>' />
//pass that id with your input type i.e item_no_1 ..etc
<input type="text" name='item_no_<%=rs.getString("id")%>' />
And then to get only particular value of Product Quantity where you have selected Checkbox do like below :
String products[] = request.getParameterValues("products");
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
//your code
<div class="form-group">
<label for="product_name">Product Total Price: <%
//getting item value of that selected checkbox
int item_no=Integer.parseInt(request.getParameter("item_no_" + products[i]));
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>

How to get input value from one jsp page to another jsp page?

I am trying to get a one-page input value to another page while clicking the order button.
while I will take a number of item value and click the order button, it will carry the value the order page. The page code is here,
<td><%=rs.getString("product_price")%></td>
<td> <input type="number" name="no_item" value="1" /></td>
<td class="text-center" width="250">
Order
Edit
Delete
</td>
The order page code is here,
<%
statement = connection.createStatement();
String u=request.getParameter("u");
String item_num =request.getParameter("no_item");
int num=Integer.parseInt(u);
String Data = "select * from products_tbl where id='"+num+"'";
rs = statement.executeQuery(Data);
String product_price;
while (rs.next()) {
%>
<input type="hidden" name="id" value='<%=rs.getString("id")%>'/>
<div class="form-group">
<h4 style="float:left; padding-right:8px;">Product Name:</h4> <h4> <%=rs.getString("product_name")%> </h4>
</div>
<div class="form-group">
<%
product_price = rs.getString("product_price"); int num1 = Integer.parseInt(product_price); %>
</div>
<%= item_num %>
<%= num1 %>
<%
}
%>
Onclick of order button add the input value in url query string. you have need to use java script in jsp page.
<script>
function order(page, id){
input_value = document.getElementById('no_item').value;
location.href= page+"?u="+id+"&no_item="+input_value;
}
</script>
Add the onclick function within order button.
<a onclick="order('order.jsp', '<%=rs.getString("id")%>')" class="btn btn-success">Order</a>
In order.jsp page you will get the input value.
request.getParameter("no_item");

Print hashmap value in jsp page

I am trying to call a HashMap value in jsp page but got error there and error says
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "res"
My code;
<c:forEach items="${onlineExamList}" var="item"
varStatus="loop">
<div>
<b>${item.question1}</b><br>
<div class="radio">
<label><input type="radio" value="a"
name="answers[${loop.index}]">${item.option1}</label>
</div>
<div class="radio">
<label><input type="radio" value="b"
name="answers[${loop.index}]">${item.option2}</label>
</div>
<div class="radio">
<label><input type="radio" value="c"
name="answers[${loop.index}]">${item.option3}</label>
</div>
<div class="radio">
<label><input type="radio" value="d"
name="answers[${loop.index}]">${item.option4}</label>
</div>
<input type="text" name="rightAnswer"
value="${item.rightAnswer}">
//problem in this line
<c:if test="${result != null}">
<br>
<br>
<b>Your answer: ${result.get("res"+loop.index).get(1)}</b>
<br>
</c:if>
</div>
<hr />
</c:forEach>
And this is how i have set hashmap from controller
Map<String, List<String>> mapResult = new HashMap<String, List<String>>();
int totalScore = 0;
for (int i = 0; i < answers.answers.size(); i++) {
List<String> result = new ArrayList<>();
String res = "Wrong";
if (answers.answers.get(i).equals(answers.rightAnswer.get(i))) {
res = "Correct";
totalScore+=10;
}
result.add(res);
result.add(answers.answers.get(i));
result.add(answers.rightAnswer.get(i));
mapResult.put("res" + i, result);
}
ra.addFlashAttribute("result", mapResult);
ra.addFlashAttribute("score", totalScore);
Same things printed on java page
for (int i = 0; i < 10; i++) {
System.out.println(mapResult.get("res" + i).get(0));
System.out.println(mapResult.get("res" + i).get(1));
System.out.println(mapResult.get("res" + i).get(2));
System.out.println("...................................");;
}
How can I print hashmap value in jsp page?
Please check try this.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${currentLoggedInUsersMap}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
I solve the problem by concating the string using concat like this
${result.get("res".concat(loop.index)).get(1)}
The mapResult object is a map containing string arrays
Hashmap<String, List<String>>
you may need to first get the Array from the map object and then iterate over it.
this may help?
<table>
<c:forEach var="results" items="${resultsMap['res' + loop.index]}" varStatus="loop">
<tr>
<c:forEach var="answer" items="${results}" varStatus="status">
<td>
<td>$answer</td>
</td>
</c:forEach>
</tr>
</c:forEach>
</table>

Why jsp returns null?

I have this code in one jsp and i want to sent to the another and display selected value and correct answer. In the first page i have this code:
<form method="post" action="result.jsp" >
<p>choose answer</p>
<select name="fill">
<option value="0">Fill</option>
<option value="1">England</option>
<option value="2">China</option>
<option value="3">France</option>
</select>
<input type="submit" name="sent" />
</form>
and then the second jsp:
<body>
<jsp:declaration>
String s = "";
</jsp:declaration>
<jsp:scriptlet>
s = request.getParameter("fill");
</jsp:scriptlet>
<h1>Your answer is <jsp:expression>s </jsp:expression>and correct is England</h1>
</body>
And it returns null, why?

Categories