在AccountController中如果可以调用service的方法,即整合成功。
要先获得service的对象,再调方法
但是现在是web.xml中可以加载SpringMVC的配置文件,但是没有地方可以加载Spring.xml (applicationContext.xml)
没有加载则没有生效,没有把service和dao的对象加载到IoC容器中
所以要在服务器启动的时候把Spring的配置文件也要加载,这时就可以获取service对象,就可以在AccountController中进行注入
监听器用写吗?不用,Spring已经帮你搞定了。
在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置 ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。
<!-- Spring整合SpringMVC-->
<!-- 配置Spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
此时再编写AccountController方法,生成service层对象并调用其方法,完成整合
@Controller
@RequestMapping("/account")
public class AccountController {
//自动类型注入
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll() {
System.out.println("表现层controller:findAll is success");
//调用service的方法
accountService.findAll();
return "list";
}
}
整合方式: 启动tomcat服务器,加载配置文件Spring.xml (applicationContext.xml),在controller中注入service对象。
如果可以成功跳转到list.jsp则说明Spring整合SpringMVC成功