Reputation: 47
I am trying to create a page on which i will type the interest like java and then i will fetch all the rows from database which has interest as java so i have created this form element
<input class="form-control" type="text" placeholder="Search..." name="interest"><br>
This is my mapping in my controller
@ModelAttribute("courses")
public Map<String, String> getCourseList() throws SQLException, IOException {
return (new ServiceImpl()).getCourseList();
}
@RequestMapping(value="showCourses", method=RequestMethod.POST)
public ModelAndView showCourses(@RequestParam("interest") String interest) {
ModelAndView mv=new ModelAndView();
mv.addObject("interest",interest);
mv.setViewName("showCourses");
return mv;
}
I am fetching all the courses from the database but in my daoimpl class
public Map<String, String> courseList() throws SQLException, IOException {
connect();
Map<String, String> courseList = new HashMap<String, String>();
String sql = "SELECT * from course;";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
courseList.put(resultSet.getString("CourseName"), resultSet.getString("CourseName"));
}
return courseList;
}
in this courseList method i want to use the interest so that i can only fetch the courses which are of specific interest and show them on my jsp how can i use the interest in my daoImpl class?
Upvotes: 0
Views: 368
Reputation: 56
Please have a look in below code snippet.
you have already implemented dao just need little modification on that method :-
public Map<String, String> getCourseList(String subjectInterest) {
connect();
Map<String, String> courseList = new HashMap<String, String>();
String sql = "SELECT * from course where subInterest = ?";
statement.setString(1,subjectInterest);
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
courseList.put(resultSet.getString("CourseName"), resultSet.getString("CourseName"));
}
return courseList;
}
Along with this you need to implement one service class from where you can call your dao method for fetching the course details like below :-
@Service
public class CourseService {
@Autowired
private CourseDAO courseDao;
public Map<String, String> getCourseList(String subjectInterest) throws SQLException, IOException {
return courseDao.getCourseList(subjectInterest);
}
}
Post this in your controller need to change little bit something like below :-
@Controller
public class CourseController {
@Autowired
private CourseService courseService;
@RequestMapping(value = "/showCourses", method = RequestMethod.POST)
public String showCourses(@RequestParam("interest") String interest, Model model) throws SQLException, IOException {
model.addAttribute("interest", interest);
Map<String, String> courseList = courseService.getCourseList(interest);
model.addAttribute("courseList", courseList);
return "showCourses";
}
}
And finally you need to loop courseList attribute in your showCourses.jsp, So you will be able to show courses based on interest.
Upvotes: 1