Above is what I am trying to create
Hi,
Above is what I am trying to create using spring boot. My question is how do I properly iterate through a forEach loop and pull out the necessary data needed in JSP?
I thought I was doing it correctly but, I keep on getting an error saying
"Don't know how to iterate over supplied "items" in <forEach>"
Please see my code below for what I am currently doing.
Thanks for your help in advance!!!
Controller
#RequestMapping(value = "/showOrders.html")
public String listOrders(Model model) {
ArrayList<Order> orders = os.findAll();
model.addAttribute("allOrders", orders);
return "allOrders";
}
Service class for "Orders"
package com.sales.services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sales.models.Order;
import com.sales.repositories.OrderRepository;
#Service
public class OrderService {
#Autowired
OrderRepository or;
public ArrayList<Order> findAll() {
return (ArrayList<Order>) or.findAll();
}
}
Repository class for orders
package com.sales.repositories;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.sales.models.Customer;
import com.sales.models.Order;
#Repository
public interface OrderRepository extends CrudRepository<Order, Long> {
}
Order class
package com.sales.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name="ORDERS")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="OID")
private Long oId;
#Min(1)
#Column(name="QTY")
private int qty;
#Column(name="ORDDATE")
private String orderDate;
#ManyToOne
#JoinColumn(name="cId")
private Customer cust;
#ManyToOne
#JoinColumn(name="pId")
private Product prod;
public Long getoId() {
return oId;
}
public void setoId(Long oId) {
this.oId = oId;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Customer getCust() {
return cust;
}
public void setCust(Customer cust) {
this.cust = cust;
}
public Product getProd() {
return prod;
}
public void setProd(Product prod) {
this.prod = prod;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
}
Customer class
package com.sales.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
#Entity
#Table(name="CUSTOMERS")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="CID")
private Long cId;
#Column(name="CNAME")
#NotBlank
private String cName;
#OneToMany(mappedBy="cust")
private List<Order> orders = new ArrayList<Order>();
public Long getcId() {
return cId;
}
public void setcId(Long cId) {
this.cId = cId;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
````````````````````````````````````````````````````````````````````````````````
Product Class
````````````````````````````````````````````````````````````````````````````````
package com.sales.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotBlank;
#Entity
#Table(name="PRODUCTS")
public class Product {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PID")
private Long pId;
#Column(name="PDESC")
#NotBlank
private String pDesc;
#Column(name="QTYINSTOCK")
#Min(value=0)
private int qtyInStock;
#OneToMany(mappedBy="prod")
private List<Order> ordersForProduct = new ArrayList<Order>();
public Long getpId() {
return pId;
}
public void setpId(Long pId) {
this.pId = pId;
}
public String getpDesc() {
return pDesc;
}
public void setpDesc(String pDesc) {
this.pDesc = pDesc;
}
public int getQtyInStock() {
return qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}
public List<Order> getOrdersForProduct() {
return ordersForProduct;
}
public void setOrdersForProduct(List<Order> ordersForProduct) {
this.ordersForProduct = ordersForProduct;
}
}
````````````````````````````````````````````````````````````````````````````````
Jsp file where I am trying to pull all the data from
````````````````````````````````````````````````````````````````````````````````
```````````````````````````````````````````````````````````````````````````````
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<link href="/css/style.css" rel="stylesheet"></link>
<head>
<meta charset="ISO-8859-1">
<title>List of Orders</title>
</head>
<body>
<h1>List of Orders</h1>
<c:forEach items="${allOrders}" var="ords">
<b>${ords.oId} </b>
<table>
<tr>
<th>Quantity</th>
<th>Order Date</th>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Product ID</th>
<th>Description</th>
</tr>
<tr>
<c:forEach items="${ords}" var="order">
<tr>
<td>${order.qty}</td>
<td>${order.orderDate}</td>
<c:forEach items="${ords.cust}" var="order">
<td>${order.cId}</td>
<td>${order.cName}</td>
<c:forEach items="${ords.prod}" var="order">
<td>${order.pId}</td>
<td>${order.pDesc}</td>
</c:forEach>
</c:forEach>
</tr>
</c:forEach>
</tr>
</table>
</c:forEach>
</body>
</html>
````````````````````````````````````````````````````````````````````````````````````
Below is the solve for this question
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<link href="/css/style.css" rel="stylesheet"></link>
<head>
<meta charset="ISO-8859-1">
<title>List of Customers</title>
</head>
<body>
<h1>List of Customers</h1>
<c:forEach items="${ordrs}" var="ords">
<c:forEach items="${ords.orders}" var="order">
<b>${order.oId} </b>
<table>
<tr>
<th>Quantity</th>
<th>Order Date</th>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Product ID</th>
<th>Description</th>
</tr>
<tr>
<td>${order.qty}</td>
<td>${order.orderDate}</td>
<td>${ords.cId}</td>
<td>${ords.cName}</td>
<td>${order.prod.pId}</td>
<td>${order.prod.pDesc}</td>
</tr>
</table>
</c:forEach>
</c:forEach>
</body>
</html>
`````````````````````````````````````````````````````````````````````````````````````````
Related
I try to write my website with spring framework in back- and thymeleaf in frontend on tomcat local server. I try add css to my html file. Css file seems to be linked on server, but devtools shows that it is empty. Do you know what could i miss?
EDIST: sorry for posting pictures, I will know better next time. I left minimum i wanted to show.
index.css
h1{
color: red;
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleag.org">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/index.css" th:href="#{../css/index.css}"/>
</head>
<body>
<h1>Hello</h1>
Greeting
Registration
</body>
</html>
HomePageController.java
package com.krs.GreatBookOfDiet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
#Controller
public class HomePageController {
#GetMapping("")
public String index(Map<String, Object> model){
return "index";
}
}
GreatBookOfDietConfiguration.java
package com.krs.GreatBookOfDiet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import java.util.Locale;
#Configuration
public class GreatBookOfDietConfiguration implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("/WEB-INF/pdf/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
#Bean
public ViewResolver thymeleafResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
}
file structure
devtools on server, index.css view
Your static resources in the /WEB-INF/css folder are not served by Spring, therefore a request for http://example.com/app/css/index.css returns a 404 error.
You need to modify your addResourceHandlers method:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("/WEB-INF/pdf/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/WEB-INF/css/");
}
Remark: Given the popularity of Spring Boot, you might consider using the same locations for static resources (cf. documentation), which sums up to the following configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/");
}
The problem is one to many hibernate mapping is not working in this json format. I think it's a logical error, syntax error is not shown.
My Controller is:
#RequestMapping(value = "/save", method = RequestMethod.POST, produces =MediaType.APPLICATION_JSON_VALUE,headers="Accept=application/json,application/xml")
public #ResponseBody JsonRecord setCurrentDataList(#RequestBody Employee emp) {
try {
int id=employeeServices.save(emp);
} catch (Exception e) {
return new JsonRecord(false,e.getMessage());
}
return new JsonRecord(true,"Successful",emp);
}
Employee Entity Class is:
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.IndexColumn;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name="Employee")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE)
public class Employee implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
#Id
#GeneratedValue
#Column(name ="empId")
#JsonProperty("empId")
private Integer empId;
#JsonProperty("empName")
private String empName;
#JsonProperty("empAddress")
private String empAddress;
#JsonProperty("salary")
private double salary;
#JsonProperty("empAge")
private Integer empAge;
#OneToMany(mappedBy="employee",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#Fetch(FetchMode.SELECT)
private List<Education> education;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public double getSalary() {
return salary;
}
public void setSalary(double d) {
this.salary = d;
}
public Integer getEmpAge() {
return empAge;
}
public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "employee")
#JsonManagedReference
public List<Education> getEducation() {
return education;
}
public void setEducation(List<Education> education) {
this.education = education;
}
}
Education Entity is:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name="Education")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE)
public class Education{
#Id
#GeneratedValue
#Column(name ="eduID")
#JsonProperty("eduID")
private int eduID;
#JsonProperty("qualification")
private String qualification;
#JsonProperty("stream")
private String stream;
#ManyToOne
#JoinColumn(name="empid")
private Employee employee;
public int getEduID() {
return eduID;
}
public void setEduID(int eduID) {
this.eduID = eduID;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "empId", nullable = false)
#JsonBackReference
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
JSON input:
{
"empName": "myname",
"empAddress": "my address",
"salary": 1000,
"empAge": 24,
"education":[{
"qualification":"mca",
"stream":"mca"
}]
}
One to many mapping is not working with this json format.How to implement this mapping in json format? Please give me your valuable suggestions.
use
#OneToMany(cascade={CascadeType.ALL})
#Fetch(FetchMode.JOIN)
#JoinColumn(name="empId", referencedColumnName="empId")
private Set<Education> education;
instead of,
#OneToMany(mappedBy="employee",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#Fetch(FetchMode.SELECT)
private List<Education> education;
I try to make a mini forum and I'm stuck. How it should be, first of all you create a post and write message of topic, it redirects to all post and add new posted which you created, an user click on post and it shows in next page all message which filled in. Also I made a comment system, I every post has to have comments, so the problem is in my code which is below, when I tried to make that comments work, it works like this: doesn't matter what post id you choose it shows all comments which does exist, so I changed and failed. May someone explains me, how to make correct with Hibernate.
PostController is: pay attention on method seeMessage, it findes post by id and show message.
package com.pandora.controllers;
import com.pandora.domain.Post;
import com.pandora.services.CommentService;
import com.pandora.services.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/posts")
public class PostController {
#Autowired
private PostService postService;
#Autowired
private CommentService commentService;
#RequestMapping
public String findAll(Model model) {
model.addAttribute("posts", postService.findAll());
return "post/post";
}
#RequestMapping(value = "/click", method = RequestMethod.GET)
public String click() {
return "post/new";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addPost(#ModelAttribute Post post) {
postService.addPost(post);
return "redirect:/posts";
}
#RequestMapping(value = "/{title}/find", method = RequestMethod.GET)
public String findByName(#PathVariable String title) {
postService.findByTitle(title);
return "redirect:/posts";
}
#RequestMapping(value = "/{id}/see", method = RequestMethod.GET)
public String seeMessage(#PathVariable long id, Model model) {
Post post = postService.findById(id);
System.out.println("the id is " + id);
System.out.println("the value of comments are " +post.getComments().size());
model.addAttribute("post", post);
// model.addAttribute("postMessage", post.getComments());
return "post/postmessage";
}
#RequestMapping(value = "/{id}/delete")
public String delete(#PathVariable long id) {
postService.delete(id);
return "redirect:/posts";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
return "login";
}
}
CommentController is: And here pay attention on method addComment, first I find from what id post it went and after this I have to add comment to founded post.
package com.pandora.controllers;
import com.pandora.domain.Comment;
import com.pandora.domain.Post;
import com.pandora.services.CommentService;
import com.pandora.services.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
#Controller
#RequestMapping("/comments")
public class CommentController {
#Autowired
private CommentService commentService;
#Autowired
private PostService postService;
#RequestMapping(value = "/post/{postId}/comment", method = RequestMethod.POST)
public String addComment(#PathVariable long postId, #ModelAttribute Comment comment){
Post post = postService.findById(postId);
System.out.println(post.getId());
System.out.println(comment.getMessage());
List comments = new ArrayList();
comments.add(commentService.addComment(comment));
post.setComments(comments);
return "redirect:/posts";
}
#RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String delete(#PathVariable long id){
commentService.delete(id);
return "redirect:/posts";
}
}
Post entity is:
package com.pandora.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
#Entity
#Setter
#Getter
#NoArgsConstructor
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "post")
private List comments;
#Column(length = 10000)
private String message;
private String title;
}
PostService is:
package com.pandora.services;
import com.pandora.domain.Post;
import com.pandora.domain.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class PostService {
#Autowired
private PostRepository postRepository;
public Post addPost(Post post){
return postRepository.saveAndFlush(post);
}
public List findAll(){
return postRepository.findAll();
}
public Post findByTitle(String title){
return postRepository.findByTitle(title);
}
public Post findById(long id){
return postRepository.findOne(id);
}
public void delete(long id){
postRepository.delete(id);
}
}
Comment entity is:
package com.pandora.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Setter
#Getter
#NoArgsConstructor
public class Comment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ManyToOne(fetch = FetchType.EAGER)
private Post post;
private String message;
}
and CommentService is :
package com.pandora.services;
import com.pandora.domain.Comment;
import com.pandora.domain.repositories.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class CommentService {
#Autowired
private CommentRepository commentRepository;
public Comment addComment(Comment comment){
return commentRepository.saveAndFlush(comment);
}
public List findAll(){
return commentRepository.findAll();
}
public void delete(long id){
commentRepository.delete(id);
}
public Comment findOne(long id){
return commentRepository.findOne(id);
}
}
and html which showes post which choose by id is: here pay attention to th:each div container. I retrieve from list which are gone from PostController comments. But it doesnt work because when I do it it's always empty. I don't know why it's empty.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
layout:decorator="layout">
<div layout:fragment="content">
<h2 align="center">
<h2 align="left">
<div th:text="${post.title}"></div>
</h2>
</h2>
<h4 align="center">
<div th:text="${post.message}"></div>
</h4>
<hr/>
<h4>Comments:</h4>
<br/>
<h4>
<div th:each="comments : ${post}">
<label for="username"><div th:inline="text">[[${#httpServletRequest.remoteUser}]]: </div> </label>
<div th:each="comment : ${comments.comments}">
<div id="username" th:text="${comment}"></div>
</div>
</div>
</h4>
<br/>
<form method="post" name="comment_form" id="comment_form" th:action="#{'/comments/post/{id}/comment'(id=${post.id}) }" role="form">
<div class="form-group">
<label for="message">Comment</label>
<textarea rows="5" class="form-control" id="message" name="message"/>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</html>
You need to change the controller as well. Think about something like this, you have a post with zero comments now. The user then posts a comment on PostController method say:
#RequestMapping(value = "/post/{postId}/addComment", method = RequestMethod.POST)
public String addPost(#PathVariable("postId")long id, #ModelAttribute Comment comment) {
postService.addComment(id, comment);
return "redirect:/to_whatever";
}
And in your PostService you might want to add the below function:
public Post addComment(long id, Comment comment){
Post post = postRepository.findOne(id);
post.getComments().add(comment);
return postRepository.saveAndFlush(post);
}
Change your UI post call accordingly. Also, this will achieve the retrieval part also. Say you want to get comments for a post, all you need to do is find the post by id (or any other unique identifier) and do post.getComments();
Embeddable will establish a OneToMany kind of relation between post and comment. Refer this for more details.
At the database level, you will have something like this:
POST TABLE
post_id post_name
1 A
2 B
POST_COMMENTS TABLE
post_id message
1 C
1 D
2 E
2 F
Hope this clears the issue.
Based on your scenario this is what I understand: You have a post and some comments associated with it. However, when you are trying to retrieve comments for a particular post, you are seeing all comments (from other posts as well).
Assuming the above, I would suggest you to not treat comments as a separate entity because comments will only be present if there is a post and comments have to be associated to a single post. #Embeddable might help in this.
My recommendation would be to try something like this:
Make Comments as embeddable:
#Embeddable
public class Comment {
private String message;
...
...
//Any other properties you might need to add
}
And in the Post Entity, make the below changes:
#Entity
#Setter
#Getter
#NoArgsConstructor
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ElementCollection(fetch=FetchType.EAGER)
private List<Comment> comments = new ArrayList<>();
#Column(length = 10000)
private String message;
private String title;
}
After this, you might want to loose the CommentService and CommentRepository as they wont be needed any longer. Let me know if this helps.
New to the world of struts2 and hibernate. I designed a form to perform CRUD operations. Projects runs without any errors... But when I submit the form values are not inserted in mySQL database. Another issue - existing values from mySQL table are not populated in datatable on jsp form. Following is code from jsp and other class files. I need to understand if I've missed something here
<%--
Document : ctsFrmCaseCategory
Created on : Nov 17, 2015, 9:30:00 PM
Author : nishad
--%>
<%# 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">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:form action="saveOrUpdateCategory">
<s:push value="category">
<s:hidden name="ccg_ID" />
<s:textfield name="ccg_CategoryName" label="Category Name" />
<s:textfield name="ccg_Description" label="Description" />
<s:checkbox name="ccg_DeleteFlag" label="Delete User?" />
<s:checkbox name="ccg_ActiveFlag" label="Active User?" />
<s:hidden name="ccg_CreateDate" />
<s:hidden name="ccg_CreateUser" />
<s:hidden name="ccg_ModifyDate" />
<s:hidden name="ccg_ModifyUser" />
<s:submit />
</s:push>
</s:form>
<s:if test="categoryList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Category Name</th>
<th>Description</th>
<th>Delete Flag</th>
<th>Active Flag</th>
<th>Create Date</th>
<th>Create User</th>
<th>Modify Date</th>
<th>Modify User</th>
</tr>
<s:iterator value="categoryList" status="categoryStatus">
<tr
class="<s:if test="#categoryStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="ccg_CategoryName" /></td>
<td><s:property value="ccg_Description" /></td>
<td><s:property value="ccg_DeleteFlag" /></td>
<td><s:property value="ccg_ActiveFlag" /></td>
<td><s:property value="ccg_CreateDate" /></td>
<td><s:property value="ccg_CreateUser" /></td>
<td><s:property value="ccg_ModifyDate" /></td>
<td><s:property value="ccg_ModifyUser" /></td>
<td><s:url id="editURL" action="editCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
CategotyDAO.java code ---
package com.cts.dao;
import java.util.List;
import com.cts.domain.Category;
public interface CategoryDAO {
public void saveOrUpdateCategory(Category category);
public List<Category> listCategory();
public Category listCategoryById(Long categoryId);
public void deleteCategory(Long categoryId);
}
CategoryDAOImpl.java code ---
package com.cts.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.cts.domain.Category;
public class CategoryDAOImpl implements CategoryDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a category.
*/
public void saveOrUpdateCategory(Category category) {
try {
session.saveOrUpdate(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a category.
*/
public void deleteCategory(Long categoryId) {
try {
Category category = (Category) session.get(Category.class, categoryId);
session.delete(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the categorys.
*/
#SuppressWarnings("unchecked")
public List<Category> listCategory() {
List<Category> courses = null;
try {
courses = session.createQuery("from Category").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single category by Id.
*/
public Category listCategoryById(Long categoryId) {
Category category = null;
try {
category = (Category) session.get(Category.class, categoryId);
} catch (Exception e) {
e.printStackTrace();
}
return category;
}
}
CategoryAction.java code ---
package com.cts.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.cts.dao.CategoryDAO;
import com.cts.dao.CategoryDAOImpl;
import com.cts.domain.Category;
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {
private static final long serialVersionUID = -6659925652584240539L;
private Category category = new Category();
private List<Category> categoryList = new ArrayList<Category>();
private CategoryDAO categoryDAO = new CategoryDAOImpl();
public Category getModel() {
return category;
}
/**
* To save or update category.
* #return String
*/
public String saveOrUpdate()
{
categoryDAO.saveOrUpdateCategory(category);
return SUCCESS;
}
/**
* To list all categories.
* #return String
*/
public String list()
{
categoryList = categoryDAO.listCategory();
return SUCCESS;
}
/**
* To delete a category.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
categoryDAO.deleteCategory(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
/**
* To list a single category by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
category = categoryDAO.listCategoryById(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Category> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<Category> categoryList) {
this.categoryList = categoryList;
}
}
Category.java code ---
package com.cts.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "cts_mcasecategory")
public class Category {
private Long ccg_ID;
private String ccg_CategoryName;
private String ccg_Description;
private boolean ccg_DeleteFlag;
private boolean ccg_ActiveFlag;
private Date ccg_CreateDate;
private int ccg_CreateUser;
private Date ccg_ModifyDate;
private int ccg_ModifyUser;
#Id
#GeneratedValue
#Column(name = "ccg_ID")
public Long getCcg_ID() {
return ccg_ID;
}
public void setCcg_ID(Long ccg_ID) {
this.ccg_ID = ccg_ID;
}
#Column(name = "ccg_CategoryName")
public String getCcg_CategoryName() {
return ccg_CategoryName;
}
public void setCcg_CategoryName(String ccg_CategoryName) {
this.ccg_CategoryName = ccg_CategoryName;
}
#Column(name = "ccg_Description")
public String getCcg_Description() {
return ccg_Description;
}
public void setCcg_Description(String ccg_Description) {
this.ccg_Description = ccg_Description;
}
#Column(name = "ccg_DeleteFlag")
public boolean isCcg_DeleteFlag() {
return ccg_DeleteFlag;
}
public void setCcg_DeleteFlag(boolean ccg_DeleteFlag) {
this.ccg_DeleteFlag = ccg_DeleteFlag;
}
#Column(name = "ccg_ActiveFlag")
public boolean isCcg_ActiveFlag() {
return ccg_ActiveFlag;
}
public void setCcg_ActiveFlag(boolean ccg_ActiveFlag) {
this.ccg_ActiveFlag = ccg_ActiveFlag;
}
#Column(name = "ccg_CreateDate")
public Date getCcg_CreateDate() {
return ccg_CreateDate;
}
public void setCcg_CreateDate(Date ccg_CreateDate) {
this.ccg_CreateDate = ccg_CreateDate;
}
#Column(name = "ccg_CreateUser")
public int getCcg_CreateUser() {
return ccg_CreateUser;
}
public void setCcg_CreateUser(int ccg_CreateUser) {
this.ccg_CreateUser = ccg_CreateUser;
}
#Column(name = "ccg_ModifyDate")
public Date getCcg_ModifyDate() {
return ccg_ModifyDate;
}
public void setCcg_ModifyDate(Date ccg_ModifyDate) {
this.ccg_ModifyDate = ccg_ModifyDate;
}
#Column(name = "ccg_ModifyUser")
public int getCcg_ModifyUser() {
return ccg_ModifyUser;
}
public void setCcg_ModifyUser(int ccg_ModifyUser) {
this.ccg_ModifyUser = ccg_ModifyUser;
}
}
Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="saveOrUpdateCategory" method="saveOrUpdate" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
<action name="listCategory" method="list" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="editCategory" method="edit" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="deleteCategory" method="delete" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
</package>
Hi there,
My task is displaying a list of object from database to JSP. But i don't know why it only show when i run servlet class,while not show anything when i run JSP. First I used setAttribute method to pass the list to JSP and at JSP i use JSTL tags for retriving data. I think everything is ok but don't why it happend like that. Here's my code
Asiakas.java
package Luokat;
public class Asiakas {
private int asiakas_id;
private String nimi;
private int puhelinnumero;
private String spostiosoite;
/**
*
*/
public Asiakas() {
asiakas_id = 0;
nimi= null;
puhelinnumero =0;
spostiosoite = null;
}
/**
* #param asiakas_id
* #param nimi
* #param puhelinnumero
* #param spostiosoite
*/
public Asiakas(int asiakas_id, String nimi, int puhelinnumero,
String spostiosoite) {
super();
this.asiakas_id = asiakas_id;
this.nimi = nimi;
this.puhelinnumero = puhelinnumero;
this.spostiosoite = spostiosoite;
}
public int getAsiakas_id() {
return asiakas_id;
}
public void setAsiakas_id(int asiakas_id) {
this.asiakas_id = asiakas_id;
}
public String getNimi() {
return nimi;
}
public void setNimi(String nimi) {
this.nimi = nimi;
}
public int getPuhelinnumero() {
return puhelinnumero;
}
public void setPuhelinnumero(int puhelinnumero) {
this.puhelinnumero = puhelinnumero;
}
public String getSpostiosoite() {
return spostiosoite;
}
public void setSpostiosoite(String spostiosoite) {
this.spostiosoite = spostiosoite;
}
#Override
public String toString() {
return "Asiakas [asiakas_id=" + asiakas_id + ", nimi=" + nimi
+ ", puhelinnumero=" + puhelinnumero + ", spostiosoite="
+ spostiosoite + "]";
}
}
NaytaAsiakasServlet
package Servletit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DBHoitaja.DBHoitaja;
import Luokat.Asiakas;
/**
* Servlet implementation class NaytaAsiakasServlet
*/
#WebServlet("/NaytaAsiakasServlet")
public class NaytaAsiakasServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NaytaAsiakasServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NaytaAsiakasServlet nayta = new NaytaAsiakasServlet();
request.setAttribute("asiakasLista", nayta.findAll());
request.getRequestDispatcher("admin_page.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public List<Asiakas> findAll(){
List<Asiakas> list = new ArrayList<Asiakas>();
try {
list.add(new Asiakas(0, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(1, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(3, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
} catch(Exception e){
list =null;
}
return list;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
admin_page.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Ylläpito Sivu</title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" width="500">
<tr>
<th>Id</th>
<th>Nimi</th>
<th>Puhelin</th>
<th>Sähköposti</th>
</tr>
<c:forEach var="asiakas" items="${asiakasLista}" >
<tr>
<td><c:out value="${asiakas.asiakas_id}" /></td>
<td><c:out value="${asiakas.nimi}" /></td>
<td><c:out value="${asiakas.puhelinnumero}" /></td>
<td><c:out value="${asiakas.spostiosoite}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
From your question I can understand that you are totally new to J2EE!! And also you are trying to run the servlet class and JSP, which is not going to work anyway.
Please read the below specified tutorials and have some idea on how run a simple web application.
how to write hello world servlet Example
Sample Code for Hello World: