java - 我如何使用从表单中获得的值作为我的 dao 类中的变量?
问题描述
我正在尝试创建一个页面,我将在该页面上键入 java 之类的兴趣,然后我将从数据库中获取所有对 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;
}
我正在从数据库中获取所有课程,但在我的 daoimpl 课程中
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属性,这样您就可以根据兴趣显示课程。
推荐阅读
- typescript - 如何在接口对象数组中定义并使用它?
- android - 如何在android中构建正确的带有标头的datagramPacket?
- android - Android Studio 替换随机文件
- php - 我想在 Wordpress 主题中使用类别作为自定义类型
- algorithm - gcd算法时间复杂度
- google-sheets - 给定月份和年份的谷歌表格中的每日总计
- postman - Postman 中的动态基本身份验证凭据
- python - 在python中附加列表列表
- functional-programming - 你把这个称作什么?将其他函数的参数设置为固定的函数
- python - 混淆矩阵在 Keras 模型 tf==2.3.0 中产生不同的结果