【问题标题】:Spring MVC - How to connect controller with service class and DAO?Spring MVC - 如何将控制器与服务类和 DAO 连接?
【发布时间】:2016-01-21 01:27:21
【问题描述】:

我正在学习 DAO 和服务,并尝试为一些测试 (JSP) 制作一个非常简单的 Web 应用程序。我创建了 DAO 和 Service 类,但是我怎样才能让它们相互协作呢?我想为了在文本字段中输入的值将保存在我的数据库中。这是一个代码:

学生道:

public void create(Student student);

学生DAOImpl:

private JdbcTemplate jdbcTemplate;

DataSource dataSource;

public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

public void create(Student student) {
    String query = "insert into studentdb.student (`name`, `age`) values (?,?)";
    Connection con = null;
    PreparedStatement ps = null;
    try{
        con = dataSource.getConnection();
        ps = con.prepareStatement(query);
        ps.setString(1, student.getName());
        ps.setString(2, student.getAge());
        int out = ps.executeUpdate();

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        try {
            ps.close();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

StudentService看起来和StudentDAO一模一样,这里是StudentServiceImpl:

StudentDAO studentDAO;


public void createStudent(Student student) {

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("studentconfig.xml");

    studentDAO = ctx.getBean("studentDAO", StudentDAO.class);

    student.setName(//value entered in webapp);
    student.setAge(//value entered in webapp);

    studentDAO.create(student);
}

这里是 MainController:

@RequestMapping(value="/home.html", method = RequestMethod.POST)
public ModelAndView homePagePost(Model model, @ModelAttribute("student") Student student1){

     model.addAttribute("student", student1);
     studentService.createStudent(student1);

    ModelAndView home = new ModelAndView("index");
    return home;
}

index.jsp:

<html>
<body>
<h2>Hello World!</h2>
<form action="/webapplication/home.html" method="post">
<input type="text" name="${student.name}"/>
<input type="text" name="${student.age} }"/>
<input type="submit" value="confirm!"/>
</form>
</body>
</html>

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    您需要 DI(依赖注入),或者更准确地说是实现这一点 - 控制反转。

    阅读此Spring DI 和Spring IoC containers。

    然后你需要指出你想在哪里使用注释将类自动装配到另一个中:

    @RestController
    public class LoginController {
        @Autowired
        private LoginService loginService;
    

    之后,您需要声明应用程序上下文要扫描哪些类以初始化所有类并注入所有依赖项,如下所示:

    <context:component-scan base-package="controller" />
    <context:component-scan base-package="service" />
    <context:component-scan base-package="dao" />
    

    因此,当您部署应用程序时,部署描述符将与应用程序上下文一起解析,然后扫描带有类及其依赖项的包,spring bean 容器将按照 IoC 原则初始化所有这些类,从最后到开始将这些类注入另一个类。

    一般你需要这样做,也许我跳过了一些东西,但这是原则。

    【讨论】:

      【解决方案2】:

      如前所述,一个好的解决方案是 Springs 依赖注入。

      以下是一些简化的信息: https://www.youtube.com/watch?v=6F3Cv1a7G0w

      这是你的 StudentDao 的实现:

      public interface StudentDao {
      
      }
      
      @Component
      public class StudentDaoImpl implements StudentDao {
         //TODO Your Code
      }
      

      这是你的 StudentService 的实现:

      @Service
      public interface StudentService { 
      
      }
      
      @Component
      public class StudentServiceImpl implements StudentService {
      
         @Autowired
         private StudentDao studentDao;
      
      }
      

      这是你的 StudentController 的实现:

      @Controller
      public interface StudentController { 
      
      }
      
      @Component
      public class StudentControllerImpl implements StudentController {
      
          @Autowired
          private StudentService studentService;
      
      }
      

      这是您的应用程序类(如果您使用的是 SpringBoot):

      @SpringBootApplication
      @ComponentScan("com.your.packages.controller", "com.your.packages.service", "com.your.packages.dao")
      public class Application {
      
          public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
          }
      }
      

      @ComponentScan 将告诉 Spring 在指定的包中搜索带有 @Component、@Service、@Controller 等注释的类。

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 2013-04-20
        • 2014-12-04
        • 2018-01-11
        • 1970-01-01
        • 2013-07-18
        • 2018-01-31
        相关资源
        最近更新 更多