servlet is not called when condtion is met in jsp - java

I am performing add to cart in java script which should call servlet addtocart.jlc as shown below.
<%#page import = "java.util.*" %>
<html>
<body>
<center>
<h1>JLC book store</h1>
<h2>JLC book search</h2>
<font color = "green" size = '6'> ${ADDED}</font>
</center>
<br/>
<%Object obj = request.getAttribute("MSG");
if(obj != null) { // if condtion
%>
<br/> <center>
<font color = "red" size = "6">
<%=obj%>
</font>
<br/><a href = "index.jsp">
<h2> GO TO SEARCH PAGE1 </h2></a>
</center>
<%} else { // if condition end and else condition open
obj = session.getAttribute("BOOKS");
ArrayList<String> blist = (ArrayList<String>)obj;
for(String bnm:blist) {
%>
<form action="addtocart.jlc" method="post">
<input type = "hidden" name = "bname"
value = "<%=bnm%>" />
<font size = '5'> <%=bnm%> <input type = "submit"
value = "ADD TO CART" />
</font>
</form>
<% } %>
<form action = "showcart.jlc">
<input type = "submit" value = "SHOW CART" />
</form>
<% } %>
</body>
</html>
when I ran above program I am getting output as shown below which is in if condition. I am not getting what is error. I am new to jsp and this is print out given by my lecture. I am working on but not able to get what is bug. I am using eclipse EE and tom cat server.
JLC book store
JLC book search
No books found with categorynull
GO TO SEARCH PAGE1

From your output I can see that at some point during this request, "No books found with categorynull" has been set to the "MSG" attribute of your request. Try to follow back before the request reaches this file.
I don't know what the .jlc extension is but from the looks of it this is a .jsp file, so your request might have gone through a HttpServlet before reaching this point where
request.setAttribute("MSG", "No books found with categorynull");
was called.
Also the error message suggests that this request was required to be called with a ?category=xxx query, and the same servlet was supposed to get the list of books for that category and call
request.setAttribute("BOOKS", ...);
If I were you I would perform a text search in the entire source code for the string .setAttribute("BOOKS"

Related

How to send dropdown value to servlet NOT the option text

I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone

Cannot find any information on property [bankOffer] in a bean of type [game.Game]

Currently getting an error that the bankOffer property in my bean cannot be found..
It is from my game.jsp file shown below:
<%#page import="game.Briefcase"%>
<jsp:useBean id="game" class="game.Game" scope="session" />
<%
// If the 'open' parameter is received, it is converted to
// an integer and passed to the method setOpen. The value given
// is the corresponding index for the ArrayList Object.
if (request.getParameter("open") != null) {
game.caseOpen(Integer.parseInt(request.getParameter("open")));
}
// If the 'restart' parameter is given, then the restart method
// is invoked on the game bean.
if (request.getParameter("restart") != null) {
game.newgame();
}
// If the deal parameter is given, then it converts it to a Boolean
// value and performs a conditional test. If the parameter is true,
// then the deal has been made so the page is forwarded to the deal.jsp.
// Otherwise, the gameRound() is incremented cause it is NO DEAL!.
if (request.getParameter("deal") != null) {
if (Boolean.parseBoolean(request.getParameter("deal"))) {
game.setDeal(true);
} else {
game.nextround();
}
}
// If there is a Bank Offer, it will display the amount offered with
// two buttons to either accept or refuse.
if (!game.getDeal()) {
if (game.offerTime()) {%>
<div id="bank_offer">
<div id="bank_offer_title"></div>
<div id="deal_button" onclick="deal(true)"></div>
<div id="bank_offer_text">
<div id="bank_offer_amount">$<jsp:getProperty name="game" property="bankOffer" /></div>
<div id="bank_offer_message">Highest amount left: $<jsp:getProperty name="game" property="highestAmount" /></div>
</div>
<div id="nodeal_button" onclick="deal(false)"></div>
</div>
<%
// Otherwise, the Briefcases will be displayed along with a game message
// above the cases.
} else {
%>
<div id="game_message">
<div id="game_round">
<% if (game.getRound() > 0) { %>
Round: <jsp:getProperty name="game" property="round" />
<% } %>
</div>
<div id="game_text">
<jsp:getProperty name="game" property="message" />
</div>
</div>
<div id="cases">
<%
int index = 0;
// Iterates For Each Briefcase
for (Briefcase briefcase : game.getcases()) {
// If the Briefcase is not opened, then it is displayed as closed with the
// number assigned. Otherwise, if the Briefcase is opened then it is displayed
// as open with the amount value inside.
if (!briefcase.isOpened()) {
// If the Briefcase is the chosen case, then it will be displayed with
// 'Your Briefcase' on the image. The Briefcase's once pressed invokes
// a JavaScript function called openBriefcase() which passes the
// index. The function then invokes an Ajax call to the same .jsp which the
// html is then placed into the game container on the main index.jsp.
%>
<div onclick="openBriefcase(<%=index%>)" class="<%=(((game.getChosen() != null)
&& game.getChosen().equals(briefcase)) ? "briefcase_chosen" : "briefcase_closed")%>">
<div class="briefcase_number"><%=briefcase.getNumber()%></div></div>
<%} else {
// Once the case is opened it gets displayed with an open background
// with the case amount centered.
%>
<div class="briefcase_open">
<div class="briefcase_amount">$<%=briefcase.getValue()%></div>
</div>
<%}
index++;
}%>
</div>
<%
}
} else { %>
<div id="deal_message">
Deal $<jsp:getProperty name="game" property="bankOffer" />
</div>
<%
}
%>
Hmu to link any other files required. The previous file is index jsp, that loads fine with my other dynamic content, but it isnt loading game.jsp.
Help would be greatly appreciated, this is the first time I've had to use jsp in any extensive way so I'm at a loss right now..
Make sure that the class game.Game has a bean property (not just a field) named bankOffer. A java bean property is defined by its getters and setters, so for bankOffer to be a property, the class game.Game must include the public methods getBankOffer (or isBankOffer if a boolean property) and setBankOffer.

jsp web application - each time button is clicked, increase number by 1

the application has a button and starts with the number 0, and each time the button is clicked on, the integer is increased by 1.
the problem is I have to incorporate it with this code and covert string "0" to integer 0
<%
int x = 0;
try { x = Integer.parseInt("0"); }
catch (Exception e) { x = 0; }
%>
also how would I continue to stay on the same page to click on the button to add one (do I put the code within the html?)
this is what I have so far:
<html>
<body>
<form method="post" action="index.jsp" />
<%
String integer = request.getParameter("0");
%>
<%
int x = 0;
try { x = Integer.parseInt("0"); }
catch (Exception e) { x = 0; }
%>
<input type="text" name="integer" value="<%=integer%>"/>
<input type="submit" value="submit" />
</form>
</body>
</html>
This is the code that would work for that situation.
<%! int clicks = 0; %>
<%
String param = request.getParameter("integer");
try
{
int i = Integer.parseInt(param);
clicks ++;
}
catch (NumberFormatException e)
{
}
%>
<p>Number of clicks untill now: <%= clicks %> </p>
<form action="">
<input type="text" name="integer" value="1"/>
<input type="submit" value="submit" />
</form>
You had some mistakes:
You are not using a form tag
You name your parameter "integer" but you are trying to recover it using the name of "0"
Some guidelines for you:
If you want to increase the value without reloading the page you need javascript/ajax.
You shouldn't be adding scriptlets to your JSP pages. Insted you should code a Servlet which handles the click increase and uses a RequestDispatcher to send to a JSP page where you are showing it (and not doing any calculations).
EDIT: I should warn you that this code would show the click value for every user on the page. If you don't want that, you should remove de JSP declaration and work with the param request instead. From my code it should be easy for you.

Looping through a list of images in JSP and calling a servlet to display each one in a table, but the final output displays same image

I am working on an assignment in which I have to provide a user login after which he will be directed to a page where he can upload images and all of his previous + new images will be displayed below in a table. So the structure of my application is like this...
(trimmed most of the code for clarity)
JSP file that allows upload and displays the image
<p>Please select an image file to upload(Max file size 1 MB)</p>
<%
Integer userId = 0;
userId = (Integer) session.getAttribute("userId");
%>
<%
String errorMessage = (String) request.getAttribute("error");
if (errorMessage != null) {
out.print("<h4> " + errorMessage + "</h4>");
}
%>
<form action="imageupload" enctype="multipart/form-data" method="post">
<br /> <input type="file" name="uploader" id="uploader" /> <br /> <br />
<input type="submit" /> <input type="button"
value="clear" onClick="clear()" />
</form>
<br />
<h4>Uploaded Images</h4>
<br />
<table width="80%">
<tr>
<th>S No.</th>
<th>Name</th>
<th>size</th>
<th>Preview</th>
<th>Actions</th>
</tr>
<%
UserImagesDAOImplementation userImages = new UserImagesDAOImplementation();
List<Image> images = (List<Image>) userImages.getUserImages(userId);
for (Image image : images) {
%>
<tr>
<td><%=image.getSn()%></td>
<td><%=image.getImageName()%></td>
<td><%=image.getSize()%></td>
<td><% session.setAttribute("image",image.getImage() ); %><img src="toimage" height="100px" width="100px" /></td>
<td><img src="img/edit.png" /> <img src="img/url.png" /></td>
</tr>
<%
}
%>
</table>
<br />
Total space used: <%= (userImages.getSizeUsage(userId)/1024) %> KB / 10 MB
the "toimage" servlet that returns the image
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Byte[] image = (Byte[]) session.getAttribute("image");
int len = image.length;
byte[] imageData = new byte[len];
for(int i=0; i < len; i++) {
imageData[i] = image[i];
}
response.setContentType("image/jpg");
response.getOutputStream().write(imageData);
response.getOutputStream().flush();
response.getOutputStream().close();
}
My problem is that it displays the last image in the list in all the table rows and after uploading some other image it displays that new image in every row.
I am not very confident about my design for the site but this is the first time I am working with JSP. I decided to get the image list inside JSP as I will have to perform some more operations on it later on. I guess the problem is either in setting the session variable or the src servlet being called in the end. Whatever it is, can someone please explain the typical flow of events in this design.
Edit:
Putting a print statement inside the "toimage" servlet proves that it is being called just once. So how can I make the JSP loop to call the image src every time ??
You use a single session attribute to store every image. So, at the end of the loop, this session attribute contains the last one.
You shouldn't use the session at all. Instead, you should pass the ID or name or whatever identifies the image as a URL parameter:
<img src="toimage?imageId=<%= image.getId() %>" height="100px" width="100px" />
And the servlet should use this parameter to now which image it must oad and send to the browser.
Also, learn the JSTL and the EL. Scriptlets sould not be used.

Geocortext IMF framework Null reference exception

Still having issues with this problem. Please help if you can.
So I am trying to fix a piece of code using the Geocortex IMF framework. I get an error on line 40 which is basically pulling a null exception. It is a mix of java and html. For some reason I can't seem to find out why the error is pulling up a null. Even if I load the variable with data, it still stops at rs = activeLayer.getRecordset();
Here is the Address Form they fill out and submit
<%# page errorPage="imfError.jsp" %>
<%
/*
Program: afoAddressForm.jsp
Purpose: Displays a page to the user to input address values for a
USAddress type of geocoding query.
Usage: </>
History:
*/
String layerId = request.getParameter("layerid");
String scale = request.getParameter("scale");
if (layerId == null) {
throw new Exception("Missing layerid parameter.");
}
if (scale == null) {
throw new Exception("Missing scale parameter.");
}
%>
<jsp:include page="/imfCopyright.jsp"/>
<html>
<head>
<title></title>
<meta http-equiv="Content-Style-Type" content="text/css">
<link href="../../../imfStyle.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/javascript">
function doNothing() {
}
function submitForm() {
var strStreetName = document.frm.streetName.value;
if (strStreetName == "") {
alert("Please enter street name." );
document.frm.streetNumber.focus();
} else {
document.frm.action = "afoAddress.jsp?streetName="+strStreetName;
document.frm.submit();
}
}
</script>
</head>
<body bgcolor="#FFFFFF" alink="#ff0000" link="#ff0000" vlink="#ff0000">
<form name="frm" action="JavaScript:doNothing()" method="post">
<input type="hidden" name="layerid" value="<%= layerId %>">
<input type="hidden" name="scale" value="<%= scale %>">
<table width="95%" border="0" cellspacing="0" cellpadding="0">
<center>
<tr><td align="left" class="bb11">Zoom To Street<hr></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="left" valign="top" class="bn8">
Enter the street name where you wish to centre the map.
If matching streets are found, you will be shown a list
of matching street names for you to choose where to
zoom the map to.
</td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center" class="bb8">Street Name</td></tr>
<tr><td align="center" class="bb8"><input name="streetName" size="15" maxLength=40 value=""></td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center" ><input name="btn" type="button" value="Submit" onclick="JavaScript:submitForm()"></td></tr>
<tr><td height="10"></td></tr>
</center>
</table>
</form>
</body>
</html>
Here is what the address form submits to
<%# page import="com.moximedia.aims.*" %>
<%
/*
Program: imfGeocodeUSAddress.jsp
An Internet Mapping Framework (IMF) system script
Copyright 2002 Province of British Columbia - all rights reserved
Purpose: Displays a page of positions matching the address
input by the user for USAddress geocoding styles.
History: 20020610 Cates: original coding
20030724 Cates: send user selection to separate script for labelling.
20040525 Cates: changed frame reference top to parent
20050103 Cates: added type to stylesheet link.
*/
String layerId = request.getParameter("layerid");
String scale = request.getParameter("scale");
String StreetName = request.getParameter("streetName");
AimsMap map = (AimsMap) (session.getAttribute("map"));
AimsFeatureLayer activeLayer = (AimsFeatureLayer) map.getLayers().getLayer(layerId);
AimsRecordset rs = null;
AimsFilter streetFilter = new AimsFilter();
if (activeLayer != null && activeLayer.getFilter()!= null) {
streetFilter = (AimsFilter) activeLayer.getFilter();
}
String query_String="";
if (StreetName == null) {
return;
}else{
StreetName = StreetName.toUpperCase();
query_String = "upper(FENAME) = '" + StreetName +"'";
//query_String = "FENAME like '%" + StreetName +"%'";
streetFilter.setWhereExpression(query_String);
}
// do the query, and whatever we need to do with the data
rs = activeLayer.getRecordset();
rs.clear();
rs.clearFilter();
rs.setMaximumResults(100);
rs.setBufferSize(rs.getMaximumResults());
rs.setFilter(streetFilter);
rs.query();
int count = 0;
rs.moveFirst();
while(!rs.EOF()) {
count++;
rs.moveNext();
}
%>
<jsp:include page="/imfCopyright.jsp"/>
<html>
<head>
<title></title>
<meta http-equiv="Content-Style-Type" content="text/css">
<link href="imfStyle.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/javascript">
function submitForm() {
document.query.submit();
}
</script>
</head>
<body onload="submitForm();">
<form name="query" method="post" action="afoSelectDefaultFind.jsp">
<input type="hidden" name="layerid" value="<%= layerId%>" >
<input type="hidden" name="rec" value="1" >
<input type="hidden" name="total" value="<%=count%>" >
<input type="hidden" name="query_String" value="<%=query_String%>" >
</form>
</body>
</html>
The error is when you hit submit on the form the java.lang.NullPointerException error pops up and put it on line 40 which is rs = activeLayer.getRecordset();. Any help with this would be great.
Well, my guess is that activeLayer is null and then you are calling getRecordset() on a null object reference. Can you try to debug
map.getLayers().getLayer(layerId);
To make sure that it is returning something?
As Chris Thompson points out, the issue is almost certainly that the layer is null. Check that your AXL file has the right layers and layerIds. (Sorry, I know ArcIMS, but I'm not familiar with the Geocortex framework.)
Also, you should add code to check if activeLayer is null and throw a different exception than NullPointerException, since that will make the error that much more obvious to the next programmer that comes along. Interesting that the streetFilter isn't applied if activeLayer is null, so somebody thought about this at some point.

Categories

Resources