send array of data from POJO to JSP - arrays

I had a problem on printing array of data in JSP, heres what happend.
I created a POJO called: popArayCustOrd
public class popAryCustOrd {
public String prodkey,descrp,strgth,stkunt;
double rprice;
int quantity;
popAryCustOrd(String prodkey,String descrp,int quantity,Double rprice,String stkunt,String strgth){
this.prodkey = prodkey;
this.descrp = descrp;
this.quantity = quantity;
this.rprice = rprice;
this.stkunt = stkunt;
this.strgth = strgth;
}
public void setProdkey(String prodkey){
this.prodkey = prodkey;
}
public String getProdkey(){
return(this.prodkey);
}
public void setDescrp(String descrp){
this.descrp = descrp;
}
public String getDescrp(){
return(this.descrp);
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return(this.quantity);
}
public void setRprice(double rprice){
this.rprice = rprice;
}
public double getRprice(){
return(this.rprice);
}
public void setStkunt(String stkunt){
this.stkunt = stkunt;
}
public String getStkunt(){
return(this.stkunt);
}
public void setStrgth(String strgth){
this.strgth = strgth;
}
public String getStrgth(){
return(this.strgth);
}
}
and in my servlet file called seekprod.java I assigned data coming from the database within a method....
connx.rs.beforeFirst();
while(connx.rs.next()){
popAryCustOrd[] prodList = new popAryCustOrd[]{new popAryCustOrd(connx.rs.getString("prodkey"),connx.rs.getString("descrp"),connx.rs.getInt("quantity"),connx.rs.getDouble("retailp"),connx.rs.getString("stkunit"),connx.rs.getString("strength"))};
request.setAttribute("prodList", prodList);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("preOrdFrm.jsp? inKey="+this.inKey+"&transkey=drugs");
dispatcher.forward(request, response);
.......
and my JSP to access the data is.....
<c:forEach items="${prodList}" var="paramx" >
<tr>
<td>${paramx.prodkey}</td>
<td style="text-align: center; word-wrap: break-word; word-break:break-all; text-overflow: ellipsis;overflow:hidden;white-space: normal; white-space: -webkit-pre-wrap;">${paramx.descrp}</td>
<td>${paramx.stkunt}</td>
<td>${paramx.strgth}</td>
<td>${paramx.rprice}</td>
<td>${paramx.quantity}</td>
<td><input type="hidden" name="agentId" value="<%=uID %>">
<input type="hidden" name="pcode" value=${paramx.prodkey}>
<input type="hidden" name="inKey" value=${param.inKey}>
<input type="hidden" name="transKey" value="sveOrd">
<input style="font-size:50px; height:55px; width:100px" type="number" name="desqty" min="1" required="" value="1"/></td>
<td><input style="font-size:20px; height:55px; width:100px" type="submit" name="transact" value="Save"/></td>
</tr>
</c:forEach>
eventually it works but I got only one result instead of three records from the database table, my syntax in sql is correct and i checked it many times and compared with the result. I dont know where part of my code to fix. Im very much glad if you could help me .?

while(connx.rs.next()){
popAryCustOrd[] prodList = new popAryCustOrd[]{new
popAryCustOrd(connx.rs.getString("prodkey"),connx.rs.getString("descrp"),connx.rs.getInt("quantity"),connx.rs.getDouble("retailp"),connx.rs.getString("stkunit"),connx.rs.getString("strength"))};
request.setAttribute("prodList", prodList);
}
think about this code it sets and then resets prodList attribute in the request object with every loop execution, so your jsp will recieve only the last value set to prodList.
It would be better to initialize an ArrayList outside the loop and add values to it and then after the loop use that list to set the attribute prodList in request object.

Related

Count Of Hidden Rows in WebTable By Using Selenium

I have a hide button in the application that hides duplicate data entries on web table. I have been trying to capture the number of hidden rows. See html and my approaches below. Every attempt I have tried ended up with 0. However, the result should be 2.
HTML CODE:
<tbody>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="even">...<tr/>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="even">...<tr/>
<tr role = "row" class="odd">...<tr/>
<tr role = "row" class="odd duplicate" style="display: none;" >...<tr/>
<tr role = "row" class="even duplicate" style="display: none;" >...<tr/>
</tbody>
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.cssSelector("[display=none]"));
int rowSize = rows_table.size();
return rowSize;
}
Here is my other attempt:
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.tagName("tr[not(contains(#style,'display: none;'))]"));
int rowSize = rows_table.size();
return rowSize;
}
If I ran the xpath as //*[#id='DataTables_Table_0']/tbody/tr[not(contains(#style,'display: none;'))] , I can find the hidden rows on the browser.
I have also tried this:
def getInvisibleTableRowCount()
{
WebDriver driver = DriverFactory.getWebDriver()
WebElement table = driver.findElement(By.xpath("//*[#id='DataTables_Table_0']/tbody"))
List<WebElement> rows_table= table.findElements(By.tagName("tr"));
int rowSize = rows_table.size();
for(WebElement row: rows_table)
{
if(row.isDisplayed()==false)
{
rowSize = rowSize -1;
}
}
return rowSize;
}
After #Hac's comment, I tried JQuery. I ran the jQuery on browser, it works with no problem. But I get a "NULL" value returned in my function. I double checked the jQuery string that prompts correct in the comment line.
#Keyword
def getTableRowCountAfterHiding()
{
def jQuery='$'+'("#DataTables_Table_0 tbody tr:visible").length'
WebUI.comment(jQuery);
def visibleRowCounts = new utils.ExecuteJavaScript().executeJavaScript(jQuery);
return visibleRowCounts;
}
I defined utils to run JS as it is in below:
public class ExecuteJavaScript {
//This keyword is designed to execute JS.
#Keyword
def executeJavaScript(String javascript) {
((JavascriptExecutor) DriverFactory.getWebDriver()).executeScript(javascript)
}
}
This worked:
def getTableRowCountAfterHiding()
{
WebDriver driver = DriverFactory.getWebDriver()
List<WebElement> table = driver.findElements(By.xpath("//*[#id='DataTables_Table_0']/tbody/tr[not(contains(#style,'display: none;'))]"))
int rowSize = table.size();
return rowSize;
}

SpringBoot : RestAPI display the unique record

Table :
this is table name
Requirement :
Using RestAPI call populate unique cateID, categoryName , but I am getting the whole record.
Table
Table Data which I am using
Code Description :
Repository :
#Repository
public interface CategoryRepository extends JpaRepository<xCategory,Integer>
{
// #Query("SELECT DISTINCT a.catID,a.categoryName FROM ccCategory a order by categoryName asc")
#Query("SELECT DISTINCT a.catID, a.categoryName FROM xCategory a order by categoryName asc")
List<ccCategory> getCategoryName();
}
Rest Controller:
#RestController
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
public class HomeResource {
private final Logger log = LoggerFactory.getLogger(HomeResource.class);
#Autowired
CategoryRepository categoryRepository;
#GetMapping("/getAllCategory")
public List<ccCategory> getAllCategory() {
// public List<String> getAllCategory() {
System.out.println("***** Call : API getAllCategory() ******");
List<ccCategory> cCategory = categoryRepository.findAll();
return cCategory;
}
Angular Code :
<label class="control-label">Category: </label>
<select [(ngModel)]="listAllCategory" name="xxcategory" class="form-control" required>
<option *ngFor="let xxcategory of listAllCategory" [value]="xxcategory.catID">
{{xxcategory.categoryName}}
</option>
</select>
Problem :
Drop Down populating all the table value but I want only the UNIQUE value like only one time catID , categoryName.
You have to add a variable to keep the selected element in your select and then change your [(ngModel)]="listAllCategory" with [(ngModel)]="selectedCategory"

Post form data with nested entity using angularjs and spring boot web api

I'm building app using angularjs and spring boot framework.
I post a normal form to rest web api, and it works. But i don't know how to post a form data with nested entity (like foreign key in another table).
What I tried is:
JS:
vm.product = {
id: '',
name: '',
price: '',
detail: '',
brand:{
brand_id: ''
},
subcategory:{
subcategory_id: ''
}
}
vm.submitForm = function () {
$http.post("http://localhost:8080/api/products/", vm.product)
.then(
function (response) {
deferred.resolve(response.data);
},
function (errResponse) {
console.error('Error while creating Product: ' + errResponse.data.errorMessage);
deferred.reject(errResponse);
}
);
}
Form
<form class="forms-sample" ng-submit="products.submitForm()">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" ng-model="products.product.name"
placeholder="Name">
</div>
<div class="form-group">
<label for="exampleInputPassword4">Price</label>
<input type="number" class="form-control" id="exampleInputPassword4" ng-model="products.product.price"
placeholder="Price">
</div>
<div class="form-group">
<label for="exampleTextarea1">Detail</label>
<textarea class="form-control" id="exampleTextarea1" rows="2" ng-model="products.product.detail"></textarea>
</div>
<div class="form-group">
<label for="exampleTextarea1">Brand Id</label>
<select ng-model="products.product.brand.brand_id" class="form-control" id="exampleFormControlSelect2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label for="exampleTextarea1">Subcategory Id</label>
<select ng-model="products.product.subcategory.subcategory_id" class="form-control" id="exampleFormControlSelect2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<button type="submit" class="btn btn-success mr-2">Submit</button>
<button class="btn btn-light">Cancel</button>
</form>
Entity:
#Entity
#Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
//----------------------------------------------------------------------
// ENTITY PRIMARY KEY
//----------------------------------------------------------------------
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//----------------------------------------------------------------------
// ENTITY DATA FIELDS
//----------------------------------------------------------------------
#Column(name = "detail", length = 2147483647)
private String detail;
private String name;
#Column(name = "price", nullable = false)
private Double price;
// Attribute "brandId" is a link
// Attribute "subcategoryId" is a link
//----------------------------------------------------------------------
// ENTITY LINKS ( RELATIONSHIP )
//----------------------------------------------------------------------
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "subcategory_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonBackReference(value = "subcategory _id")
private Subcategory subcategory;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "brand_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonBackReference(value = "brand _id")
private Brand brand;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
#JsonManagedReference(value = "product _id")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private List<Review> listOfReview;
// getters and setters
//----------------------------------------------------------------------
// toString METHOD
//----------------------------------------------------------------------
#Override
public String toString() {
return "Product{" +
"id=" + id +
", detail='" + detail + '\'' +
", image1='" + image1 + '\'' +
", image2='" + image2 + '\'' +
", image3='" + image3 + '\'' +
", name='" + name + '\'' +
", price=" + price +
", subcategory=" + subcategory +
", brand=" + brand +
'}';
}
}
WEBAPI
#CrossOrigin
#PostMapping("/api/products")
public Product createProduct(#RequestBody Product product) {
System.out.println("Product: " + product);
System.out.println("Subcategory: " + product.getSubcategory());
Product product1 = productRepository.save(product);
return product1;
}
It seems that subcategory_id and brand_id can't be parsed.
In console, product is printed as following:
Product: Product{id=null, detail='asdg', image1='null', image2='null', image3='null', name='dfgfsg', price=3.0, subcategory=null|null, brand=null|null}
So how can I post a form with foreign key like this app? I search a lot but can't find solution.
Thanks
It seems that you are trying to save Product and its children in one go.
You would need two additional things to achieve that:
1) Turn on PERSIST cascading:
#ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.PERSIST)
...
private SubCategory subcategory;
2) If the Subcategory has a #OneToMany association to Product, then you would need to set both sides of relationship:
public Product createProduct(#RequestBody Product product) {
Subcategory subCat: product.product.getSubcategory();
subCat.getProducts().add(product);
Product product1 = productRepository.save(product);
return product1;
}
You dont need that of course if its only mapped in Product solely.

Rename a file (file upload in servlet)

I'm trying to rename a file after upload but the error I get is:
File Upload Failed due to java.io.FileNotFoundException: C:\Users\Akhil\Documents\CryptographicSteganography\Image\toshaMon Dec 29 22:21:41 IST 2014.jpg (The filename, directory name, or volume label syntax is incorrect).
I went through almost all the possible related topics in stackoverflow as well as other sites but couldn't resolve this error.
my servlet class:
package FileUploadHandler;
import com.pointerunits.web.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Date date = new Date();
String name = null;
public String UPLOAD_DIRECTORY = "";
/**
* #see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//process only if its multipart content
String FileType = (String)request.getSession().getAttribute("FileType");
//System.out.println(FileType);
String usrnam = (String) request.getSession().getAttribute("name");
//System.out.println(usrnam);
switch (FileType) {
case "image":
//UPLOAD_DIRECTORY = "C:/Users/Akhil/Downloads/SpringMain/SpringMain/WebContent/WEB-INF/Uploads/Image";
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "audio":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "video":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
default:
System.out.println("invalid path");
break;
}
//UPLOAD_DIRECTORY = getServletContext().getRealPath(UPLOAD_DIRECTORY);
//System.out.println(UPLOAD_DIRECTORY);
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
// System.out.println(getName());
String nam = usrnam+date.toString();
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = item.getName();
//System.out.println(name);
File uploadedFile = new File(UPLOAD_DIRECTORY+File.separator+nam+name.substring(name.indexOf('.')));
item.write(uploadedFile);
//File uploadedFile = new File(UPLOAD_DIRECTORY, name);
// item.write( new File(UPLOAD_DIRECTORY + File.separator + nam + name));
// System.out.println("uploaded file : "+uploadedFile.toString());
// System.out.println(nam);
// String f1 = uploadedFile.getAbsolutePath();
// System.out.println(f1);
//
// File oldName = new File(f1);
// //File newName = new File(UPLOAD_DIRECTORY+File.separator+nam+"."+FilenameUtils.getExtension(oldName.toString()));
// File newName = new File(UPLOAD_DIRECTORY,nam+name.substring(name.indexOf('.')));
// File uploadedFile = new File ("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\IMAG0187.jpg");
// File newName = new File("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\toshaMon Dec 29 22:01:40 IST 2014.jpg");
// boolean flag = uploadedFile.renameTo(newName);
//
// System.out.println(newName.toString());
//
//// File uploadedFile = new File(UPLOAD_DIRECTORY , nam);
//// item.write(uploadedFile);
//
}
}
System.out.println();
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
below is the .jsp webpage:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload File</title>
</head>
<h1><%
String FileType = request.getParameter("select");
out.println("File Type is: "+FileType);
session.setAttribute("FileType", FileType);
%>
</h1>
<body>
<body>
File:
<%if (FileType.equalsIgnoreCase("image")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType")%>" accept="image/*"> <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("audio")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="audio/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("video")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="video/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
%>
</body>
</body>
</html>
Sorry about that awful lot of comments:
my program was going through a testing phase
May be there is right issue, it cannot access the folder as it does not have right.
If this is not the case then.
You should try to remove space from the file name format data value to a format that does not contains any space Sample Format Date . Because space can create problems.
Before item.write(uploadedFile); check
if(!uploadedFile.exists()){
uploadedFile.createNewFile();
}

displaytag, how to integrate checkboxes?

I use displaytag on a list bean: utilisateurBean. I need to add a column on this tab to add a checkbox for selecting an element.
Pb : With the displaytag struts looks for the property choixUtilisateur in the bean and not in the formBean. Is there a way to talk struts/displaytag to map this property in the form? I don't understand the mix of prestenation layer/ business layer that this involves.
I understand that I iterate on the bean and that he looks for the property in. But I did not understand the mapping of the decorator property in the business layer.
My code :
<html:form action="/rechercheUtilisateur"
name="formRechercheUtilisateur"
decorator="org.displaytag.render.DecorateurCheckbox"
type="lan.poujoulat.osac.forms.FormRechercheUtilisateur">
...
<div align="center"><display:table style="width: 100%;"
class="mars" sort="list"
name="formRechercheUtilisateur.listeUtilisateurs"
id="formRechercheUtilisateur.listeUtilisateurs"
decorator="org.displaytag.render.DecorateurCheckbox"
cellspacing="4" cellpadding="2" pagesize="10"
requestURI="rechercheUtilisateur.do" export="true" >
<display:column title="id" property="id" sortable="true"
style="color: black;" headerClass="sortable"></display:column>
...
<display:column media="html" property="choixUtilisateur" title=" "></display:column>
...
</display:table></div>
</html:form>
The DecorateurCheckbox.java to add checkbox to my tab:
public class DecorateurCheckbox extends TableDecorator{
...
public String getChoixUtilisateur()
{
String retour = "";
UtilisateurBean user= (UtilisateurBean) getCurrentRowObject();
int idUser ;
idUser = user.getId();
retour = "<input type='checkbox' name='formRechercheUtilisateur' property='choixUtilisateur' value='"+idUser+"' id='selectedArticle" + idUser + "' />";
return retour;
}
...
}
Error:
/Administration/acces.jsp. Exception : javax.servlet.ServletException:
Error looking up property "choixUtilisateur" in object type
"xxx.UtilisateurBean".
public class DecorateurCheckbox extends TableDecorator{
public String getChoixUtilisateur()
{
String retour = "";
UtilisateurBean user= (UtilisateurBean) getCurrentRowObject();
int idUser ;
idUser = user.getId();
retour = "<input type='checkbox' name='utilisateurModif' property='choixUtilisateur' value='"+idUser+"' id='" + idUser + "' />";
return retour;
}
}
utilisateurModif is the form property and choixUtilisateur is the displaytag property with the decorator :
jsp :
<display:column property="choixUtilisateur" title="modif"></display:column>

Resources