I have a very peculiar problem. I am developing a web application in Java and Spring MVC. I have a row that can be duplicated dynamically by the user on the press of a button. Each row has around 10 fields. I am binding these rows as list of objects in the backing bean and initializing this list as a lazy list in the bean. Now, it has been working fine till now but the user tried to enter 12 rows and on the 12th row, i.e., the 11th iteration(the iteration starting from 0), the 5th field becomes empty, although the user enters values and all the other fields retain their values. Since the binding happens with name, I have checked the name of the field, it is consistent with the rest of the fields in the same row and the rest of the rows. I am unable to debug and rectify the issue. This is affecting the code in production.
I can provide whatever code snippets are required.
Can somebody please help me with this. Thanks in advance.
EDIT: I tried executing the same code on a different server and it works fine there but still persists on the live server. And the problem seems to be only in the 11th iteration's 5th field. Could it be a problem with the server
Adding code:
JSP:
<c:forEach items="${addProposal.requirements}" var="req" varStatus="status">
<!--Rest of the fields-->
<form:input path="requirements[${status.index}].sampleSize" id="r_sample${status.index}" value="${addProposal.requirements[status.index].maximumFeasibility}" class="inptform2" style="width:65px;" size="10" onchange="functions();"/>
<!--Rest of the fields-->
<td width="57" align="left" valign="middle" id="btn-close" class="btn-remove">' +
'<a href="javascript:void(0)"><img src="images/btncross.png" width="18" height="17" border="0" />' +
'</a>
</td>
</c:forEach>
Javascript:
$(document).ready(function(){
//Add more dynamic rows
$("#addMore").click(function() {
var tr_temp=$("#requirement tr:first").clone();
//rest of the fields code
tr_temp.find("#r_sample0").each(function() {
$(this).attr({
'id': function(_, id) { return 'r_sample' + i},
'name': function(_, name) { return 'requirements[' + i + '].sampleSize'},
'value': ''
});
}).end();
tr_temp.find("td:last").remove();
tr_temp.append(btn_close);
tr_temp.appendTo("#requirement");
i++;
});
//To remove a dynamically added row
$("#btn-close").live('click',function(){
doNotDel=false;
count=0;
//To fetch the values of the Input Fields
$(this).parent().find("input").each(function(){
count++;
var value = $(this).val();
var id=$(this).attr('id');
if(id.indexOf("r_total")==-1){
//Skip the minutes and currency column
if(id.indexOf("minutes")==-1 && id.indexOf("currencyValF")==-1 && id.indexOf("currencyVal")==-1){
if(value!=""){
doNotDel=true;
return false; //breaks the .each loop
}
}
}
});
if(doNotDel==false){
$(this).parent().remove();
}
});
});
Bean:
private List<RequirementBean> requirements;
//in constructor
requirements = LazyList.decorate(
new ArrayList<RequirementBean>()
, new InstantiateFactory(RequirementBean.class));
Controller:
#RequestMapping(value="/addProposal", method=RequestMethod.POST)
public String addProposal(#ModelAttribute("addProposal") ProposalBean proposal, ModelMap model){
RequirementBean req;
List<RequirementBean> reqmtList;
System.out.println("Before empty rows");
reqmtList = proposal.getRequirements();
for(int i=0; i<reqmtList.size(); i++){
req = reqmtList.get(i);
if(req.getCountry()!=null){
System.out.println("sample size " + i + " :" + req.getSampleSize());
}
}
}
EDIT:
I tried changing the value of the 4th row in the same column, and now the code seems to work. I am still not able to understand what is the issue.
Hope this gives more clarity. Please help me.
Related
I am developing an application in struts 2 and hibernate 3.
I have 3 tables
Inspection
InspectionMission
Timeline
Inspection is associated with InspectionMission and InspectionMission is associated with Timeline.
Now I have following problem. I have written following query in HQL
public List getQuartewiseInspectionList(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query q = session.createQuery(
"select count(i.inspectionId) as tot_inspections,t.year,t.quarter" +
" From Inspection as i " +
" inner join i.inspectionMission as im inner join im.timeline as t" +
" GROUP by t.year,t.quarter");
return q.list();
}
I want to fetch result as following
result[0][tot_inspections] = "6"
result[0][year] = "2009";
result[0][quarter] = "Q2";
result[1][tot_inspections] = "3"
result[1][year] = "2009";
result[1][quarter] = "Q3";
and so on so that I can display it in jsp struts as follows:
In JSP I have written following code
<table border="1">
<s:iterator value="result" status="status">
<tr class="<s:if test="#status.even">even</s:if><s:else>odd</s:else>">
<td class="nowrap"><s:property value="tot_inspections" /></td>
<td class="nowrap"><s:property value="year" /></td>
<td class="nowrap"><s:property value="quarter" /></td>
</tr>
</s:iterator>
</table>
Can anyone here help me?
You have to use the "new map" syntax (Hibernate Reference paragraph 14.6)
select new map(count(i.inspectionId) as tot_inspections, t.year as year, t.quarter as quarter) from ...
The rest of the query is the same. This will return a list of maps, where the key is the alias of the "column".
Another solution would be to define a data object just for displaying those results and let Hibernate create instances of those on the fly. This class would just need a matching constructor.
Example class (getters and fields omitted)
public class InspectionCount() {
// fields
public InspectionCount(int count, int year, int quarter) {
// initialize instance
}
// getters
}
The query would then look
select new InspectionCount(count(i.inspectionId), t.year, t.quarter)
from Inspection as i
inner join i.inspectionMission as im inner join im.timeline as t
group by t.year,t.quarter
As a result you would get a List of InspectionCounts.
I'm trying to create a fileupload. My file input:
<input class="form-control" name="file" type="file" size="20" accept="application/pdf, image/jpeg, image/png, text/plain" multiple >
And this for-loop in the servlet iterate over the Parts to get their total size. It iterate over the selected files and a additional element with size 1 and content type null. This cause an errror.
for (Part part : request.getParts()) {
System.out.println("Dateigrösse: " + part.getSize());
uploadSize = uploadSize + part.getSize();
System.out.println("Dateityp: " + part.getContentType());
if(part.getContentType().equals("application/pdf") || part.getContentType().equals("text/plain") || part.getContentType().equals("image/jpeg") || part.getContentType().equals("image/png")) {
} else {
types = false;
}
}
First it worked, but know there's this null element. What should I do? Where does it comes from? I don't change anything. I'm using the code from oracle EE7 doc and a famous online article. I don't change anything before this for-loop.
Thank you in advance.
The getParts() returns all named Inputs too. So it returns me the choosen subject as a Part. Now i'm filtering for inputs named "file".
I am outputting data to an html table using a struts-tags iterator. It works for the most part but for a few rows, it duplicates the previous row instead of putting in the correct data. Very strange inconsistency.
Here is the html:
<s:iterator value="result">
<tr>
<td><s:property value="timestamp"/></td>
<td><s:property value="targetId"/></td>
<td><s:property value="sourceIp"/></td>
<td><s:property value="transactionType"/></td>
<td><s:property value="status"/></td>
</tr>
</s:iterator>
"result" is defined in the java controller:
private List<AuditData> result
and is populated by a hibernate query like so:
session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = buildQuery2(session);
result = criteria.list();
Here is an example output of the problem:
10/3/16 8:17:31 PM.000 hanogreg 10.10.10.10 Pwd Reset Success
10/3/16 8:17:31 PM.000 hanogreg 10.10.10.10 Pwd Reset Success
The second row is a duplicate of the first but the database shows the second entry should say "Pwd Change", not "Pwd Reset".
Does anyone have any ideas as to what could be causing this inconsistent behavior?
Edit: This is a hibernate issue, not a struts issue as I can see "result" already contains the duplicate row instead of the real row. Here is buildQuery2() which creates the hibernate criteria:
private Criteria buildQuery2(Session session) throws ParseException {
Criteria criteria = session.createCriteria(AuditData.class);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
if (!fromDate.equals("All")) {
Date fDate = df.parse(fromDate);
criteria.add(Restrictions.ge("timestamp", fDate));
}
if (!toDate.equals("All")) {
Date tDate = df.parse(toDate);
actionlogger.debug("toDate=" +toDate +", tDate="+tDate.toString());
tDate = getEndOfDayDate(tDate); //set the time to the last millisecond of the day so all other times will be less
criteria.add(Restrictions.le("timestamp", tDate));
}
if (!csgUsername.equals("All")) criteria.add(Restrictions.eq("target_id",csgUsername));
if (!sourceIp.equals("All")) criteria.add(Restrictions.eq("source_ip",sourceIp));
if (!transactionType.equals("All")) criteria.add(Restrictions.eq("transaction_type",transactionType));
if (!status.equals("All")) criteria.add(Restrictions.eq("status",status));
criteria.addOrder(Order.asc("timestamp"));
return criteria;
}
Since I was unable to figure out why this was happening, I was forced to re-write the code to do the same thing without hibernate and got it to work correctly.
Okay so I have two Java Servlets, one for letting the user select which images to delete (DeleteImages) and another for actually deleting the images (HandleDelete). DeleteImages displays all the images in the container with a checkbox HTML form for the user to select which images to delete. Then, using POST the servlet passes that information along to HandleDelete which iterates over which images it received and deletes them.
I actually had this working, but then I tried to change the structure of the code (have DeleteImages forward to a .jsp file that output the HTML form which would then forward to HandleDelete) but that didn't work out, so I'm trying to go back to the old way and now it's not working even though I'm pretty sure it's the same as I had before.
From DeleteImages:
// retrieve image files
List<? extends SwiftObject> objs = os.objectStorage().objects().list("imageFiles");
out.println("<!DOCTYPE html><html><head><title>Object Storage - Delete</title><link rel='stylesheet' href='stylesheet.css' type='text/css' /></head>"
+ "<body>
<h1>Select images to Delete from container</h1>
<form method='POST' enctype='multipart/form-data' action='/ImageUpload/OSHandleDelete'>");
for (SwiftObject o : objs) {
// omitted code that gets the image's name, date last modified, and filepath (all Strings, I know this works)
out.println("<b>Name:</b> " + name + "<br/> <b>Time of Upload:</b> " + date + "<br/>"
+ "<input type='checkbox' name='"+name+"'> "
+ "<img src='"+filepath+"' alt='' style='max-width:800px;' /> <br/> <br/> <br/> ");
}
out.println("<input type='submit' value='Delete Images' /></form>");
out.println("</form> <br/> <br/> <div><br/><a class='return' href='index.jsp'><b>Click here to return home</b></a><br/><br/></div> <br/> <br/></body></html>");
From HandleDelete:
Enumeration<String> parameterNames = request.getParameterNames();
if (!parameterNames.hasMoreElements())
System.out.println("no parameters (null)");
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
System.out.println("*****************");
System.out.println("parameter: " + paramName);
String[] vals = request.getParameterValues(paramName);
if (vals == null)
System.out.println(" vals is null for " + paramName);
else {
for (int i = 0; i < vals.length; i++) {
System.out.println(" vals["+i+"]: " + vals[i]);
}
}
Right now I don't have HandleDelete actually doing anything besides print statements. This is because I use request.getParameter("<name>") to find out whether the user checked image of <name> (i.e. if it's null it was not checked but if it's not null it was checked).
The HTML form displays perfectly with the images and everything. My problem is that no matter what's checked in the HTML form, HandleDelete always prints to the console no parameters (null) meaning nothing was passed from DeleteImages to HandleDelete. I have a feeling the problem comes from either (1) the setAttribute statement in DeleteImages or (2) something with the HTML form. I've done a lot of searching and I'm pretty confident what I have is right though and I really can't figure out what's causing this issue (especially since I'm pretty sure this is exactly what I had before and it worked). Does anyone have any ideas?
I found the error: I included enctype=multipart/form-data
Not exactly sure why that caused the error but I removed that part and now it's passing the parameters perfectly. Thanks for your help guys!
I am developing a small application using spring mvc where I need to have option to delete each item from cart (in case customer feels he donot need after adding to cart).
I have got a "delete" button below each item item.(The items added are in a list).My pupose is when I click delete button against a particular item only that item should be removed from the cart.
I have written some code but it is remove lastest added items from cart and not required one.
I know my mistake but not able to proceed further.Here is what I implemented.
This is jsp :
<c:forEach items="${cart}" var="nextMovie">
<li>
<h2>${nextMovie.title}</h2>
</li>
<h2>Price</h2>
<h2>${nextMovie.price}</h2>
<c:set var="totalPrice" value="${0}" />
<c:forEach var="nextMovie" items="${cart}">
<c:set var="totalPrice" value="${totalPrice + nextMovie.price}"/>
</c:forEach>
<form method='post' action='<c:url value="removeFromCart.do"/>'>
<input type='image' src='Delete.png'/>
<input type='hidden' name='id' value='${nextMovie.id}'/>
</form>
</c:forEach>
This is my controller:
#RequestMapping("/removeFromCart")
public ModelAndView removeFromCart(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
}
List<Movie> allMovies = cart.getAllItems();
for(int i= 0;i<allMovies.size();i++)
{
allMovies.remove(i);
}
return new ModelAndView("/cartContents.jsp", "cart", allMovies);
}
Please suggest me how I will be able to delete the element again the delete button from the list.
Thanks
Maruthi
[HttpPost]
[Route("~/CartDetail/DeleteCartDetail")]
public ActionResult DeleteCartDetail(CartDetailModel model)
{
var response = _cartDetailService.DeleteCartItem(model.Id);
return Json(new
{
success = response.Success,
message = response.Message
});
}
}
I am importing my data from service DeleteCartItem
Here is service code
public BaseResponse DeleteCartItem(int cartDetailId)
{
var response = new BaseResponse();
try
{
var itemCart = _context.CartDetails.FirstOrDefault(x => x.Id == cartDetailId);
if (itemCart == null)
{
response.Message = "This item does not exist in the cart.";
return response;
}
_context.CartDetails.Remove(itemCart);
_context.SaveChanges();
response.Success = true;
}
catch (Exception exception)
{
response.Message = "Some error occured : " + exception.ToString();
}
return response;
}
Your JSP has nested <c:forEach> tags, with both containing the same items expression. Either you don't need 2 of them of else you need to close the first one before starting the second.
Your application has some problems:
First, your problem is because you are using the same var attribute name, for your both foreach tags. The first tag defines an attribute named nextMovie in its scope, the second foreach which is nested within first, defines the same attribute name, and then iterates, so when its iteration completes, nextMovie will be last element in the list, so ${nextMovie.id} will be last element's id.
Second,
List<Movie> allMovies = cart.getAllItems();
for (int i= 0;i<allMovies.size();i++) {
allMovies.remove(i);
}
is equivalent of allMovies.clear(), isn't it? So you are removing all items form list, what else do you need?
Third, next problem is you have an object of type ShoppingCart in your session which is named cart, and you add an object of type List<Movie> to your model with the same name; although when EL processor tries to resolve a name request has a more priority than session, but believe me it is much better to rename one.
Forth, why are you calculating 'totalPrice' in each iteration? And what is its use?