首页 > 解决方案 > 我如何使用从表单中获得的值作为我的 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 类中使用兴趣?

标签: javaspring-bootspring-mvcjdbc

解决方案


请查看下面的代码片段。

您已经实现了 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属性,这样您就可以根据兴趣显示课程。


推荐阅读