How to save data in one thymeleaf page in multiple sql rows - java

i'm new to spring-boot. In my thymeleaf page i have used a for loops to generate headers and have a dropdown under each of them.I need to save that header and selected dropdown item in one sql row.(ex:im using days of the week in a for loop as the header and a user can select a subject under each header, and when a user select subjects and click submit button then 5 sql rows should be saved with day and subject) but currently it saves all the dates and subjects in 1 sql row
addTimeTableMapping thymeleaf view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timeTableMapping.css" th:href="#{/css/timeTableMapping.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
</form>
<div class="container2">
<form action="#" th:action="#{/timeTableMapping/saveAll}" th:object="${timeTableMapping}" method="post">
<table border="0" cell[adding="10">
<tr>
<td><h1>Time Table:</h1></td>
<td>
<select th:field="*{time_table_code}">
<option value="">Choose..</option>
<option th:each="timeTable: ${timeTables}" th:value="${timeTable.name}" th:text="${timeTable.name}"/>
</select>
</td>
</tr>
</table>
<table border="1" >
<thead>
<tr>
</tr>
<br>
<th:block th:each="day : ${days}">
<th th:value="${day.name}" th:text="${day.name}"></th>
</th:block>
</thead>
<tbody>
<th:block th:each="day : ${days}">
<td>
<select th:field="*{subject_code}">
<option value=""></option>
<option th:each="subject: ${subjects}" th:value="${subject.subject_code}" th:text="${subject.name}"/>
<td><input type="text" th:value="${day.name}" name="day" style="display:none" /></td>
</select>
</td>
</th:block>
<tr>
<td colspan="2">
<button type="submit">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
timeTable Mapping Controller
#Controller
public class TimeTableMappingController {
#Autowired
private TimeTableMappingDAO timeTableMappingDAO;
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private DayDAO dayDAO;
#Autowired
private TimeDAO timeDAO;
#RequestMapping("/timeTableMapping")
public String viewHomePage(Model model){
List<TimeTableMapping> timeTableMappingDetails= timeTableMappingDAO.findAll();
model.addAttribute("timeTableMappingDetails",timeTableMappingDetails);
return "timeTableMapping";
}
/*
#RequestMapping ("/timeTableMapping/new")
public String addTimeTableMapping(Model model) {
TimeTableMappingDTO timeTablesForm = new TimeTableMappingDTO();
for (int i = 1; i <= 3; i++) {
timeTablesForm.addTimeTableMapping(new TimeTableMapping());
}
model.addAttribute("form", timeTablesForm);
return "addTimeTableMapping";
}
*/
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
String[] dayArray = timeTableMapping.getDay().split(",");
String[] subArray = timeTableMapping.getSubject_code().split(",");
List<TimeTableMapping> tempList = new ArrayList<>();
for(int i = 0 ; i < dayArray.length; i++) {
TimeTableMapping tempTimeTable = new TimeTableMapping();
tempTimeTable.setTime_table_code(timeTableMapping.getTime_table_code());
System.out.println(timeTableMapping.getTime_table_code());
tempTimeTable.setDay(dayArray[i]);
System.out.println(dayArray[i]);
tempTimeTable.setSubject_code(subArray[i]);
System.out.println(subArray[i]);
tempTimeTable.setStart(timeTableMapping.getStart());
tempTimeTable.setEnd(timeTableMapping.getEnd());
tempList.add(tempTimeTable);
}
timeTableMappingDAO.saveAll(tempList);
return "redirect:/timeTableMapping";
}
#RequestMapping("/timeTableMapping/new")
public String addTimeTableMapping(Model model){
System.out.println("hey");
System.out.println("hey");
TimeTableMapping timeTableMapping =new TimeTableMapping();
model.addAttribute("timeTableMapping",timeTableMapping);
List<TimeTable> timeTableDetail = timeTableDAO.findAll();
model.addAttribute("timeTables", timeTableDetail);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
String[] days = new String[] { "Monday", "Tuesday"};
List<Day> dayDetails = dayDAO.findAll();
model.addAttribute("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
model.addAttribute("times",timeDetails);
return "addTimeTableMapping";
}
/*
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public void saveAll(List<TimeTableMapping> timeTableMappingList) { timeTableMappingDAO.saveAll(timeTableMappingList);}
#RequestMapping(value="/timeTableMapping/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println(timeTableMapping.getId());
System.out.println(timeTableMapping.getDay());
System.out.println(timeTableMapping.getStart());
System.out.println(timeTableMapping.getEnd());
System.out.println(timeTableMapping.getSubject_code());
System.out.println(timeTableMapping.getTime_table_code());
timeTableMappingDAO.save(timeTableMapping);
return "redirect:/timeTableMapping/new";
}
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST) public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
String[] dayArray = timeTableMapping.getDay().split(",");
String[] subArray = timeTableMapping.getSubject_code().split(",");
List<TimeTableMapping> tempList = new ArrayList<>();
for(int i = 0 ; i < dayArray.length; i++) {
TimeTableMapping tempTimeTable = new TimeTableMapping();
tempTimeTable.setTime_table_code(timeTableMapping.getTime_table_code());
tempTimeTable.setDay(dayArray[i]);
tempTimeTable.setSubject_code(subArray[i]);
tempTimeTable.setStart(timeTableMapping.getStart());
tempTimeTable.setEnd(timeTableMapping.getEnd());
tempList.add(tempTimeTable);
}
timeTableMappingDAO.saveAll(tempList);
return "redirect:/timeTableMapping";
}
/*
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveAll(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableDAO.saveAll(timeTableMapping);
return "redirect:/timeTableMapping";
}*/
#RequestMapping("/timeTableMapping/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetails = subjectDAO.findAll();
mav.addObject("subjects", subjectDetails);
List<StudentGroup> studentGroupDetails = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetails);
List<Day> dayDetails = dayDAO.findAll();
mav.addObject("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
mav.addObject("times",timeDetails);
return mav;
}
#RequestMapping("/timeTableMapping/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
timeTableMapping Repository
#Repository
public interface TimeTableMappingRepository extends JpaRepository<TimeTableMapping, Long> {
}

You are using form submission for saving complex data which is much complicated instead of that write java script and save your information in javascript object and send json string to controller for saving with list.
For now with your implementation simple hacky solution would be this.
1) saveTimeTable implementation with following
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
String[] dayArray = timeTableMapping.getDay().split(",");
String[] subArray = timeTableMapping.getSubject_code().split(",");
List<TimeTableMapping> tempList = new ArrayList<>();
for(int i = 0 ; i < dayArray.length; i++) {
TimeTableMapping tempTimeTable = new TimeTableMapping();
tempTimeTable.setTime_table_code(timeTableMapping.getTime_table_code());
tempTimeTable.setDay(dayArray[i]);
tempTimeTable.setSubject_code(subArray[i]);
tempTimeTable.setStart(timeTableMapping.getStart());
tempTimeTable.setEnd(timeTableMapping.getEnd());
tempList.add(tempTimeTable);
}
timeTableMappingDAO.saveAll(tempList);
return "redirect:/timeTableMapping";
}

Related

How to save selected for loop data in mysql database?

I'm new to spring boot and struck in a prob for some time now. In my thymeleaf page i have used a for loops and i need to save currently iterating item in the database.(ex:im using days of the week in a for loop and a user can select a subject for each item in my for loo, then 5 sql rows should be saved with day and subject) but currently it doesn't save the date and save 2 selected subjects in 1 sql row
Add time Table thymeleaf view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timeTableMapping.css" th:href="#{/css/timeTableMapping.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
</form>
<div class="container2">
<form action="#" th:action="#{/timeTableMapping/save}" th:object="${timeTableMapping}" method="post">
<table border="0" cell[adding="10">
<tr>
<td><h1>Time Table:</h1></td>
<td>
<select th:field="*{time_table_code}">
<option value="">Choose..</option>
<option th:each="timeTable: ${timeTables}" th:value="${timeTable.name}" th:text="${timeTable.name}"/>
</select>
</td>
</tr>
</table>
<table border="1" >
<thead>
<tr>
</tr>
<br>
<th:block th:each="day : ${days}">
<th th:value="${day.name}" th:text="${day.name}"></th>
</th:block>
</thead>
<tbody>
<th:block th:each="day : ${days}">
<td>
<select th:field="*{subject_code}">
<option value=""></option>
<option th:each="subject: ${subjects}" th:value="${subject.subject_code}" th:text="${subject.name}"/>
</select>
</td>
</th:block>
<tr>
<td colspan="2">
<button type="submit">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
Time Table Mapping Controller
#Controller
public class TimeTableMappingController {
#Autowired
private TimeTableMappingDAO timeTableMappingDAO;
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private DayDAO dayDAO;
#RequestMapping("/timeTableMapping")
public String viewHomePage(Model model){
List<TimeTableMapping> timeTableMappingDetails= timeTableMappingDAO.findAll();
model.addAttribute("timeTableMappingDetails",timeTableMappingDetails);
return "timeTableMapping";
}
#RequestMapping("/timeTableMapping/new")
public String addTimeTableMapping(Model model){
System.out.println("hey");
System.out.println("hey");
TimeTableMapping timeTableMapping =new TimeTableMapping();
model.addAttribute("timeTableMapping",timeTableMapping);
List<TimeTable> timeTableDetail = timeTableDAO.findAll();
model.addAttribute("timeTables", timeTableDetail);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
List<Day> dayDetails = dayDAO.findAll();
model.addAttribute("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
model.addAttribute("times",timeDetails);
return "addTimeTableMapping";
}
#RequestMapping(value="/timeTableMapping/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableMappingDAO.save(timeTableMapping);
return "redirect:/timeTableMapping";
}
/*
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveAll(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableDAO.saveAll(timeTableMapping);
return "redirect:/timeTableMapping";
}*/
#RequestMapping("/timeTableMapping/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetails = subjectDAO.findAll();
mav.addObject("subjects", subjectDetails);
List<StudentGroup> studentGroupDetails = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetails);
List<Day> dayDetails = dayDAO.findAll();
mav.addObject("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
mav.addObject("times",timeDetails);
return mav;
}
#RequestMapping("/timeTableMapping/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
Add Time Table DAO
#Service
public class TimeTableMappingDAO {
#Autowired
TimeTableRepository timeTableRepository;
#Autowired
TimeTableMappingRepository timeTableMappingRepository;
//to save a time table
public TimeTableMapping save(TimeTableMapping timeTableMapping){
return timeTableMappingRepository.save(timeTableMapping);
}
//#Override
public void saveAll(List<TimeTableMapping> timeTableMapping) {
List<TimeTableMapping> timetable=new ArrayList<>();
timeTableMappingRepository.saveAll(timetable).forEach(timeTableMapping::add); // TimeTable repository
}
/*
public TimeTableMapping saveAll(TimeTableMapping timeTableMapping){
return timeTableMappingRepository.saveAll(timeTableMapping);
}
*/
//to search all
public List<TimeTableMapping> findAll(){
return timeTableMappingRepository.findAll();
}
//get by id
public TimeTableMapping findById(Long id){
return timeTableMappingRepository.findById(id).orElse(null);
}
//delete
public void delete(Long id){
timeTableMappingRepository.deleteById(id);
}
}
Time Table Mapping Repository
#Repository
public interface TimeTableMappingRepository extends JpaRepository<TimeTableMapping, Long> {
}
Before auto wiring TimeTableMappingRepository in your DAO, you should add #Repository on interface TimeTableMappingRepository.
Just like this
#Repository
public interface TimeTableMappingRepository extends JpaRepository {}
By Adding #Repository on the interface, spring-data-jpa will create a proxy object of this interface on runtime and you will be able to autowired it.
You are getting more than one data. So you should use List<TimeTableMapping> timeTableMapping
In your service Implementation, you can pass the list that you got adn save all
#Override
public void saveAll(List<TimeTableMapping> timeTableMapping) {
List<TimeTableMapping> timetable=new ArrayList<>();
repository.saveAll(timetable).forEach(timeTableMapping::add); // TimeTable repository
}

I need to create a responsive timetable view in springboot

I'm new to Spring boot and i'm currently working on a project. I need to create a responsive timetable view(for a particular student group ex: CS year1), when user select a cell he should be redirected to a page where he should be able to add or edit the subject for that particular cell. Can someone please tell me how to do this? thanks.
I have created studentgroup,subject and they are working properly
Student group controller
#Controller
public class StudentGroupController {
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private CourseDAO courseDAO;
#RequestMapping("/studentGroup")
public String viewHomePage(Model model){
List<StudentGroup> studentGroupDetails= studentGroupDAO.findAll();
model.addAttribute("studentGroupDetails",studentGroupDetails);
return "studentGroup";
}
#RequestMapping("/studentGroup/new")
public String addStudentGroup(Model model){
StudentGroup studentGroup =new StudentGroup();
model.addAttribute("studentGroup",studentGroup);
List<Course> courseDetail = courseDAO.findAll();
model.addAttribute("courses", courseDetail);
return "addStudentGroup";
}
#RequestMapping(value="/studentGroup/save",method= RequestMethod.POST)
public String saveStudentGroup(#ModelAttribute("studentGroup") StudentGroup studentGroup){
studentGroupDAO.save(studentGroup);
return "redirect:/studentGroup";
}
#RequestMapping("/studentGroup/edit/{id}")
public ModelAndView updateStudentGroup(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateStudentGroup"));
StudentGroup studentGroup = studentGroupDAO.findById(id);
mav.addObject("studentGroup",studentGroup);
List<Course> courseDetail = courseDAO.findAll();
mav.addObject("courses", courseDetail);
return mav;
}
#RequestMapping("/studentGroup/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
studentGroupDAO.delete(id);
return "redirect:/studentGroup";
}
}
Subject Controller
#Controller
public class SubjectController {
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private CourseDAO courseDAO;
#Autowired
private LectureHallDAO lectureHallDAO;
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
return "subject";
}
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
List<Course> courseDetail = courseDAO.findAll();
model.addAttribute("courses", courseDetail);
List<LectureHall> lectureHallDetail = lectureHallDAO.findAll();
model.addAttribute("lectureHalls",lectureHallDetail);
return "addSubject";
}
#RequestMapping(value="/subject/save",method= RequestMethod.POST)
public String saveSubject(#ModelAttribute("subject") Subject subject){
subjectDAO.save(subject);
return "redirect:/subject";
}
#RequestMapping("/subject/edit/{id}")
public ModelAndView updateSubjcet(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateSubject"));
Subject subject=subjectDAO.findById(id);
mav.addObject("subject",subject);
List<Course> courseDetail = courseDAO.findAll();
mav.addObject("courses", courseDetail);
List<LectureHall> lectureHallDetail = lectureHallDAO.findAll();
mav.addObject("lectureHalls",lectureHallDetail);
return mav;
}
#RequestMapping("/subject/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
subjectDAO.delete(id);
return "redirect:/subject";
}
}
Time Table Controller
#Controller
public class TimeTableController {
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#RequestMapping("/timeTable")
public String viewHomePage(Model model){
List<TimeTable> timeTableDetails= timeTableDAO.findAll();
model.addAttribute("timeTableDetails",timeTableDetails);
return "timeTable";
}
#RequestMapping("/timeTable/new")
public String addTimeTable(Model model){
TimeTable timeTable =new TimeTable();
model.addAttribute("timeTable",timeTable);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
List<StudentGroup> studentGroupDetail = studentGroupDAO.findAll();
model.addAttribute("studentGroups",studentGroupDetail);
return "addStudentGroup";
}
#RequestMapping(value="/timeTable/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTable") TimeTable timeTable){
timeTableDAO.save(timeTable);
return "redirect:/timeTable";
}
#RequestMapping("/timeTable/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetail = subjectDAO.findAll();
mav.addObject("subjects", subjectDetail);
List<StudentGroup> studentGroupDetail = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetail);
return mav;
}
#RequestMapping("/timeTable/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
Time Table view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timetable.css" th:href="#{/css/view.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
<h1>Time Table</h1>
<div class="container" style="margin-top:30px">
<br><br>
<table border="1">
<thead>
<tr>
<td></td>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
</tr>
</thead>
<tbody>
<tr><td> 8.00 - 9.00</td>
</tr>
<tr><td> 9.00 - 10.00</td>
</tr>
<tr> <td>10.00 - 11.00</td>
</tr>
<tr><td>11.00 - 12.00</td>
</tr>
<tr> <td>12.00 - 1.00</td>
</tr>
<tr> <td>1.00 - 2.00</td>
</tr>
<tr><td> 2.00 - 3.00</td>
</tr>
<tr><td> 3.00 - 4.00</td>
</tr>
<tr><td> 4.00 - 5.00</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

populating thymeleaf dropdown with data of another table

i'm new to spring-boot. In my system there are two models named subject,course(two databases with the same names and connected by the foreign key course_id).I need to make it possible to select course name in a dropdown list in the addSubject thymeleaf form. Can someone please tell me how to do this
Subject.DAO file
#Service
public class SubjectDAO {
#Autowired
SubjectRepository subjectRepository;
//to save a subject
public Subject save(Subject subject){
return subjectRepository.save(subject);
}
//to search all subjects
public List<Subject> findAll(){
return subjectRepository.findAll();
}
//get a subject by id
public Subject findById(Long id){
return subjectRepository.findById(id).orElse(null);
}
//delete a subject
public void delete(Long id){
subjectRepository.deleteById(id);
}
}
Course.DAO file
#Service
public class CourseDAO {
#Autowired
CourseRepository courseRepository;
//to save a course
public Course save(Course course){
return courseRepository.save(course);
}
//to search all courses
public List<Course> findAll(){
return courseRepository.findAll();
}
//get a course by id
public Course findById(Long id){
return courseRepository.findById(id).orElse(null);
}
//delete a course
public void delete(Long id){
courseRepository.deleteById(id);
}
}
Subject Controller
#Controller
public class SubjectController {
#Autowired
private SubjectDAO subjectDAO;
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
return "subject";
}
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
return "addSubject";
}
#RequestMapping(value="/subject/save",method= RequestMethod.POST)
public String saveCourse(#ModelAttribute("subject") Subject subject){
subjectDAO.save(subject);
return "redirect:/subject";
}
#RequestMapping("/subject/edit/{id}")
public ModelAndView updateSubjcet(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateSubject"));
Subject subject=subjectDAO.findById(id);
mav.addObject("subject",subject);
return mav;
}
#RequestMapping("/subject/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
subjectDAO.delete(id);
return "redirect:/subject";
}
}
Subject html file
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Adding a Subject</title>
</head>
<body>
<div align="center">
<h1>Add a new Subject</h1>
<br/>
<form action="#" th:action="#{/subject/save}" th:object="${subject}" method="post">
<table border="0" cell[adding="10">
<tr>
<td>Subject code:</td>
<td><input type="text" th:field="*{course_code}" /></td>
</tr>
<tr>
<td>Subject Name:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Course:</td>
<td>
<select>
<option value=""></option>
</select>
Z
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</body>
</html>
So you want to load Course combo inside subject html
You need to modify subject controller
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
model.addAttribute("courses",courseDetail);
return "subject";
}
In HTML
<tr>
<td>Course:</td>
<td>
<select th:field="*{course_code}">
<option value="">Choose..</option>
<option th:each="course: ${courses}" th:value="${course.id}" th:text="${course.name}" />
</select>
</td>
</tr>
<tr>
Edit 1:
I think you are loading addSubject.html
In that case you need to modify addSubject controller
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("courses",courseDetail);
return "addSubject";
}
Edit 2:
As per your code in Git I can see
#Autowired
private SubjectDAO subjectDAO;
private CourseDAO courseDAO;
It should be
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private CourseDAO courseDAO;
First add all courses to the ModelMap
model.addAttribute("cources",courseDao.findAll());
Then use th:each attribute to populate select options
<select th:field="*{course}">
<option value="">Choose..</option>
<option th:each="c: ${cources}" th:value="${c.id}" th:text="${c.name}" />
</select>

Spring MVC Hibernate Application loading database table

I created a simple web application with SpringMVC and Hibernate. Everything works fine, my employees are added to database (using MySQL) but page don't show the list of them:
Also logger don't show any output message when I'm adding the object when it should show something like: "Employee add successfully, Employee details: ..."
Here's the page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html>
<head>
<title>Employee Page</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a Employee
</h1>
<c:url var="addAction" value="/employee/add" ></c:url>
<form:form action="${addAction}" commandName="employee">
<table>
<c:if test="${!empty employee.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty employee.name}">
<input type="submit"
value="<spring:message text="Edit Employee"/>" />
</c:if>
<c:if test="${empty employee.name}">
<input type="submit"
value="<spring:message text="Add Employee"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>List of Employees</h3>
<c:if test="${!empty listEmployees}">
<table class="tg">
<tr>
<th width="80">Employee ID</th>
<th width="120">Employee Name</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listEmployee}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td><a href="<c:url value='/edit/${employee.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${employee.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
#Qualifier(value = "employeeDAO")
public class EmployeeDAOImpl implements EmployeeDAO {
private static final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addEmployee(Employee e) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(e);
logger.info("Employee saved successfully, Employee details: " + e);
}
#Override
public void updateEmployee(Employee e) {
Session session = this.sessionFactory.getCurrentSession();
session.update(e);
logger.info("Employee updated successfully, Employee details: " + e);
}
#SuppressWarnings("uncheked")
#Override
public List<Employee> listEmployee() {
Session session = this.sessionFactory.getCurrentSession();
List<Employee> employeeList = session.createQuery("FROM Employee").list();
for (Employee e: employeeList){
logger.info("Employee List::" + e);
}
return employeeList;
}
#Override
public Employee getEmployeeById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee e = (Employee) session.load(Employee.class, new Integer(id));
logger.info("Employee loaded successfully, Employee details: " + e);
return null;
}
#Override
public void removeEmployee(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee e = (Employee) session.load(Employee.class, new Integer(id));
if(e != null){
session.delete(e);
}
logger.info("Employee delete successfully, Employee details: " + e);
}
}
My Service class:
#Service
#Qualifier(value = "employeeService")
public class EmployeeServiceImpl implements EmployeeService{
public EmployeeServiceImpl() {
}
private EmployeeDAO employeeDAO;
public EmployeeServiceImpl(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
#Override
#Transactional
public void addEmployee(Employee e) {
this.employeeDAO.addEmployee(e);
}
#Override
#Transactional
public void updateEmployee(Employee e) {
this.employeeDAO.updateEmployee(e);
}
#Override
#Transactional
public List<Employee> listEmployee() {
return this.employeeDAO.listEmployee();
}
#Override
#Transactional
public Employee getEmployeeById(int id) {
return this.employeeDAO.getEmployeeById(id);
}
#Override
#Transactional
public void removeEmployee(int id) {
this.employeeDAO.removeEmployee(id);
}
public void setEmployeeDAO(EmployeeDAOImpl employeeDAO) {
this.employeeDAO = employeeDAO;
}
}
Here I create the mapping:
#Entity
#Table(name = "Employee")
public class Employee {
#Column(name = "Name")
private String name;
#Id
#Column(name = "Employee ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int employeeID;
public Employee(String name) {
this.name = name;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", employeeID=" + employeeID +
'}';
}
}
Controller class:
#Controller
public class EmployeeController {
private EmployeeService employeeService;
#Autowired(required = true)
#Qualifier("employeeService")
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public String employeeList(Model model) {
model.addAttribute("employee", new Employee());
model.addAttribute("listEmployee", this.employeeService.listEmployee());
return "employee";
}
//For add and update person both
#RequestMapping(value = "/employee/add", method = RequestMethod.GET)
public String addEmployee(#ModelAttribute("person") Employee e){
if (e.getEmployeeID() == 0){
//new employee, add it
this.employeeService.addEmployee(e);
}else {
//existing employee, call update
this.employeeService.updateEmployee(e);
}
return "redirect:/employee";
}
#RequestMapping(value = "employees/remove/{id}")
public String removeEmployee(#PathVariable("id") int id){
this.employeeService.removeEmployee(id);
return "redirect:/employees";
}
#RequestMapping(value = "/employees/edit{id}")
public String editEmployee(#PathVariable("id") int id, Model model){
model.addAttribute("employee", this.employeeService.getEmployeeById(id));
model.addAttribute("listEmployees", this.employeeService.listEmployee());
return "employee";
}
}
In JSP Page your checking condition listEmployees , but in Controller You have added as model attribute listEmployee. remove last character s from listEmployees in Jsp. It should work. Otherwise everything is fine.
<c:if test="${!empty listEmployees}">
In Controller
model.addAttribute("listEmployee", this.employeeService.listEmployee());
change
<c:forEach items="${listEmployee}" var="employee">
to
<c:forEach items="${listEmployees}" var="employee">

How make a link to show a list of a subject an jsp?

In my jsp project/overview I need to add a link which takes me to review/add and lets the user add the review to the specific project but unfortunately I have problem making that link. Any help is really appreciated :-)
This is the projectController:
#Controller
#RequestMapping(value = "/project")
public class ProjectController {
#Autowired
private ProjectService projectService;
#RequestMapping(value = "/add", method = RequestMethod.GET)
#Secured("ROLE_MANAGER")
public ModelAndView addProjectPage() {
ModelAndView modelAndView = new ModelAndView("project/add");
modelAndView.addObject("project", new Project());
return modelAndView;
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
#Secured("ROLE_MANAGER")
public ModelAndView addingProject(#ModelAttribute Project project) {
ModelAndView modelAndView = new ModelAndView("project/overview");
Map<String, String> validationResult = validate(project, false);
String message = "";
if (validationResult.isEmpty()) {
project.setStatus("Actief");
projectService.addProject(project);
message = "Project was successfully added.";
modelAndView = new ModelAndView("project/overview");
List<Project> projects = projectService.getProjects();
modelAndView.addObject("projects", projects);
} else {
for (String key : validationResult.keySet()) {
modelAndView.addObject(key, validationResult.get(key));
}
modelAndView.addObject("project", project);
}
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value = "/overview")
#Secured({"ROLE_MANAGER"})
public ModelAndView listOfProjects() {
ModelAndView modelAndView = new ModelAndView("project/overview");
List<Project> projects = projectService.getProjects();
modelAndView.addObject("projects", projects);
return modelAndView;
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
#Secured("ROLE_MANAGER")
public ModelAndView editProjectPage(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("project/edit");
Project project = projectService.getProject(id);
modelAndView.addObject("project", project);
return modelAndView;
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
#Secured("ROLE_MANAGER")
public ModelAndView edditingProject(#ModelAttribute Project project,
#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("project/edit");
Map<String, String> validationResult = validate(project, true);
String message = "";
if (validationResult.isEmpty()) {
projectService.updateProject(project);
message = "Project was successfully edited.";
modelAndView = new ModelAndView("project/overview");
List<Project> proejcts = projectService.getProjects();
modelAndView.addObject("projects", proejcts);
} else {
for (String key : validationResult.keySet()) {
modelAndView.addObject(key, validationResult.get(key));
}
modelAndView.addObject("project", project);
}
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
#Secured("ROLE_MANAGER")
public ModelAndView deleteProject(#PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("project/overview");
projectService.deleteProject(id);
String message = "Project was successfully deleted.";
modelAndView.addObject("message", message);
List<Project> projects = projectService.getProjects();
modelAndView.addObject("projects", projects);
return modelAndView;
}
private Map<String, String> validate(Project project, boolean edit) {
Map<String, String> result = new HashMap<String, String>();
if (StringUtils.isEmptyOrWhitespaceOnly(project.getTitle())) {
result.put("titleError", "Cannot be empty");
}
Project tempProject = projectService.getProjectByTitle(project.getTitle());
if (tempProject != null) {
if (edit) {
if (tempProject.getId() != project.getId()) {
result.put("titleError", "Already taken");
}
} else {
result.put("titleError", "Already used");
}
}
return result;
}
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
#Secured("ROLE_MANAGER")
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is welcome page!");
model.setViewName("home");
return model;
}
#RequestMapping(value = "/projectReviews/{id}", method = RequestMethod.GET)
public ModelAndView projectReviews(#PathVariable Integer id){
ModelAndView projectReviewsView = new ModelAndView("project/projectreviewslist");
Project project = projectService.getProject(id);
Set<Review> projectReviews = project.getReviews();
projectReviewsView.addObject("project", project);
projectReviewsView.addObject("projectReviews", projectReviews);
return projectReviewsView;
}
}
Here the project/overview where I need to make the list to project/projectreviewslist.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<t:masterpage>
<jsp:body>
<body>
<div class="container" id="main">
<div class="login" style="width: auto;">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title pull-left">Lijst van projecten</h3>
</div>
<div class="panel-body">
<fieldset>
<legend>Hier ziet u een lijst van projecten. Hier kunt u ze wijzigen, verwijderen of updaten.</legend>
<p>${message}</p>
<div class="box">
<table class="table table-bordered table-hover table-striped" width="600">
<thead height="50px">
<tr>
<th width="5%">ID</th>
<th width="30%">Titel</th>
<th width="30%">Begin datum</th>
<th width="30%">Eind datum</th>
<th width="30%">Status</th>
<th width="5%">Acties</th></tr>
</thead>
<tbody>
<c:forEach var="project" items="${projects}">
<tr>
<td>${project.id}</td>
<td>${project.title}</td>
<td>${project.startDate}</td>
<td>${project.endDate}</td>
<td>${project.status}</td>
<td>
Wijzigen<br/>
Verwijderen<br/>
Reviews<br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="form-actions">
Een nieuwe project toevoegen<br/>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</jsp:body>
</t:masterpage>

Categories