I have the following code
<%
String projectId = request.getParameter("projectId");
%>
<iframe width="100%" id="uploadFrame"
src="testframe.jsp?projectId=<%=projectId %>"></iframe></body>
</html>
and in testframe.jsp I am setting session value as
<%
String projectId = request.getParameter("projectId");
request.getSession(true).setAttribute("prj",projectId);
%>
and finally in servlet, I am getting session value in doGet method as
String prjId = request.getSession(false).getAttribute("prj").toString();
Problem I am facing is sometimes session value is null in doGet method, not all the time, although request.getParameter("projectId") is not null in testframe.jsp
What could be the reason for this?
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.
In my Liferay portlet view.jsp page I have int i =0; (I know that it is not good to have java code in jsp pages but I have to) now I need to increase it whenever the page is refreshed. I added <META HTTP-EQUIV="refresh" CONTENT="4"> to refresh the page.
Try this code :
<%! int i =1; %>
<%
System.out.println(i++);
%>
But as you yourself said it is not recommended to use java code in .jsp pages.
Maybe it could be an option to store this variable in portlet session scope and increment on page request.
U have to intialize count in session object for that u have to
set it in session object using setattribute function before this page
and in the page where u want to check it use the following code
<%
HttpSession session = request.getSession(false);
if(session!=null){
Integer Count=
(Integer)session.getAttribute("Count");
if( Count==null || Count== 0 ){
/* First visit */
out.println("Welcome to my website!");
Count=count+ 1;
}else{
Count=count+ 1;
out.println("Welcome back again for the "+Count+"Time");
}
session.setAttribute("Count", Count);
%>
Try to make the variable static
<% static int i = 0; %>
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
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 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.