Display values from database in input form (JSP) - java

i am looking for some better solutions. I am making a matching word game for my school project, but i have some issues. Instead of this code style, i want to my values be displayed from sql database randomly, but without repeating same words. I try something, but it doesnt work, so i will appreciate any of your help.
Here is screenshot of my litlle game: when i click start words will be open, and the game will start...
My code is:
<!DOCTYPE html>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.*" %>
<%! String[] wordsleft ={"Belgrade","Zagreb","Sarajevo", "Washington", "Paris" };
%>
<%! String[] wordsright ={"Serbia","Bosnia","Croatia","France","USA"};
%>
<%!
String printleft(){
Random rand = new Random();
int a = rand.nextInt(4 - 0 + 1) + 0;
return String.valueOf(wordsleft[a]);
} %>
<%!
String printright(){
Random rand = new Random();
int a = rand.nextInt(4 - 0 + 1) + 0;
return String.valueOf(wordsright[a]);
} %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="cssstyle.css" rel="stylesheet">
<title>Matching Words</title>
</head>
<body>
<h1 id="welcome">Welcome!</h1>
<p class="tekst">Spojnica je igra sa rečima. <br><br>U dve kolone je prikazano po 5 reči.
Svaka reč u levoj koloni ima svoj par u desnoj koloni. Za svaki spojen par dobijate 3 poena.
</p>
<div id="container">
<div class="containerlevo">
<input type="submit" class="leftword" name="prvo" id="firstleft" value="?" />
<input type="submit" class="leftword" name="drugo" id="secondleft" value="?" />
<input type="submit" class="leftword" name="trece" id="thirdleft" value="?" />
<input type="submit" class="leftword" name="trece" id="fourthleft" value="?" />
<input type="submit" class="leftword" name="trece" id="fifthleft" value="?" />
</div>
<div class="containerdesno">
<input type="submit" class="rightword" name="prvo" id="firstright" value="?" />
<input type="submit" class="rightword" name="drugo" id="secondright" value="?" />
<input type="submit" class="rightword" name="trece" id="thirdright" value="?" />
<input type="submit" class="rightword" name="drugo" id="fourthright" value="?" />
<input type="submit" class="rightword" name="trece" id="fifthright" value="?" />
</div>
<form action="Rezultat" method="post" >
<input class="button start" type="button" id="start" onclick = "printright(); printleft();" value="START" name="start"/>
<input class="button" type="submit" id="end" value="END" name="end"/>
</form>
</div>
</body>
</html>
<script>
function printleft(){
document.getElementById("firstleft").value = "<%= printleft() %>";
document.getElementById("secondleft").value = "<%= printleft() %>";
document.getElementById("thirdleft").value = "<%= printleft() %>";
document.getElementById("fourthleft").value = "<%= printleft() %>";
document.getElementById("fifthleft").value = "<%= printleft() %>";
document.getElementById("start").disabled = true;
}
function printright(){
document.getElementById("firstright").value = "<%= printright() %>";
document.getElementById("secondright").value = "<%= printright() %>";
document.getElementById("thirdright").value = "<%= printright() %>";
document.getElementById("fourthright").value = "<%= printright() %>";
document.getElementById("fifthright").value = "<%= printright() %>";
document.getElementById("start").disabled = true;
}

To use a database on the names is a lot of stuff to add and learn. Maybe you want to start out with name-files - that seems easier to start with.
Nevertheless. First you need to create a database and depending on the jdbc driver used, you will create jdbc connection string to your database (here a mysql).
String connurl = "jdbc:mysql://localhost:3306/riddle?profileSQL=true";
Then you open need to load the driver class once in your application, usually at init() or even better as a context listener. As you are using JDBC it will be best practice to define a datasource in the application deployment descriptor.
Describing all details of this is clearly out of scope here, and definitely has been written up better somewhere else. You can find numerous samples: Netbeans has a tutorial showing this here https://netbeans.org/kb/docs/web/mysql-webapp.html
You should then start with a class that provides you the list of words, a model class. The model class will hide all the data fetching from your JSP page.
And this is where you should go from where you are: Remove all the functions from your JSP and put the data handling in a model class. That model class is then used in your JSP to provide the arrays.
When you got that going, you only need to change the model to read from file instead of const array. If you have that working, tackle the database.

Related

Is there any other way to convert string value into integer value in jsp? I am trying a basic program in jsp

index.html
<html>
<head>
<title>AddModule | Home page</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<form action="op.jsp">
<div class="card">
<div class="card-header bg-dark text-white">
<h3>Provide me a number</h3>
</div>
<div class="card-body">
<div class="form-group">
<input name="n1" type="number" class="form-control" placeholder="Enter n1">
</div>
<div class=form-group>
<input name="n2" type="number" class="form-control" placeholder="Enter n2">
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">Divide</button>
</div>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
Getting an exception in op.jsp named java.lang.NumberFormatException
HTTP Status 500-Internal Server Error
op.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Jsp Page</title>
</head>
<body>
<%
String n1= request.getParameter("n1");
String n2= request.getParameter("n2");
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
%>
<h3>Result is <%=c %></h3>
</body>
</html>
While converting value from string to integer it is generating an exception
Also Tried below code but still not working
<%int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n1"));
int c=n1/n2 %>
The problem is not with your code, but rather how you run it.
You need to access index.html first to allow you to input numbers, then hit Divide. This will invoke op.jsp with n1 and n2 as parameters.
If you try to access op.jsp directly, your code will run without values for n1 and n2. If you don't have input, then trying to parse input as integers will obviously fail.
If you want to simplify testing, you can manually specify HTTP GET query parameters in the URL using op.jsp?n1=42&n2=7
<%
String n1 = request.getParameter("n1");
String n2 = request.getParameter("n2");
int n1Val,n2Val;
if(n1 != null){
n1Val=Integer.parseInt(n1);
}
if(n2!=null){
n2Val=Integer.parseInt(n2);
}int c;
if(n1 != null && n2!=null)c=n1Val + n2val;
%>

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>

Accessing selected dropdown items using 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);

Embedding JavaScript code in JSP won't call the JS function

Given the following code :
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<script>
function verifyEmptyString()
{
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
return !(username == null || username == "" || password == null || password == "");
}
</script>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form id="loginForm" action="loginPage" onsubmit="verifyEmptyString()" >
<p style="font-size:15px"> <span style="color:red;font-weight:bold;">*</span> Username: <input type="text" name="username"><br> </p>
<p style="font-size:15px"><span style="color:red;font-weight:bold;">*</span> Password : <input type="password" name="password"><br> </p>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
I'm trying to call the JS function verifyEmptyString() , but the JSP doesn't call the function.
Any idea what's wrong with the code ?
The function is being called (I added an alert to verify). But you want to return the value of the function in the onclick event:
<form id="loginForm" action="loginPage" onsubmit="return verifyEmptyString(this)" >
Try something like this : http://jsfiddle.net/daguru/RBYnc/1/
var myForm = document.getElementById('loginForm');
myForm.addEventListener("submit", function(ev) {
ev.preventDefault(); // to stop the form from submitting
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if(!(username == null || username == "" || password == null || password == "")){
this.submit(); // If all the validations succeeded
alert("submiting")
}
});
Here is the solution :
<form onsubmit="return verifyEmptyString(this)" id="loginForm" action="loginPage" >
For anyone who might encounter this problem in the future , you need to change the onsubmit ...
From this :
onsubmit="verifyEmptyString()"
To this :
onsubmit="return verifyEmptyString(this)"
I do not quite understand why we need to pass thisas a parameter to the function, because it is not accepted in the actual function definition function verifyEmptyString() . You are directly referring the form elements inside the function.
On the otherhand, if your code is similar to the below scenario,
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(obj) {
var x = obj["firstname"].value;
alert(x);
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="action.jsp"
onsubmit="return validateForm(this)" method="post">
First name: <input type="text" name="firstname"> <input
type="submit" value="Submit">
</form>
</body>
</html>
In this scenario, we are making use of the passed parameter this.
It refers to the current context, In our case, it is the form whose name is myForm
But in your original scenario, you are directly referring the form inside the javascript function by calling document.forms["loginForm"]["username"].value.

Find whether check boxes are checked inside a servlet

I have several check box in a form I just wanna way to check whether they are checked or not .
If checked i need to store their id in the database(that i can do it ) . But my question is how to determine whether are checked or not instead of checking for each check box on at a time . I need to check whether its checked or not inside a servlet.
This is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Role Id<input type="text" name="roll_id"/><br>
Role Name<input type="text" name="roll_name"/><br>
Role Description<textarea name="roll_desc"></textarea><br>
<br>
<br>
Screen1<br>
tab1<br>
<input type="checkbox" name="s1_t1_view" value="s1_t1_view" >view<br>
<input type="checkbox" name="s1_t1_add" value="s1_t1_add" >add<br>
<input type="checkbox" name="s1_t1_edit" value="s1_t1_edit" >edit<br>
<input type="checkbox" name="s1_t1_delete" value="s1_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s1_t2_view" value="s1_t2_view" >view<br>
<input type="checkbox" name="s1_t2_add" value="s1_t2_add" >add<br>
<input type="checkbox" name="s1_t2_edit" value="s1_t2_edit" >edit<br>
<input type="checkbox" name="s1_t2_delete" value="s1_t2_delete" >delete<br>
Screen2<br>
tab1<br>
<input type="checkbox" name="s2_t1_view" value="s2_t1_view" >view<br>
<input type="checkbox" name="s2_t1_add" value="s2_t1_add" >add<br>
<input type="checkbox" name="s2_t1_edit" value="s2_t1_edit" >edit<br>
<input type="checkbox" name="s2_t1_delete" value="s2_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s2_t2_view" value="s2_t2_view" >view<br>
<input type="checkbox" name="s2_t2_add" value="s2_t2_add" >add<br>
<input type="checkbox" name="s2_t2_edit" value="s2_t2_edit" >edit<br>
<input type="checkbox" name="s2_t2_delete" value="s2_t2_delete" >delete<br>
<input type="submit" name="sumbit" text="submit">
</body>
</html>
But in my code I have several check boxes . I need to hardcode that for every check box . Is there way so that i put it in a loop and check for all check boxes ?
To be simple, you can use the name attribute to get the data since you are using different name for each checkbox.
In Servlet :
String[] s1_t1_view = request.getParameterValues("s1_t1_view");
String[] s1_t1_add = request.getParameterValues("s1_t1_add");
If you want to use group of checkbox to give the user a choice between multiple values, you will need to iterate over the group in the servlet. You can use this :
In HTML : (same name = same group)
<input type = "checkbox" name = "s1_t1" value = "s1_t2_view" >View <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_add" >Add <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_edit" >Edit <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_delete" >Delete<br>
In Servlet :
String[] results = request.getParameterValues("s1_t1");
for (int i = 0; i < results.length; i++) {
System.out.println(results[i]);
}
You can use
String[] checked = request.getParameterValues("checkboxName");
and then check the checked value
For me this one worked.
String[] selecttype=request.getParameterValues("selectType");
//selectType is the name of checkbox in jsp page.
This will return selected checkbox values.
Create hidden fields as
Now in your servlet as: String[] names = request.getParameterValues("checkbox");
PrintWriter pw = new PrintWriter(new File("/Desktop/sticker.txt"));
for(int i=0; i < names.length; i++) {
if(i + 1 < names.length && names[i].equals(names[i+1])) {
pw.write(names[i] + ",true\n");
++i;
} else {
pw.write(names[i]+",false\n");
}
}
pw.close();

Categories