I have created a simple shopping cart project using spring framework. I've created a button add to cart so that when clicked it will create session of that item. I have following codes
<button href="/addcart/1">Add to button</button>
This is my controller
#RequestMapping("/addcart/{id}")
public ModelAndView goCart(#PathVariable("id")int id,HttpServletRequest request, HttpSession session) {
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(new CartItem(productService.findProductCart(id),1));
session.setAttribute("cart", cart);
ModelAndView model = new ModelAndView();
model.setViewName("cart");
return model;
}
this is my CartItem class
public class CartItem {
private List<Product> product;
private int quantity;
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public CartItem(List<Product> product, int quantity) {
super();
this.product = product;
this.quantity = quantity;
}
public CartItem() {
super();
}
}
this is my Product class
public class Product {
private int pid;
private String productName;
private int unitPrice;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
}
I've a productServiceImpl class of this productDaoImpl
#Override
public List<Product> findProductCart(int id) {
List<Product> cartProduct = new ArrayList<Product>();
String sql = "select * from product where pid= " + id;
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
cartProduct = jdbcTemplate.query(sql, new ProductRowMapper());
return cartProduct;
}
I've view in jsp with following code
<c:forEach var="item" items="${sessionScope.cart}">
<li>${item.quantity}</li>
<li>${item}</li>
</c:forEach>
this give
1
com.sparktronix.mvc.domain.CartItem#344e01
How to display session value productname and unitprice? Any suggestion are welcomed. Thanks in advance
You are almost there! You just have to get the product object from sessionScope and iterate once again like below.
<c:forEach var="item" items="${sessionScope.cart}">
<li>${item.quantity}</li>
<c:forEach items = "${item.product}" var="product">
<li>${product.productName}</li>
<li>${product.unitPrice}</li>
</c:forEach>
</c:forEach>
Hope this helps!
Related
i am practicing with spring boot for work with restful applications
I have set a #RestController and #Entity like this
#RestController
#RequestMapping(value = "/api")
public class RestControllerCar {
#Autowired
private CarRepository carRepository;
#RequestMapping(value = "/cars")
public Iterable<Car> getCars() {
return carRepository.findAll();
}
}
and
#Entity
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String brand, model, color, registerNumber;
private Integer year, price;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToMany(mappedBy = "cars")
private Set<Owner> owners;
public Car() {
}
public Car(String brand, String model, String color, String registerNumber, Integer year, Integer price) {
super();
this.brand = brand;
this.model = model;
this.color = color;
this.registerNumber = registerNumber;
this.year = year;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getRegisterNumber() {
return registerNumber;
}
public void setRegisterNumber(String registerNumber) {
this.registerNumber = registerNumber;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Set<Owner> getOwner() {
return owners;
}
public void setOwner(Set<Owner> owners) {
this.owners = owners;
}
when i use postman to http://localhost:8080/cardatabase/api/cars i get a list of Cars
but even if i go to http://localhost:8081/cardatabase/cars, with _embedded on the top
it`s normal?
Thanks!!!!
Is your repository annotated #RestRepository? The _embedded make me think to the kind of output given by a #RestRepository for an array.
#RestRepository auto create all endpoint. As #M.Deinum pointed out, with the data rest starter, if ou remove it , you only have your controller, and not the one generated by #RestRepository.
Two main choices here:
You dont annotate the Repository. Just an interface which implement JpaRepository<YourEntity, TypeOfYourID> and use your controllers
You use only the auto created controllers by #RestRepository.
Or, you can install swagger2 on your project, so, accessing the docs on your browser, you will see all available endpoints, and it may be more clear for you.
With swagger you will also see what is the return type of the endpoint, the parameters etc..
Swagger is really easy to install in a project and to use. (dependencies, one annotation and it's good.. for basic usage).
This little project follows a basic MVC pattern, i'm using spring boot and apache derby as an embedded data base.
1) When adding a hardcoded object list inside service class, they all share the same id. Is there an explanation for this behavior ?
This shows the problem (Don't mind the 'kkk' objects, i've solved that part already)
Screen1
So this is the object account i'm working with :
#Entity
public class Account {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String owner;
private double budget;
private double budgetInvest;
private double budgetFonction;
public Account() {
}
public Account(String owner, double budget, double budgetInvest, double budgetFonction
) {
this.owner=owner;
this.budget = budget;
this.budgetInvest = budgetInvest;
this.budgetFonction = budgetFonction;
}
public Account (String owner, double budget) {
this.owner = owner;
this.budget=budget;
}
public Account (String owner) {
this.owner=owner;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
public double getBudgetInvest() {
return budgetInvest;
}
public void setBudgetInvest(double budgetInvest) {
this.budgetInvest = budgetInvest;
}
public double getBudgetFonction() {
return budgetFonction;
}
public void setBudgetFonction(double budgetFonction) {
this.budgetFonction = budgetFonction;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
These are the lines responsible for displaying the objects inside the view :
<tr th:each="account : ${accounts}">
<td th:text="${account.id}">id</td>
<td><a href="#" th:text="${account.owner}">Title
...</a></td>
<td th:text="${account.budget}">Text ...</td>
</tr>
Here is the controller :
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.GET)
public String addAccount(Model model) {
model.addAttribute("account", new Account());
return "accountAdd";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.POST)
public String postAccount(#ModelAttribute Account account) {
accountService.addAccount(account);
return "redirect:listAccount";
}
#RequestMapping(value="/listAccount", method=RequestMethod.GET)
public String listAccount(Model model) {
System.out.println(accountService.getAllAccounts());
model.addAttribute("accounts",accountService.getAllAccounts());
return "listAccount";
}
}
And finally the service class :
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public List<Account> getAllAccounts(){
List<Account>accounts = new ArrayList<>(Arrays.asList(
new Account("Maths Department",1000000,400000,600000),
new Account("Physics Department",7000000,200000,500000),
new Account("Science Department",3000000,700000,1000000)
));
accountRepository.findAll().forEach(accounts::add);
return accounts;
}
public Account getAccount(long id) {
return accountRepository.findById(id).orElse(null);
}
public void addAccount(Account account) {
accountRepository.save(account);
}
public void updateAccount(long id, Account account) {
accountRepository.save(account);
}
public void deleteAccount(long id) {
accountRepository.deleteById(id);
}
}
Ok, so while i haven't yet found the exact answer as to why it affects the same id for every object in a static list.
I found an elegant workaround to not only solve the issue but also enhance the structure of the code.
Instead of doing whatever barbaric initialization I was trying to perform, It's way better to do this inside the main class :
#SpringBootApplication
public class PayfeeApplication {
#Autowired
private AccountRepository accountRepository;
public static void main(String[] args) {
SpringApplication.run(PayfeeApplication.class, args);
}
#Bean
InitializingBean sendDatabase() {
return () -> {
accountRepository.save(new Account("Maths Department",1000000,400000,600000));
accountRepository.save(new Account("Physics Department",7000000,200000,500000));
accountRepository.save(new Account("Science Department",3000000,700000,1000000));
};
}
}
Could someone help me as I show the result of an inner join query in a view in Spring.
How do I return all fields from all inner join tables and show in view?
Ex from Model Class:
#NotEmpty(message="Destino não pode estar vazio")
private Integer idDestinoAgendamento;
private Integer idMotoristaAgendamento;
private Integer idAutomovelAgendamento;
private Integer idRotaAgendamento;
#NotEmpty(message="Data não pode estar vazia")
private String dataSolicitacaoPacApp;
#NotEmpty(message="Hora não pode estar vazia")
private String horaSolicitacaoPacApp;
#NotEmpty(message="Status não pode estar vazio")
private String statusAgendamento;
private Destino destino;
private Motorista motorista;
private Automovel automovel;
Ex do DAO:
public List buscarTodosAgendamentos()
{
String sql = "SELECT * FROM bAgendamento AS agendamento INNER JOIN bsDestino AS destino"
+ " ON agendamento.idDestinoAgendamento = destino.idDestino INNER JOIN"
+ " bsMotorista AS motorista ON agendamento.idMotoristaAgendamento = motorista.idMotorista "
+ " INNER JOIN bsAutomovel AS automovel ON agendamento.idAutomovelAgendamento = "
+ " automovel.idAutomovel INNER JOIN bsRota AS rota ON agendamento.idRotaAgendamento ="
+ " rota.idRota ORDER BY agendamento.dataSolicitacaoPacAPP ASC "
List list =
namedParameterJdbcTemplate.query(sql,getSqlParameterByModel(null), new AgendamentoMapper());
return list;
}
View (return fields object Destino, Automovel...):
c:forEach items="${listAgendamento}" var="agendamento"
${agendamento.idAgendamento}
${agendamento.cpfPacienteSolicitacaoPacApp}
${agendamento.idDestinoAgendamento}
${agendamento.idMotoristaAgendamento}
${agendamento.idAutomovelAgendamento}
${agendamento.idRotaAgendamento}
${agendamento.dataSolicitacaoPacApp}
${agendamento.horaSolicitacaoPacApp}
${agendamento.statusAgendamento}
public class SiteJoinCategory {
private Category category;
private Site site;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Site getSite() {
return site;
}
public void setSite(Site site) {
this.site = site;
}
}
public class Site {
private Integer siteId;
private String siteName;
private Integer categoryId;
public Integer getSiteId() {
return siteId;
}
public void setSiteId(Integer siteId) {
this.siteId = siteId;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
public class Category {
private Integer categoryId;
private String categoryName;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}
#Component
public class SiteJoinCategoryDao {
#Resource
private JdbcTemplate jdbcTemplate;
public List findAll() {
String sql = "select site., cat. " +
"from t_site site inner join m_category cat " +
"ON site.category_id = cat.category_id";
RowMapper rowMapper = new SiteCategoryRowMapper();
List list = jdbcTemplate.query(sql, rowMapper);
return list;
}
/**
* RowMapper
*/
protected class SiteCategoryRowMapper implements RowMapper {
#Override
public SiteJoinCategory mapRow(ResultSet rs, int rowNum) throws SQLException {
SiteJoinCategory siteJoinCategory = new SiteJoinCategory();
Site site = new Site();
Category category = new Category();
site.setSiteId(rs.getInt("site.site_id"));
site.setSiteName(rs.getString("site.site_name"));
site.setCategoryId(rs.getInt("site.category_id"));
category.setCategoryId(rs.getInt("cat.category_id"));
category.setCategoryName(rs.getString("cat.category_name"));
siteJoinCategory.setSite(site);
siteJoinCategory.setCategory(category);
return siteJoinCategory;
}
}
}
View (exemplo:
${siteJoinCategory.site.siteName}
${siteJoinCategory.category.categoryName}
no errors display in my view...but when it run it gives the value as '0'. my database table name is 'categories'.it has a value like 'category_l dummy' for the column .But in the view display as a 0...please help me to slove this...
This is my model class
#Entity
#Table(name = "categories")
public class CategoriesModel implements Serializable{
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO) //for autonumber
private int id;
#Column
private String category1;
#Column
private String desccategory1;
public CategoriesModel() {
}
public CategoriesModel(
int id,
String category1, String desccategory1) {
super();
this.id = id;
this.category1 = category1;
this.desccategory1 = desccategory1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory1() {
return category1;
}
public void setCategory1(String category1) {
this.category1 = category1;
}
public String getDesccategory1() {
return desccategory1;
}
public void setDesccategory1(String desccategory1) {
this.desccategory1 = desccategory1;
}
This is my Dao class
public interface CategoriesDao {
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
}
This is my Dao impl class
#Repository
public class CategoriesDaoImpl implements CategoriesDao {
#Autowired
private SessionFactory session;
#Override
public void add(CategoriesModel categories) {
session.getCurrentSession().save(categories);
//this "categories" is a table name
}
#Override
public void edit(CategoriesModel categories) {
session.getCurrentSession().update(categories);
//this "categories" is a table name
}
#Override
public void delete(int id) {
session.getCurrentSession().delete(getCategoriesModel(id));
//this "id" is a feild in Model
}
#Override
public CategoriesModel getCategoriesModel(int id) {
return (CategoriesModel) session.getCurrentSession().get(CategoriesModel.class, id);
}
#Override
public List getAllCategoriesModel() {
return session.getCurrentSession().createQuery("from CategoriesModel").list();
//this "CategoriesModel" is a its model name
}
This is my service class
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
This is my service impl class
#Service
public class CategoriesServiceImpl implements CategoriesService {
#Autowired
private CategoriesDao CategoriesDao;
#Transactional
public void add(CategoriesModel categories) {
CategoriesDao.add(categories);
}
#Transactional
public void edit(CategoriesModel categories) {
CategoriesDao.edit(categories);
}
#Transactional
public void delete(int id) {
CategoriesDao.delete(id);
}
#Transactional
public CategoriesModel getCategoriesModel(int id) {
return CategoriesDao.getCategoriesModel(id);
}
#Transactional
public List getAllCategoriesModel() {
return CategoriesDao.getAllCategoriesModel();
}
this is my controller class
#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Map<String, Object> map) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
map.put("category", categories);
//new created object is assign and view name
map.put("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}
this is my view
<c:forEach items="${categoriesList}" var="category">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="category">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6 ">
<a href="" target="_self"><img src="images/properties/cars.png" class="img-responsive">
<div class="link">
<p>${category.category1}</p>
</div>
</div>
#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Model model) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
model.addAttribute("category", categories);
//new created object is assign and view name
model.addAttribute("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}
I am trying to access getter properties in a subclass with a TableView in JavaFX. I have the following class:
public class PersonType implements Serializable {
private static final long serialVersionUID = 1L;
Person person;
short count;
public PersonType() {
}
public PersonType(Person person, short count) {
super();
this.person = person;
this.count = count;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public short getCount() {
return count;
}
public void setCount(short count) {
this.count = count;
}
Person is like this:
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
String firstName;
String lastName;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Okay - lastly we have the following:
#FXML
private TableColumn tcFirstName;
#FXML
private TableColumn tcLastName;
#FXML
private TableView tblPersonTypes;
ArrayList<PersonType> pType = new ArrayList<PersonType>();
//Can assume that pType here has say 5 entries, the point of this
//is I'm trying to get to the firstName, lastName properties of the
//PersonType in the TableView below like the following:
tcFirstName.setCellValueFactory(new PropertyValueFactory<String,String>("firstName"));
tcLastName.setCellValueFactory(new PropertyValueFactory<String,String>("lastName"));
//Populate Table with Card Records
ObservableList<PersonType> data = FXCollections.observableArrayList(pType);
tblPersonTypes.setItems(data);
And I'm unsure how with a list of PersonTypes I can tell the table columns that I want the firstName and lastName properties of the Person object contained within. I know I could create a new object, and have the "count" from PersonTypes, then the other properties of "firstName", "lastName" etc without having an object property of Person. Any help would be greatly appreciated.
-- EDIT --
Another way I thought to do this was using CellFactories - where I would pass in to the CellValueFactories the Person object, then set the CellFactory to return a String value (firstName for the first name column, etc). And it would look like this:
tcFirstName.setCellValueFactory(new PropertyValueFactory<Person,String>("person"));
tcFirstName.setCellFactory(new Callback<TableColumn<Person,String>,TableCell<Person,String>>(){
#Override
public TableCell<Person,String> call(TableColumn<Person,String> param) {
TableCell<Person,String> cell = new TableCell<Person,String>(){
#Override
public void updateItem(String item, boolean empty) {
if(item!=null){
setGraphic(new Label(item.getFirstName()));
}
}
};
return cell;
}
});
Try this:
tcFirstName.setCellValueFactory(new Callback<CellDataFeatures<PersonType, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<PersonType, String> p) {
// p.getValue() returns the PersonType instance for a particular TableView row
if (p.getValue() != null && p.getValue().getPerson() != null) {
return new SimpleStringProperty(p.getValue().getPerson().getFirstName());
} else {
return new SimpleStringProperty("<No TC firstname>");
}
}
});
}