How to display the data in database on a jsp using struts1? - struts1

I am new to struts. I want to display all the details from a table in database on a jsp to user. Please help me in doing these.
thanks in advance,
Vidya
LoginFormBean.java
public class LoginFormBean extends ValidatorForm
{
public String name;
public String city;
public String state;
public String phone;
public String mailId;
public String gender;
public String branch;
private List studentDetails;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public String getMailId() {
return mailId;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getGender() {
return gender;
}
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public List getStudentDetails() {
return studentDetails;
}
public void setStudentDetails(List studentDetails) {
this.studentDetails = studentDetails;
}
}
Logindao.java
public class Logindao {
public List viewStudents()
{
Connection conn=DBUtil.getDBConnection();
List list=new ArrayList();
Statement stmt = null;
ResultSet rs=null;
String query="select * from student_info";
stmt=conn.createStatement();
rs= stmt.executeQuery(query);
while(rs.next())
{
list = new ArrayList();
list.add(rs.getString("name"));
list.add(rs.getString("phone"));
list.add(rs.getString("email"));
list.add(rs.getString("city"));
list.add(rs.getString("state"));
list.add(rs.getString("gender"));
list.add(rs.getString("branch"));
}
}
return list;
}
RetrieveDataActionClass.java
public class RetrieveDataActionClass extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception,ServletException
{
List list=new ArrayList();
String key="success";
Logindao dao=new Logindao();
LoginFormBean formbean=(LoginFormBean)form;
try{
list=dao.viewStudents();
formbean.setStudentDetails(dao.viewStudents());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Error occured");
}
return mapping.findForward(key);
}
}
viewstudents.jsp
<body>
<html:form action="/retrieve" method="post">
<table border="1">
<tr>
<th>Name</th>
<th>Phone</th>
<th>MailId</th>
<th>City</th>
<th>State</th>
<th>Gender</th>
<th>Branch</th>
</tr>
<logic:iterate id="students" name="LoginFormBean" property="studentDetails">
<tr>
<td><bean:write name="students" property="name"/></td>
<td><bean:write name="students" property="phone"/></td>
<td><bean:write name="students" property="mailId"/></td>
<td><bean:write name="students" property="city"/></td>
<td><bean:write name="students" property="state"/></td>
<td><bean:write name="students" property="gender"/></td>
<td><bean:write name="students" property="branch"/></td>
</tr>
</logic:iterate>
</table>
</html:form>
</body>
I have a table 'student_info' in my sqlserver database.
columns:name,phone,email,city,state,gender,branch
I want to display the output in the following format in jsp.
name phone email city state gender branch
abc 55555 a#gmail.com hyd AP Female IT
xyz 55555 x#gmail.com bang KT Female CSE
Error:
javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find bean: "LoginFormBean" in any scope
Thanks in Advance,
Vidya.

You need to instantiate your bean"LoginFormBean" in your JSP before logic:iterate . you can use use jsp:usebean tag for that

Related

How do i correctly loop through the my list to display the information using Razor?

I have been struggling to loop through my private static List in my HomeController to display in such a way it shows a list of both students and personnel. Below is an example of what my loop should look like.
[Student] Name:John Surname:Greenberg Email: 123#123 Cellphone:123456789 Age: 20
[Personnel] Name:Rose Surname:Marry Email: email#email Cellphone:123456789 WorkerType: Permanent Degree: BED Education
[Student] Name:Chaz Surname:Brown Email: chazz#gmail.com Cellphone:123456789 Age: 30
Please help me loop properly and Below is my ContestantView i tried coding
#model List<Assignment9_u14333393.Models.ContestantViewModel>
<div style="width:100%;height:auto; background-color:brown; padding-top:10px; padding-bottom:10px;">
<h2 style="text-align:center; color:white;">List of Contestants</h2>
</div>
.
<div class="members" >
<table>
#foreach (var temp in Model)
{
<div class="member">
[#temp.MemberType] Name:#temp.Name Surname:#temp.Surname Email: #temp.Email Cellphone:#temp.CellPhone
</div>
}
</table>
</div>
For additional information I also have three models (StudentViewModel, PersonnelViewModel and ContestantViewModel).
ContestantViewModel is my parent class and StudentViewModel and PersonnelViewModel are my classes which have inherited data members and properties for the parent class.
1st Model
public class ContestantViewModel
{
//Data members
private string mName;
private string mSurname;
private string mCellPhone;
private string mEmail;
private string mMemberType;
//Defeaut Constructor
public ContestantViewModel()
{
mName = "NoName";
mSurname = "NoSurname";
mCellPhone = "NoCellNumber";
mEmail = "NoEmail";
mMemberType = "NoMemberType";
}
//Constructor
public ContestantViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType)
{
mName = Name;
mSurname = Surname;
mCellPhone = CellPhone;
mEmail = Email;
mMemberType = MemberType;
}
//Properties
public string Name
{
get { return mName; }
set { mName = value; }
}
public string Surname
{
get { return mSurname; }
set { mSurname = value; }
}
public string CellPhone
{
get { return mCellPhone; }
set { mCellPhone = value; }
}
public string Email
{
get { return mEmail; }
set {mEmail = value; }
}
public string MemberType
{
get; set;
}
}
2rd Model
public class PersonnelViewModel : ContestantViewModel
{
private string mWorkerType;
private string mDegree;
public PersonnelViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType, string WorkerType, string Degree) : base (Name,Surname,CellPhone,Email, MemberType)
{
mWorkerType = WorkerType;
mDegree = Degree;
}
public PersonnelViewModel()
{
mWorkerType = "NoWorkerType";
mDegree = "NoDegree";
}
public string WorkerType
{
get { return mWorkerType;}
set { mWorkerType = value; }
}
public string Degree
{
get { return mDegree; }
set { mDegree = value; }
}
}
3rd Model
public class StudentViewModel : ContestantViewModel
{
//Data members
private int mAge;
//D Constructor
public StudentViewModel()
{
mAge = 0;
}
//Constructor
public StudentViewModel(string Name, string Surname, string CellPhone, string Email, string MemberType, int Age) : base(Name, Surname, CellPhone, Email, MemberType)
{
mAge = Age;
}
//properties
public int Age
{
get { return mAge; } set { mAge = value; }
}
}
and this is my controller
public class HomeController : Controller
{
// list to hold all my new members
private static List<ContestantViewModel> List = new List<ContestantViewModel>();
// GET: Home
public ActionResult Index()
{
return View();
}
// GET: Signup
public ActionResult Signup(string Name, string Surname, string Email, string Cellphone, string MemberType, int Age,string WorkerType,string Degree)
{
StudentViewModel Stundent = new StudentViewModel();
PersonnelViewModel Personnel = new PersonnelViewModel();
if (MemberType == "Student")
{
//creates instance
Stundent.Name = Name;
Stundent.Surname = Surname;
Stundent.Email = Email;
Stundent.CellPhone = Cellphone;
Stundent.MemberType = MemberType;
Stundent.Age = Age;
// Add data to list
List.Add(Stundent);
}
else
{
//creates instance
Personnel.Name = Name;
Personnel.Surname = Surname;
Personnel.Email = Email;
Personnel.CellPhone = Cellphone;
Personnel.MemberType = MemberType;
Personnel.WorkerType = WorkerType;
Personnel.Degree = Degree;
// Add data to list
List.Add(Personnel);
}
return View(List);
}
}
Put your collection into it's own view model instead of trying to reference it with this line:
#model List<Assignment9_u14333393.Models.ContestantViewModel>
Make a new view model, ViewModelCollections with a collection of your ContestantViewModel. Something like
List<ContestantViewModel> ContestantList
(you can also add others, like your students and workers and reuse the model, even if for some purposes some collections are empty)
Then reference that with:
#model ViewModelCollections
Once you have put all your contestants into the collection you are very close in your current view code.
<div class="members">
<table id="contestantListTable">
<tbody>
#* Column Headers *#
<tr class="contestantListHeaders">
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
#* Content Rows *#
#foreach (var temp in Model.ContestantList)
{
<tr>
<td>#temp.mName</td>
<td>#temp.mSurName</td>
<td>#temp.mEmail</td>
<td>#temp.mCellPhone</td>
</tr>
}
</tbody>
</table>
</div>
Instead of this saying "Name: Contestant" "LastName: #1" etc etc
You will have a table:
First Name | Last Name | Email etc etc
Contestant | #1 | ...
.
.
.

How to use OneToMany Association in more than one table

I am trying to join three tables with my model class.Here is my model classes.
Users.java
#Entity
#Table(name = "users")
public class Users implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
public String username;
public String password;
public Integer privid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "pid")
private Set<Privillages> priviJoin;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "actid")
private Set<Actions> actionJoin;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "privid")
public Integer getPrivid() {
return privid;
}
public void setPrivid(Integer privid) {
this.privid = privid;
}
public Set<Privillages> getPriviJoin() {
return priviJoin;
}
public void setPriviJoin(Set<Privillages> priviJoin) {
this.priviJoin = priviJoin;
}
public Set<Actions> getActionJoin() {
return actionJoin;
}
public void setActionJoin(Set<Actions> actionJoin) {
this.actionJoin = actionJoin;
}
public Users() {
}
}
And Privillages.java,
#Entity
#Table(name = "privillages")
public class Privillages implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
#Column(name = "pname")
public String pname;
#ManyToOne(optional = false)
#JoinColumn(name = "pid", referencedColumnName = "privid")
public Users pid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Users getPid() {
return pid;
}
public void setPid(Users pid) {
this.pid = pid;
}
public Privillages(){
}
}
And Actions.java
#Entity
#Table(name = "actions")
public class Actions implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
#Column(name = "actname")
public String actname;
#ManyToOne(optional = false)
#JoinColumn(name = "actid", referencedColumnName = "privid")
public Users actid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getActname() {
return actname;
}
public void setActname(String actname) {
this.actname = actname;
}
public Users getActid() {
return actid;
}
public void setActid(Users actid) {
this.actid = actid;
}
public Actions(){
}
}
My repository containing following code,
#Query(value = "SELECT u.*,p.*,a.* FROM users u "
+ "INNER JOIN privillages p ON u.privid = p.pid "
+ "INNER JOIN actions a ON u.privid = a.actid",
nativeQuery=true)
Set<Users> findByUsername();
My controller action is,
#RequestMapping(value = "/joinResult", method = RequestMethod.GET)
public ModelAndView joinResultShow(Model model)
{
model.addAttribute("joinData",userRepo.findByUsername());
ModelAndView viewObj = new ModelAndView("fleethome");
return viewObj;
}
And my view fleethome is like,
<table>
<th> Username </th>
<th> Privillage </th>
<th> Action </th>
<tr th:each="message : ${joinData}">
<td th:text="${message.username}"></td>
<td><span th:each="privi : ${message.priviJoin}"
th:text="${privi.pname}"></span></td>
<td><span th:each="action : ${message.actionJoin}"
th:text="${action.actname}"></span></td>
</tr>
</table>
I am trying to join Privillages and Actions with my main model Users. Users-Privillages have one to many. And also Users - Actions also have one to many. When I joined Users with Privillages it working good. I successfully joined two table.
Now I also need to join Actions class with Users. I am trying to displaying one column from each Model classes. When I implemented the procedure that I follow previously for joining Users-Privillages is not working here, when I added one more table.
I am getting the error like,
There was an unexpected error (type=Internal Server Error, status=500).
Exception evaluating SpringEL expression: "message.pname" (fleethome:65)
How can I join the additional one table with my previous join?
You probably can't do that without model entity changes.
If i got you right, you want to get your entity class with multiple related collections initialized from db. But this can't work as is in your case because MultipleBagFetchException: cannot simultaneously fetch multiple bags. It is basically the same problem of multiple collections with fetch = FetchType.EAGER. Easy fix would be to change Collection<Privillages> to Set<Privillages> or same for Actions if you can.
More info
As for Exception evaluating SpringEL expression: "message.pid.username" the actual reason is that you are trying to work with joinData as if it is some database table record, but instead you should work with it like you would with java classes. Because you already got Set<User> joinData from hibernate. Can try something like
<tr th:each="message : ${joinData}">
<td th:text="${message.username}"></td>
<td><span th:each="privi : ${message.priviJoin}"
th:text="${privi.pname}"></span></td>
<td><span th:each="action : ${message.actionJoin}"
th:text="${action.actname}"></span></td>
</tr>
If you want same output like in the image you provided, you can try:
<div th:remove="tag" th:each="message : ${joinData}">
<div th:remove="tag" th:each="privi : ${message.priviJoin}">
<div th:remove="tag" th:each="action : ${message.actionJoin}">
<tr>
<td th:text="${message.username}"></td>
<td th:text="${privi.pname}"></td>
<td th:text="${action.actname}"></td>
</tr>
</div>
</div>
</div>

Form Gives 400 Bad Request error when using with Spring's ModelAttribute

i have html form which i forward to spring controller. Its works fine if i use getParameter but using modelAttribute it says 400 bad request error.
Here is my controller Code
#Controller
public class BookController {
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book){
System.out.println(book.getBookName());
bookService.addBooks(book);
return "index";
}
}
This is Book model Code
#Entity
#Table (name = "Book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID",columnDefinition = "BIGINT NOT NULL AUTO_INCREMENT")
private long bookId;
#Column(name="book_code",columnDefinition = "VARCHAR(200) NOT NULL")
private String bookCode;
private String bookName;
private String author;
#Temporal (TemporalType.DATE)
private Date dateOfArrival;
private Double price;
private String rackNo;
private int numberOfBook;
private String subjectCode;
public Book() {
super();
}
public Book(String bookCode, String bookName, String author,
Date dateOfArrival, Double price, String rackNo,
int numberOfBook, String subjectCode) {
super();
this.bookCode = bookCode;
this.bookName = bookName;
this.author = author;
this.dateOfArrival = dateOfArrival;
this.price = price;
this.rackNo = rackNo;
this.numberOfBook = numberOfBook;
this.subjectCode = subjectCode;
}
public String getBookCode() {
return bookCode;
}
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDateOfArrival() {
return dateOfArrival;
}
public void setDateOfArrival(Date dateOfArrival) {
this.dateOfArrival = dateOfArrival;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRackNo() {
return rackNo;
}
public void setRackNo(String rackNo) {
this.rackNo = rackNo;
}
public int getNumberOfBook() {
return numberOfBook;
}
public void setNumberOfBook(int numberOfBook) {
this.numberOfBook = numberOfBook;
}
public String getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(String subjectCode) {
this.subjectCode = subjectCode;
}
}
I have doubt that the problem is due to using date
Please Help me out
I would try 2 things.
In your Model add this:
//here use the same pattern of date your send from the view
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dateOfArrival;
In your controller
#RequestMapping (value="/addBook")
public String addBook(#ModelAttribute Book book, BindingResult result){
...
Then you will be able to debug your method and know the problem.

Th:each iterate specific variables from a hashSet Thymeleaf Spring MVC

So I"m using Thymeleaf and spring MVC and I have a Course object which has a TreeSet of Posts and the set of posts are similar to a reddit post. I'm trying to represent a set of Posts, on a user homepage that I created. I want the posts to come in chronological order, in a newsfeed sort of way, and I already have the user's courses that they are subscribed to on the model.
My problem is that when I try to iterate through each of the posts I can only pull up the post's id, which looks something like this [com.quizbanks.domain.Post#26], and when I try to show the title, which is the variable for the title of the post I always get a spring processor error.
So here's what my thymeleaf code looks like
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts}"></span></td>
</tr>
</table>
and then I tried this, but this gives me the spring processor error
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts.title}"></span></td>
</tr>
</table>
So I'm not really sure what to do, if anyone can see my issue and help me out that would be great, thanks in advance.
Also if you want to see my controller code or anything else, let me know and I'll post it.
UPDATE
User Class
package com.quizbanks.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.quizbanks.security.Authorities;
import com.quizbanks.validators.ValidEmail;
#Entity
#Table(name="users")
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class User
{
private Long id;
#ValidEmail
#NotNull
#NotEmpty
private String email;
private String username;
private String password;
private University university;
private Set<Authorities> authorities = new HashSet<>();
private Set<Course> courses = new HashSet<>();
private Set<Post> posts = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<StudySet> studySet = new HashSet<>();
private Set<Course> myCourses = new HashSet<Course>();
public User ()
{
}
public User(User user)
{
this.id = user.getId();
this.email = user.getEmail();
this.username = user.getUsername();
this.password = user.getPassword();
this.university = user.getUniversity();
this.authorities = user.getAuthorities();
this.courses = user.getCourses();
this.posts = user.getPosts();
this.comments = user.getComments();
this.studySet = user.getStudySet();
this.myCourses = user.getMyCourses();
}
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Course> getCourses()
{
return courses;
}
public void setCourses(Set<Course> courses)
{
this.courses = courses;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
#JsonManagedReference
#JsonIgnoreProperties(allowGetters=true, value = "user" )
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Authorities> getAuthorities()
{
return authorities;
}
public void setAuthorities(Set<Authorities> authorities)
{
this.authorities = authorities;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<StudySet> getStudySet() {
return studySet;
}
public void setStudySet(Set<StudySet> studySet) {
this.studySet = studySet;
}
#ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
#JoinTable(name="user_myCourses")
public Set<Course> getMyCourses()
{
return myCourses;
}
public void setMyCourses(Set<Course> myCourses)
{
this.myCourses = myCourses;
}
}
Post Class
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Course
{
private Long id;
#Size(min=1, max=50)
private String name;
#Size(min=1, max=50)
private String professor;
#Size(min=1, max=50)
private University university;
private Set<Post> posts = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getProfessor()
{
return professor;
}
public void setProfessor(String professor)
{
this.professor = professor;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="course")
public Set<Post> getPosts()
{
return posts;
}
public void setPosts(Set<Post> posts)
{
this.posts = posts;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Post
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Post
{
private Long id;
#Size(min=1, max=140)
#NotNull
private String title;
#Size(min=1, max=1000)
private String content;
private Course course;
private Set<Comment> comments = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#ManyToOne
public Course getCourse()
{
return course;
}
public void setCourse(Course course)
{
this.course = course;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="post")
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Controller
#RequestMapping(value="{user}", method=RequestMethod.GET)
public String userPageGet (ModelMap model, #AuthenticationPrincipal User user)
{
List<User> usersList = userRepo.findAll();
model.addAttribute("usersList", usersList);
List<StudySet> studySets = studySetRepo.findByUser(user);
model.addAttribute("studySets", studySets);
List<Course> courses = courseRepo.findByUser(user);
model.addAttribute("courses", courses);
return "user";
}
${courses} is a list of Courses with posts set inside.
It seems that the problem is that posts is a TreeSet, so you should iterate for each element inside that set to get actual Posts and then get titles.
UPDATE:
List<Course> courses = courseRepo.findByUser(user); here you get all courses for your user. So, next step is to iterate over that list to get all posts:
Set<Post> posts = new TreeSet<>();
for (Course course : courses) {
posts.addAll(course.getPosts);
}
model.addAttribute("posts", posts);

How to set values for a set of a bean object from jsp using Spring MVC 3.0

Here is my bean
package com.sasken.sewa.dto;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Set;
public class SewaGroup implements Serializable{
private static final long serialVersionUID = 1L;
private int group_id;
private String group_name;
private SewaMember group_leader_1;
private SewaMember group_leader_2;
private Village village;
private Double openingbalance_insurance;
private Double openingbalance_employment;
private Double openingbalance_saving;
private Double current_balance;
private Double insurance_fund;
private Double employment_fund;
private Double saving;
private boolean active_status;
private Timestamp golive_date;
private Timestamp deleted_on;
private String bankAccountNumber;
private String bankName;
//private Set<SewaMember> sewamembers;
private Set<SewaGroupMembers> sewagroupmembers;
private Set<GroupInstallment> groupInstallment;
private Set<SewaOperator> sewaoperators;
public int getGroup_id() {
return group_id;
}
public void setGroup_id(int group_id) {
this.group_id = group_id;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public SewaMember getGroup_leader_1() {
return group_leader_1;
}
public void setGroup_leader_1(SewaMember group_leader_1) {
this.group_leader_1 = group_leader_1;
}
public SewaMember getGroup_leader_2() {
return group_leader_2;
}
public void setGroup_leader_2(SewaMember group_leader_2) {
this.group_leader_2 = group_leader_2;
}
public Village getVillage() {
return village;
}
public void setVillage(Village village) {
this.village = village;
}
public Double getOpeningbalance_insurance() {
return openingbalance_insurance;
}
public void setOpeningbalance_insurance(Double openingbalance_insurance) {
this.openingbalance_insurance = openingbalance_insurance;
}
public Double getOpeningbalance_employment() {
return openingbalance_employment;
}
public void setOpeningbalance_employment(Double openingbalance_employment) {
this.openingbalance_employment = openingbalance_employment;
}
public Double getOpeningbalance_saving() {
return openingbalance_saving;
}
public void setOpeningbalance_saving(Double openingbalance_saving) {
this.openingbalance_saving = openingbalance_saving;
}
public String getBankAccountNumber() {
return bankAccountNumber;
}
public void setBankAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public Double getCurrent_balance() {
return current_balance;
}
public void setCurrent_balance(Double current_balance) {
this.current_balance = current_balance;
}
public boolean isActive_status() {
return active_status;
}
public void setActive_status(boolean active_status) {
this.active_status = active_status;
}
public Timestamp getGolive_date() {
return golive_date;
}
public void setGolive_date(Timestamp golive_date) {
this.golive_date = golive_date;
}
public Timestamp getDeleted_on() {
return deleted_on;
}
public void setDeleted_on(Timestamp deleted_on) {
this.deleted_on = deleted_on;
}
public Set<SewaOperator> getSewaoperators() {
return sewaoperators;
}
public void setSewaoperators(Set<SewaOperator> sewaoperators) {
this.sewaoperators = sewaoperators;
}
public Set<SewaGroupMembers> getSewagroupmembers() {
return sewagroupmembers;
}
public void setSewagroupmembers(Set<SewaGroupMembers> sewagroupmembers) {
this.sewagroupmembers = sewagroupmembers;
}
public Set<GroupInstallment> getGroupInstallment() {
return groupInstallment;
}
public void setGroupInstallment(Set<GroupInstallment> groupInstallment) {
this.groupInstallment = groupInstallment;
}
/*public String getGroupAccountNumber() {
return bankAccountNumber;
}
public void setGroupAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}*/
public Double getInsurance_fund() {
return insurance_fund;
}
public void setInsurance_fund(Double insurance_fund) {
this.insurance_fund = insurance_fund;
}
public Double getEmployment_fund() {
return employment_fund;
}
public void setEmployment_fund(Double employment_fund) {
this.employment_fund = employment_fund;
}
public Double getSaving() {
return saving;
}
public void setSaving(Double saving) {
this.saving = saving;
}
}
Jsp page
<form:form method="post" action="/SEWATemp/add_new_sewa_group"
modelAttribute="sewaGroup">
<fieldset>
<legend>SimpleAjaxDemo:</legend>
<table>
<tr>
<td>SEWA group_name</td>
<td><form:input path="group_name" /></td>
</tr>
<tr>
<td>SEWA group_leader_1</td>
<td><form:input path="group_leader_1.member_name" /></td>
</tr>
<tr>
<td>group_leader_2</td>
<td><form:input path="group_leader_2.member_name" /></td>
</tr>
<tr>
<td>Bank Name</td>
<td><form:input path="bankName" /></td>
</tr>
<tr>
<td>groupAccountNumber</td>
<td><form:input path="bankAccountNumber" /></td>
</tr>
<tr>
<td>groupInstallment</td>
<c:forEach var="group" items="${sewaGroup.groupInstallment}"
varStatus="vs">
<td><form:input path="group.installment_amount" /></td>
</c:forEach>
</tr>
<tr>
<td>operatorName</td>
<td><form:select path="sewaoperators" id="operatorName">
<form:option value="">select SKK</form:option>
<c:forEach var="operator" items="${operatorList}">
<form:option value="${operator.operator_id}">${operator.operator_member.member_name}</form:option>
</c:forEach>
</form:select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</fieldset>
My issue is how to set the value for sewaoperators from jsp.
The error i am getting is Type mismatch cannot convert from java.lang.String[] to java.util.set
Please reply to this question .
You can create an Array of String, sewaoperators[] as transient object like this:
#Transient
public String[](or List<String>) getSewaoperators() {
return sewaoperators;
}
on receiving the model attribute, you convert the array(list) to your own entity class.
If not, the spring doesn't know how to convert it.
You cannot assign a selected value from operatorList to a Set type (in form:select) in this way. You need to use another field in your SewaGroup as say:
private String selectedOperator;
//setters and getters of selectedOperator
Make changes to jsp as:
<form:select path="selectedOperator" id="operatorName">
...
</form:select>
When you submit this, in your controller or whatever handler you have to process this, you have to compare selectedOperator value with operatorList, get the operator and assign the remaining fields from this operator(because you have not specified the datatype of this operator in question) to SewaOperator and then add this SewaOperator to set.

Resources