using a scriplet inside a javascript function - java

I wanted to use a scriplet inside a java script function. I wanted to check for some attribute's vale and give an alert according to that. Following is the function in which the only scriplet statement gives an error.
function UploadMessage() {
<% if((String)request.getAttribute("SuccessMessage").compareTo("Uploaded successfully") == 0) { %>
alert("File Successfully uploaded !");
<%
} %>
}
Is there any way i can do this ? What is the problem here ?
NOTE : I have placed the above snippet in a jsp page

function UploadMessage() {
<% if(((String)request.getAttribute("SuccessMessage")).equals("Uploaded successfully")) { %>
alert("File Successfully uploaded !");
<%
} %>
}
Problem was -
The method compareTo(String) is undefined for the type
Object
Incompatible operand types String and int

Related

How to call a variable with JSP?

In JSP I have created a simple variable like this:
<%
if (request.getSession().getAttribute("user") != null) {
String status = "online";
}
else {
String status = "offline";
}
%>
In HTML I call the variable like this: ${status}
So the string "offline" or "online" would just be a CSS class, as you see in the code below:
<img class="profile-pic" src="../assets/img/reza.png" alt="Chin"> <i class="status ${status}"></i>Reza
So the whole code looks like this:
<%
if (request.getSession().getAttribute("user") != null) {
String status = "online";
}
else {
String status = "offline";
}
%>
<div class="user-section">
<img class="profile-pic" src="../assets/img/reza.png" alt="Chin"> <i class="status ${status}"></i>Reza
</div>
but from Intellij I get the warning:
Cannot resolve variable 'status'
How can I fix this?
You have a problem with scopes, when you declare a variable inside an if or else block you can use this variable just in that scope, you can solve your issue like so :
<%
String status = "offline"; // declare the variable outside the if else
if (request.getSession().getAttribute("user") != null) {
status = "online"; // if the condition is correct then assign "online"
}
%>
After your edit
It seems you are using the variable name with a wrong way, instead you have to use :
<i class="status <%=status%>">
Instead of :
<i class="status ${status}">
Per your updated code, you need to reference "status" like this in your HTML:
<div class="user-section">
<img class="profile-pic" src="../assets/img/reza.png" alt="Chin"> <i class="status <%=status%>"></i>Reza
</div>
"JSP" is processed "server side". It's output is HTML, which is then sent to your browser.
The Java variable "status" is set to the Java string "offline" or "online" on the server. You can use the JSP tag <%= %> to write its value into your HTML stream.

How to check JSP variable and hide if value is null/empty or some specific string?

I am creating a project where i am getting set data in JSP page from database.
if any field data value is null the jsp page is showing null but i do not want to show it on jsp page. please help. i am getting data from bean.
<%=p.getOffer()%>
<% String s = p.getOffer() %>
<% if (<%=s ==null) { %>
show nothing
If you are coding java inside a jsp, you need to use scriptlet tags(<% and %>). So if you are checking for conditions you need to open a scriptlet tag.
<%
String s = p.getOffer();
if (s != null && !s.equals("")) {
out.print(s);
} else { %>
<!-- s is either null or empty. Show nothing -->
<% }%>
What exactly do you want to show when the value is null? Anyway, your approach looks good:
<%=p.getOffer()%> // Here you print the value "offer". If you don't want to show it when it is null, remove this line
<% String s = p.getOffer() %>
<% if (<%=s ==null) { %> // the <%= is unnecessary. if(s==null) is enough
show nothing // show nothing, why not inverse the if and show something
Here another approach:
<%
String s= p.getOffer();
if(s != null){ %>
Offer: <%= s%>
<% }%>
That way you only print the offer when the variable is not null.
By the way: naming a String variable "s" is not recommended, call it "offer" or something to facilitate the reading.

Display a session if not null in jsp file

I am trying to display a session only if it is not null in jsp file and I am having issues as shown
Syntax error on token "<", invalid Expression 59: 60: <% if(request.getAttribute("message") != null) 61:
this is my jsp file where I am checking if the session is not null but it is not working
<% if(request.getAttribute("message") != null)
{
<%=session.getAttribute("message")%>
}
%>
Please how do I display a session only if it is not null
You cannot use the <%= construct within a scriptlet block <% %>. You will have to write Java code to do this:
<% if(request.getAttribute("message") != null)
{
out.println(session.getAttribute("message"));
}
%>
Note that the <%= expression %> construct is shorthand for out.println(expression).

Print javascript alert with the value available in request object

I am trying to alert a value which is available in request object, following is my code:
<%
String isValidTransaction="";
if (request.getAttribute("isValidTransaction") != null)
{
isValidTransaction = request.getAttribute("isValidTransaction").toString();
%>
<script>
var transactionAlert = "<%=isValidTransaction%>";
if(transactionAlert.length == 0)
{
alert(transactionAlert);
}
</script>
<span class="formError" id="isValidTransaction">
<h1><%=request.getAttribute("isValidTransaction").toString()%></h1>
</span>
<%}%>
but the alert message is printed and the whatever is printed in <h1><%=request.getAttribute("isValidTransaction").toString()%></h1> is getting printed.
so, how to alert a value using javascript which is available in request object?
thanks
You should use console.log() instead of alert() function. Because alert() just return object.toString().

java.lang.NumberFormatException: null

I have created a login form which contains validations for each field. When i click on submit button function validation() will be invoked to validate all the fields and after successful validation it will redirect to another jsp page where all the details will be inserted in to the Oracle database.
But I'm getting "org.apache.jasper.JasperException: java.lang.NumberFormatException: null" exception. Also "The server encountered an internal error () that prevented it from fulfilling this request" error. I hope you will help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function validate()
{
if(document.frm.username.value=="")
{
alert("Please enter Username");
document.frm.username.focus();
}
else if(document.frm.mobile.value=="")
{
alert("Please Enter your contact number");
document.frm.mobile.focus();
}
else
{
window.location = "insert.jsp";
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr><td>User Name:</td><td><input type="text" name="username"></td></tr>
<tr><td>Contact Number:</td><td><input type="text" name="mobile"></td></tr>
<tr><td><input type="submit" value="Submit" onclick="validate()"></td><td></td></tr>
</table>
</form>
</body>
insert.jsp:
<body>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
Connection con=null;
int mobile=Integer.parseInt(request.getParameter("mobile"));
String username=request.getParameter("username");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","manager");
Statement st=con.createStatement();
st.executeUpdate("insert into stud values("+mobile+",'"+username+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
}
%>
</body>
You're redirecting the browser to do a GET on insert.jsp, but you're not supplying the request parameters to that new URL. Thus, your JSP fetches the mobile request parameter, which is null, and then tries to parse that to an integer, yielding the NumberFormatException.
What you could do is append the request parameters to the URL, like so:
window.location = "insert.jsp?mobile=" + document.frm.mobile.value + "&username=" + document.frm.username.value;
But it would be even better to submit those values in a POST request, instead of a GET. I think you could achieve that by adding a action="insert.jsp" attribute to the form tag, changing the onClick attribute to onSubmit and removing the
else {
window.location = "insert.jsp";
}
because that would allow the browser to resume its normal form submission. If you combine that with an return false; statement after focussing on the empty fields, you'll prevent the browser from submitting the form.
So what will happen if your mobile number is blank ?
int mobile=Integer.parseInt(request.getParameter("mobile"));
You're asking Integer.parseInt() to parse an empty or null string and that's causing your problem.
From the doc:
Throws:
NumberFormatException - if the string does not contain a parsable integer.
You need to check that mobile is populated and.or handle the scenario when it's not.
I wouldn't use an Integer to store a mobile number, btw. The number of digits could cause an overflow and/or you may want to maintain structure (e.g. country code and the number) etc.
If you are using parseInt(), you should catch an exception somewhere:
int mobile;
try {
mobile = Integer.parseInt(request.getParameter("mobile"));
} catch (NumberFormatException e) {
// do something
}
In your case, request.getParameter("mobile") is probably returning null.
Edit: as nother already noted - storing phone number in an integer may not be a good idea. Try Long instead.
First, your code is very dangerous. You should check null or empty on the server side! Using PreparedStatement instead of Statement.
Second, the code window.location = "insert.jsp"; will not work as your expectation.
Use action="insert.jsp" to make data send to that page. Then, on your js function, return false if it does not pass the condition, otherwise, return true;
Using onSubmit="return validate()" instead of onClick event.

Categories