i am trying to fetch data from database in spring mvc, this is my code for fetching data
#Override
public List getOrderDetail(Integer shop_id) {
// TODO Auto-generated method stub
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT order_id,shop_id,delivery_address,total_amount FROM master_order WHERE shop_id =" + shop_id);
SQLQuery query1 = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT itm.image,itm.name,itm.brand,odr.quantity,itm.offerprice,(itm.offerprice*odr.quantity) AS Total,modr.cust_id FROM master_order modr\r\n"
+ "INNER JOIN tblorder odr ON modr.order_id = odr.order_id INNER JOIN item itm on odr.item_id = itm.item_id WHERE modr.shop_id ="+shop_id);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
List results1 = query1.list();
results.add(results1);
System.out.println(results);
return results;
}
above System.out.println(results); statement give following output
[{shop_id=1, delivery_address=1, abc, xyz, aaa, USA, order_id=6, total_amount=1800}, [{image=Screenshot (19).png, quantity=8, Total=800, name=DhruvRajkotiya, offerprice=100, brand=gsgsrgs, cust_id=2}, {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2}, {image=Screenshot (19).png, quantity=1, Total=100, name=ewq, offerprice=100, brand=gsgsrgs, cust_id=2}]]
i want print order_id as well as {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2} in jsp page
this is my controller code
#RequestMapping(value = "/notifications", method = RequestMethod.GET)
public String notifications(Model model, HttpServletRequest request) {
if (request.getSession().getAttribute("shopkeeper") == null) {
return "redirect:login";
} else {
Shopkeeper sp = (Shopkeeper) request.getSession().getAttribute("shopkeeper");
model.addAttribute("order", shopkeeperService_shopkeeper.getOrderDetail(sp.getSk_id()));
return "shopkeeper/notifications";
}
}
this is my jsp code
<div class="row">
<c:forEach items="${ order}" var="order">
<div class="col-lg-12">
<div class="card">
<div class="card-header" style="padding-bottom: 5px;">
<h6># ${order.shop_id }</h6>
</div>
<div class="card-body">
<div class="col-lg-2" style="float: left;">Image</div>
<div class="col-lg-2" style="float: left;">Product name</div>
<div class="col-lg-2" style="float: left;">Product brand
</div>
<div class="col-lg-1" style="float: left;">Quantity</div>
<div class="col-lg-1" style="float: left;">Unit Price</div>
<div class="col-lg-1" style="float: left;">Total</div>
<div class="col-lg-3" style="float: left;">Approve of
request</div>
</div>
<div class="card-body">
<div class="col-lg-6" style="float: left;">Delivery
Address</div>
<div class="col-lg-6" style="float: left;">Total Amount</div>
</div>
</div>
</div>
</c:forEach>
</div>
i want to print
my question concept is order_id,address,total_amount one time and multiple bought item that can be one or more
how i can print
The way to "send" some data to a JSP page is to set and pass a request (or session) attribute.
From a Servlet, which handles current request, in a doGet() or doPost() method (depending on the HTTP request method used), you can do:
request.setAttribute("attributeName", attributeObject);
request.getRequestDispatcher("<name_of_your_page>.jsp").forward(request, response);
where the attributeName is a string, which will be treated as a reference to the attributeObject on a JSP page.
Then on the JSP page, you can use JSTL library and Expression Language (see this tutorial regarding JSTL and this one regarding JSP & EL in general). To iterate over the list, which has been passed as a request attribute, use <c:forEach> tag from JSTL.
First of all you need to import the core JSTL tags by placing this line on the top of your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Another useful statement to put under the latter is:
<%# page isELIgnored="false" %>
which tells your web browser to evalue the expressions written in EL instead of including them in HTML body as a plain text.
Provided that you used the string "orders" to name the collection set as attribute, the <c:forEach> tag usage can look similarly as below. You'll probably want to structure it differently and the field names (like order.order_id) can be different in your case, but I think you can get the idea.
<c:forEach item="order" items="${requestScope.orders}">
<p>${order.order_id}</p>
<p>${order.delivery_address}</p>
...
</c:forEach>
You can save the list as a model attribute. For example you want to save the current user:
model.addAttribute("user",user);
and access this attribute in your jsp file inside a div maybe :
<div> ${user.name} </div>
The controller method could look like this:
#RequestMapping( value = "/user", method = RequestMethod.GET )
public String displayUser(final Model model)
{
final User user = userService.findUserById(1); // here you'll provide custom implementation
model.addAttribute("user",user);
return "somejsppage.jsp";
}
If you want to add a List to your model:
final List<User> users = fillUserList(); // your implementation here
model.addAttribute("users",users);
You can access every element in that list via <c:forEach> tag:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<table>
<tr>
<th>First Name</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.firstName}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
I'm trying to pass an arry into a new HashMap and then pass it into a jsp file. Problem is that it doesn't seem to be working. There is no output of my array on the jsp display. This is someof the code for the HashMap declaration.
Map<String, Object> params = new HashMap<String, Object>();
for (int x = 0; x < nl3.getLength(); x++){
Node currentItem3 = nl3.item(x);
String key3 = currentItem3.getAttributes().getNamedItem("name").getNodeValue();
if (requirement.equals(key3)) {
matchingID[x] = build;
params.put("message", matchingID[x]);}}
My jsp file looks like this
<%# include file="/include.jsp" %>
<bs:page>
<p>Please Input an Agent-Requirement</p>
<form method="get" action="/QueueStat.html">
Agent Requirement: <input type ="text" id='agentPram' name="requirement" value="${requirement}"/> <br/>
<input type="submit" value="Submit" />
List of Matching builds:
<c:forEach items="${mathcingId}" var="mathcingId">
<br><span class="mono mono-12px"><c:out value="${message}"/></span>
</c:forEach>
</jsp:attribute>
</bs:page>
Any ideas on what I'm doing wrong? I suspect that the prams.put might be incorrect. Or maybe the jsp file?
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"
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.
It is possible to bind a List of String (List) and display them in a jsp in a combo box like this:
<form:select path="countryId">
<form:option value="" label="Please Select"></form:option>
<form:options items="${countryList}" itemValue="countryId" itemLabel="countryName"/>
</form:select>
I want this list to display in <td> or <form:input> like fields, not in combo box.
I am binding String list in model as
Map referenceData = new HashMap();
referenceData.put("OutputsList", Outputs);
In JSP I use
<c:forEach var="OutputsList" items="${Outputs}">
${OutputsList}
</c:forEach>
But list is not printed. What could be the reason?
do it that way.
<c:forEach var="country" items="${countryList}">
<tr>
<td>${country.countryId}</td>
<td>${country.countryName}</td>
</tr>
</c:forEach>
and on the server side use ModelAndView object
List<Country> countryList;
ModelAndView mv = new ModelAndView("index");
mv.addObject("country",countryList);
There was a wrong approach while using it in a jsp. From the code in question just swap OutputsList
Map referenceData = new HashMap();
referenceData.put("OutputsList", Outputs);
In JSP I use
<c:forEach var="item" items="${OutputsList}">
${item}
</c:forEach>
It will work.