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.
Related
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.
I have two jsp pages: search.jsp and update.jsp.
When I run search.jsp then one value fetches from database and I store that value in a variable called scard. Now, what I want is to use that variable's value in another jsp page. I do not want to use request.getparameter().
Here is my code:
<%
String scard = "";
String id = request.getParameter("id");
try {
String selectStoredProc = "SELECT * FROM Councel WHERE CouncelRegNo ='"+id+"'";
PreparedStatement ps = cn.prepareStatement(selectStoredProc);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
scard = rs.getString(23);
}
rs.close();
rs = null;
} catch (Exception e) {
out.println(e.getLocalizedMessage());
} finally {
}
%>
How can I achieve this?
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
Use sessions
On your search.jsp
Put your scard in sessions using session.setAttribute("scard","scard")
//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.
And in your next page you retrieve it using session.getAttribute("scard")
UPDATE
<input type="text" value="<%=session.getAttribute("scard")%>"/>
Use below code for passing string from one jsp to another jsp
A.jsp
<% String userid="Banda";%>
<form action="B.jsp" method="post">
<%
session.setAttribute("userId", userid);
%>
<input type="submit"
value="Login">
</form>
B.jsp
<%String userid = session.getAttribute("userId").toString(); %>
Hello<%=userid%>
How can I send data from one JSP page to another JSP page?
One of the best answer which I filtered out from above discussion.
Can be done in three ways:
using request attributes:
Set the value to send in request attribute with a name of your choice as request.setAttribute("send", "valueToSend") and retrieve it on another jsp using request.getAttribute("send");
using session attributes
Similar to above but using session object instead of request.
using application attributes
Same as 1 and 2 above but using application object in place of request and session.
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp'
Make three hidden text boxes and a button that is click automatically(using javascript).
//Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)
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().
I am trying to get this if statement to display
<s:hidden id="userNameTest" value="nameTest"></s:hidden>
<s:if test="userNameTest.value.equals('false')">
That name is already in use.
</s:if>
if this happens in my action page
public String createUser()
{
user.set_permission("user");
if(user.get_userName().matches("^([a-zA-Z0-9]{5,15})$")&&(user.get_password().matches("^((?=.+\\d).{8,20})$")))
{
if(manager.checkUserName(user.get_userName()) == false)
{
manager.createUser(user);
valueButton = "userPage";
}
else
{
valueButton = "createUser";
}
}
else
{
nameTest = false;
valueButton = "createUser";
}
return valueButton;
}
I have tried making the hidden field false in the jsp onclick, I have tried making it false in the action as you see above. I have looked it up on other sites but cant find what I am after.
If your variable nameTest is boolean then <s:if test="!nameTest"> User Name is Taken </s:if> will work.
Please use JSTL core tags. As a convention the prefix would then be <c:>
The solution would be to set request attribute nameTest in your action class:
Boolean comparison:
<c:if test="nameTest eq false">
..
</c:if>
String comparison:
<c:if test="nameTest eq 'false'">
..
</c:if>
First of all in order to check if your value is getting properly in JSP , you can either use s:debug or can print it like <s:property value = "nameTest"/>.
If you want to use if condition, You can directly check throught
<s:if test="nameTest =='false'"> User Name is Taken </s:if>
Try out following.
1)
<s:if test="'${nameTest}'=='false'">
That name is already in use.
</s:if>
2) if that variable is boolean then try out this
<s:if test="%{${nameTest} == false}">
That name is already in use.
</s:if>
nameTest must have getter and setter in action class
Since you're using struts2, a more generalised approach to show alerts based on the result is as follows (I am also using the Bootstrap framework here because it gives a way better look, feel and is responsive):
After you fill the form and submit, the action class does it's job and returns a "success" or "error". You then map this in the struts.xml, where you should do this -
<action name="the-form-action" class="com.example.action.MyActionClass">
<result name="success">/result-page.jsp?result=true</result>
<result name="error">/result-page.jsp?result=false</result>
</action>
In the result-page.jsp (which can be your initial form page also) add this code
//Tags and everything
<body>
<%
String result=request.getParameter("result");
if (result==null)
result="";
if (result.equalsIgnoreCase("true"))
{
%>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Success!</strong> Who's the boss?! You're the boss!!
</div>
<%
}
if (result.equalsIgnoreCase("false"))
{
%>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Oops!</strong> There seems to be an error! You may try the following :<br>
<ul>
<li>Fill the compulsory fields</li>
<li>Pray to god</li>
</ul>
</div>
<%
}
%>
//Rest of the body
</body>
Now the alert will only show if there's a success or failure.
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.