Print javascript alert with the value available in request object - java

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

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.

How to pass message from servlet to jsp?

I want to pass a status parameter from servlet to jsp. I am sending it through
response.sendRedirect("newpage.jsp?status=yes");
If status = yes then show success message in <div> and then set status to null. But when the newpage.jsp loads at the first time the value of status is null and it gives null pointer exception.
Same thing happens with session also.
<%
String status = request.getParameter("status");
System.out.println("Check Successful of Status"+status);
if (status.equalsIgnoreCase("yes")) {
System.out.println("Check Successful of Status");
%>
<div style="color: green;" align="center">Selected tenant approved successfully</div>
<script type="text/javascript"> window.location.href = window.location.href.split("?")[0]; </script>
<%
request.setAttribute("status1", null);
%>
In Servlet you can use
request.setAttribute("status","yes")
in jsp, you can retrieve using
request.getAttribute("status");
Yes, I missed the point
for above u need to use
RequestDispatcher rd = request.getRequestDispatcher("somefile.jsp");
rd.forward(request,response);
If u want to use response.sendRedirect("somefile.jsp"),
u can set the variable in session as
HttpSession session = request.getSession(false);
session.setAttribute("status","yes")
and get it back as
session.getAttribute("status").
Once used, u can remove it as
session.removeAttribute("status")
request.setAttribute("status1", yourstatus);
getServletContext().getRequestDispatcher("yourpageyouwanttosend.jsp").forward(request, response);
your view <%= request.getAttribute("status1") %>
You are using status as parameter name and you are comparing status1 in your JSP
if (status1.equalsIgnoreCase("yes")) {
Note:
placing javacode on jsp is not good thing, switch to JSTL

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.

How to get returned data from servlet with Jquery?

I am currently learning jsp/servlet, and trying to make an online bookstore. Using jquery, I was able to send the GET request to the servlet. Upon success, it will reload the browseBookArea div with browseBookArea.jsp. What I don't understand is, this procedure causes infinite loop on my glashfish servet (it happens within the BrowseBookTag.java. I put a System.out.println there to check it).
Is there another way to get the data returned from servlet to Jquery, so I can do it properly? Setting variables in session is not a good way for this I think. I saw the example with jquery.get where we can get the response data.
var currentCat = "all";
$(document).ready(function(){
$(".categoryItem").click(function(event){
$("#browseBookArea").fadeToggle(100);
currentCat = $(this).attr("id");
$.get("GetBookFromCategoryServlet",{selectedCat:currentCat, currentPage:1}); });
$("#browseBookArea").ajaxSuccess(function(){
$(this).show(300);
$(this).load("Components/browseBookArea.jsp");
});
$(".pagination").click(function(event){
$("#browseBookArea").fadeToggle(100);
var page = $(this).attr("id");
alert(currentCat);
$.get("GetBookFromCategoryServlet",{selectedCat:currentCat, currentPage:page});
});
});
Here is my browseBookArea.jsp:
<div id="browseBookArea" class="span-15 last">
<%System.out.println("Back from servlet");
Collection c = (Collection) request.getAttribute("booksFromCat");
if (c == null) {
Collection c1 = (Collection) session.getAttribute("booksFromCat");
if (c1 == null) System.out.println("Books are null");
}
%>
<myJavaTags:BrowseBookTag books="${booksFromCat}" pageSize="${pageSize}" >
<c:if test="${not empty book1 }">
<div class="span-7">
<center>
<img width="115px" height="115px" src='${book1.photoPath}.jpg'/>
<p>${book1.price}<br/><a>${book1.title}</a> <br/>${book1.authorName}<p>
</center>
</div>
</c:if>
<c:if test="${not empty book2 }">
<div class="push-1 span-7 last">
<center>
<img width="115px" height="115px" src='${book2.photoPath}.jpg'/>
<p>${book2.price}<br/><a>${book2.title}</a> <br/>${book2.authorName}<p>
</center>
</div>
</c:if>
<hr class="space">
</myJavaTags:BrowseBookTag>
<hr class="space"/>
</div>
My BrowseBookTag:
public void doTag() throws JspException, IOException{
// if (books ==null){
// admin = AdminBeanFactory.getAdminInstance();
// books = admin.browseBook(cat);
// }
Iterator bookIt = books.iterator();
JspContext jsp = getJspContext();
int i = 0, count = 0;
System.out.println("Total book size in browse tag: "+books.size());
while (bookIt.hasNext() && i < pageSize){
BookDTO b = (BookDTO) bookIt.next();
if (count == 0){
jsp.setAttribute("book1", b);
if ((i+1) == pageSize){
jsp.setAttribute("book2", null);
getJspBody().invoke(null);
}
count++;
}else{
jsp.setAttribute("book2", b);
getJspBody().invoke(null);
count = 0;
}
i++;
}
}
I found the culprit. It is:
$("#browseBookArea").ajaxSuccess(function(){
$(this).show(300);
$(this).load("Components/browseBookArea.jsp");
});
Bad, bad, bad. This demonstrates that I didn't know the meaning of success method call. I've just realized that if I let the #browseBookArea div to load every time, it causes a successful operation, and then it will perform again which ultimately leads to recursion. Finally I got out of this pitfall. The correct thing should be:
$(".categoryItem").click(function(event){
$("#browseBookArea").fadeToggle(100);
var currentId = $(this).attr("id");
$.get("GetBookFromCategoryServlet",{selectedCat:currentId, currentPage:1}, function(data){
$("#browseBookArea").fadeIn(300);
$("#browseBookArea").load("Components/browseBookArea.jsp");
});
});
I just need to define a successful handler after the GET request, and the successful handler must not be the div which invokes the operation.

Categories