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

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.

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;
%>

Display values from database in input form (JSP)

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.

How to pass java string variable to the javascript function by jsp expression tag?

I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!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>
<script>
function stringGenerate(str){
var x = document.getElementsByTagName("input");
x[0].value = str;
}
function numberGenerate(num){
var x = document.getElementsByTagName("input");
x[1].value = num;
}
</script>
</head>
<body>
<%
String num ="1234567890";
String str = "abcdefghij";
%>
<input type="text" name="string" readonly="readonly"/>
<input type="text" name="number" readonly="readonly"/><br/><br/>
<input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" />
<input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" />
</body>
</html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
Try using single quote ' when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'.
You should add the ' chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \" to escape as this would break your code.

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();

Number guesser game generates a different numbers each guess

I have a Java Server Page that lets the user pick a number of their choice from 1-1000. The page then uses the number entered and finds out if the number matches the number that is generated. -- Pictures below if ^ is unclear. Currently, the program generates a different number each time the user guesses a number -- whether it is correct or not. How do I make it so that the program only generates a number when the user either refreshes the page or guesses correctly?
JSP code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import = "Chapter12.RandomGuess" %>
<jsp:useBean id = "randomGuessId" class = "Chapter12.RandomGuess" scope = "page" >
</jsp:useBean>
<jsp:setProperty name = "randomGuessId" property = "*" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guess Random Number</title>
</head>
<body>
<h3>Guess a number from 1 to 1000</h3>
<form method = "post">
Enter guess: <input name = "guess" /><br /><br />
<input type = "submit" name = "Submit" value = "Take Guess" />
<input type = "reset" value = "Reset" /><br /><br />
Your guess of <jsp:getProperty name = "randomGuessId" property="guess" />
is <%= RandomGuess.guess(randomGuessId.getAnswer()) %>
</form>
</body>
</html>
Java code:
import java.util.Random;
public class RandomGuess {
private int guess;
Random r = new Random();
private int low = 1;
private int high = 1000;
int R = r.nextInt(high-low) + low;
public int getGuess() {
return guess;
}
public void setGuess(int newValue) {
guess = newValue;
}
public String getAnswer() {
String tooLow = "too low.";
String tooHigh = "too high.";
String correct = "correct!";
if(guess == R)
return correct;
else if(guess < R)
return tooLow;
else
return tooHigh;
}
public static String guess(String s) {
return s;
}
}
picture: http://i.imgur.com/dMSZ7SD.png
Every time the page refreshes, a new instance of the bean is created - with a new number.
To preserve the number across calls, use a static field in your class.
Better yet, use JavaScript!
Find complete program here:http://sickprogrammersarea.blogspot.in/2014/01/creating-number-guesser-in-jsp_8296.html
Hello friends this is a simple program of creating a number guesser in JSP....Have a look...
Number.jsp:
<html>
<head><title>Number Guesser</title></head>
<body>
<% int num=(int)(Math.random()*100); %>
<h2>Welcome To Number Guesser</h2>
<br><h3>Want To Check Your Guessing Power.....GIVE IT A TRY?????</h3>
<form name="guess" action="try.jsp?c=0" method="post">
<input type="text" name="val" value="<%=num %>" hidden>
<input type="submit" value="GO">
</form>
</body>
</html>
try.jsp :
<html>
<head><title>Number Guesser</title></head>
<body>
<% String str=request.getParameter("val");
boolean flag=true;
int num=Integer.parseInt(str);
int c=Integer.parseInt(request.getParameter("c"));
if(c!=0)
{
int guess=Integer.parseInt(request.getParameter("guess"));
if(num==guess){
flag=false;
%>
<h3>Congratulation...You Successes After <%=c%> attempts</h3>
<b>Want to Improve...try again</b>
<% }else if(num>guess) { %>
<h3>You Guessed Lower...Try Bigger Number</h3>
<% }else{ %>
<h3>You Guessed Higher...Try Smaller Number</h3>
<% }
}
if (flag) { c++; %>
<h3>I Guessed a Number between 1 to 100. Try To Guess..</h3>
<form name="guess" action="try.jsp?c=<%= c%>" method="post">
<input type="text" value="<%=num %>" name="val" hidden>
Make Your Guess : <input type="text" name="guess" size=10 maxlength=3>
<input type="submit" value="GO">
</form>
<% } %>
</body>
</html>
You could pass the user number back as a query parameter.
I'm guessing you are not too familiar with the MVC pattern or Spring, but there are plenty of resources available to get you quickly up and running. I'll try to make a strip down demo later, if I remember.

Categories