如何将从表单中获得的值用作dao类中的变量



我正在尝试创建一个页面,在该页面上我将像java一样键入感兴趣的内容,然后我将从感兴趣的数据库中获取所有行,因此我创建了这个表单元素

<input class="form-control" type="text" placeholder="Search..." name="interest"><br>

这是我在控制器中的映射

@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;
}

我正在从数据库中获取所有课程,但在我的daimpl类中

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;
}

在这个courseList方法中,我想使用兴趣,这样我就只能获取特定兴趣的课程,并在我的jsp上显示它们。我如何在daoImpl类中使用兴趣?

请查看下面的代码片段。

您已经实现了dao,只需要对该方法进行一些修改:-

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;
}

除此之外,您还需要实现一个服务类,从中可以调用dao方法来获取课程详细信息,如下所示:-

@Service
public class CourseService {
@Autowired
private CourseDAO courseDao;
public Map<String, String> getCourseList(String subjectInterest) throws SQLException, IOException {
return courseDao.getCourseList(subjectInterest);
}
}

在你的控制器中张贴这个需要改变一点,如下所示:-

@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";
}
}

最后,您需要在showCourses.jsp中循环courseList属性,这样您就可以根据兴趣显示课程。

最新更新