Spring整合SpringMVC的框架
- 目的:在controller中能成功的调用service对象中的方法。
- 在项目启动的时候,就去加载spring.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器默认加载WEB-INF目录下的applicationContext.xml的配置文
件,所以要配置全局的变量加载类路径下的配置文件)。
<!--配置Spring的监听器-->
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置加载类路径的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
- 在controller中注入service对象,调用service对象的方法进行测试
package com.qcby.controller;
import com.qcby.entity.Account;
import com.qcby.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
//依赖注入
@Autowired
private AccountService accountService;
/**
* 查询所有
* @return
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
System.out.println("表现层:查询所有");
//调用service的方法
List<Account> list = accountService.findAll();
ModelAndView mv = new ModelAndView();
mv.setViewName("suc");
return mv;
}
}