Calling a JSP Function from another jsp file - java

I have create a simple application on jsp..
In my global function jsp file, I have created functions as follows:
<%! public double calcB(double w, double h){
double B = 0;
return B = (w / (h * h));
}
public String calcClassif(double B){
String classifi = null;
if(B >= 30)
classif = "Obese";
else if(B >= 25)
classif = "Overweight";
else if(B >= 18.5)
classif = "Normal";
else
classif = "Underweight";
return classif;
}
%>
Now in my my index.jsp file, I have written the following:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= calcBMI(we, he) %> <br> <br>
Classification: <%= classification %>
</form>
When I execute the application, the classification is not working.. How do I call the method to display me the correct classification ?
Please help.. Thanks

You are never assign a value into classification. You may try this:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
bmi = calcBMI(we, he);
classification = calcClassif(bmi);
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= bmi %> <br> <br>
Classification: <%= classification %>
</form>

Whenever your JSP is compiled by your servlet container, it is compiled under different names every time. This makes it hard to use a JSP page function in another JSP page. I would recommend you to start using servlets and POJOs for your data processing needs.
Anyway, you don't have any variable named classification (index.jsp:21), therefore it is not displayed and the server logs an error to the console, and not to the client like PHP.

Related

Form validation issue in HTML

People, I am having a problem in my HTML form validation. Currently I am using JSP (at the back end) to extract the form data and jquery to validate the data in my HTML file. Problem is that when i run my HTML on server (apache tomcat), my jquery validation snippet doesn't work and data simply gets passed to the JSP file. Only if I remove the action attribute from form tag then the validation code runs but JSP doesn't get called. Here are my HTML and JSP scripts.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<form class = ".form-inline"
method = "POST" action = "process.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit">Submit</button>
<script type="text/javascript">
/*global $*/
$(function(){ // JS form validation snippet.
// variables are used to
store different types of
regex expressions.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email
= /^([\w-]+ (?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-] {0,66})
\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
var ck_username =
/^[A-Za-z0-9_] {1,20}$/;
var ck_password =
/^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
var flag;
$("#submission").on("click",
function validate(form){
var day = $("#date").val();
var month = $("#month").val();
var year = $("#year").val();
if ((day >= 1 && day <= 31 ) &&
(month >= 1 && month <= 12) &&
(year >= 1930)) {
//alert("correct date ");
}
else {
//alert("wrong date");
}
//alert("submission active");
// variable extracts
the specific user input from the form.
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
var confirmpassword = $("#confirmpassword").val();
var errors = [];
if (!ck_name.test(firstname)) {
errors[errors.length] = "Your valid first Name .";
}
if (!ck_name.test(lastname)) {
errors[errors.length] = "Your valid last Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] =
"Yor must enter a valid email address.";
}
if(!ck_username.test(username)) {
errors[errors.length] =
"Your valid UserName no special char .";
}
if (!ck_password.test(password) ) {
errors[errors.length] =
"Your must enter a valid Password ";
}
if (!ck_password.test(confirmpassword) ||
password !== confirmpassword) {
errors[errors.length] = "password doesn't match ";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
//$.get("process.jsp", [firstname, lastname, email, username,
password, confirmpassword, day, month, year]);
//alert(".get() executed");
return true;
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
//alert(msg);
}
});
});
</script>
</div>
</form>
there is a syntax error in your javascript please check your code properly
if i remove all your javscript code then i am able to do validation.
check my code you will get an idea.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//if(request.getParameter("btnsubmit")!=null){
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
// }
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<script type="text/javascript">
function validate(form) {
alert('hi');
}
</script>
<form class = ".form-inline"
method = "POST" action ="index.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit" name='btnsubmit'>Submit</button>
</div>
</form>

getting a value from a variable in jsp's input type

In my jsp i have a variable
String str = "Get_Name";
What can i do to have my variable(str) directly accessed in the input type shown below? By this I want to see the form auto filled with the the variable I have instead of me filling it.
<input id="vendorName" name="vendorName" type="text" class="txtsmall2" />
ANSWER ALSO CONTAINS SOLUTION FOR PROBLEM DISCUSSED IN COMMENTS.
Do this.
<%
long val = 2; //can be anything.
if(val > 1) {
%>
<input id="vendorName" name="vendorName" type="text" class="txtsmall2" value="<%=str%>"/>
<%
else {
%>
<input id="vendorName" name="vendorName" type="text" class="txtsmall2" />
<%
}
%>
<%=str%> is called as expression tag.

How to send variable in action java class to jquery?

When I click on the button will be equal to the amount of undefind while the amount is equal to 1
in jsp page :
<%
String err1 = (String) request.getAttribute("err2");
int code = 0;
if (err1 != null){
code = Integer.parseInt(err1);
System.out.println(" code " + code);
}
%>
<button type="button" id="btnok">ok</button>
<br />
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
<br />
in jquery code:
$(document).ready(function() {
$("#btnok").click(function(event) {
var xxx = $("#txtcode").val();
alert("xxx 1 test + " + xxx);
});
});
The most likely reason is that the condition:
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
is not being met and the input is not being inserted to the DOM. Reload the page and view the page source to see if the input is inserted.

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