ssm整合-Spring整合SpringMVC的框架04

Spring整合SpringMVC:启动tomcat服务器的时候,需要加载Spring的配置文件

ServletContext域对象

服务器启动的时候创建ServletContext对象,服务器关闭才销毁

一类监听器,监听ServletContext域对象创建和销毁的(执行一次,服务器启动执行)

 监听器去加载Spring的配置文件,创建WEB版本工厂,存储SercletContext对象

 在web.xml中添加监听器,并且配置文件的路径

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<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>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件(springmvc的核心配置文件)-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--启动服务器,创建该servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决中文乱码的过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

加载完spring的配置文件之后,通过自动注入把,ioc中的对象注入到变量中

 

package cn.itcast.controller;

import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/*
* 账户web
* */
@Controller
@RequestMapping("/account")
public class AccountController {

@Autowired
private AccountService accountService;

@RequestMapping("/findAll")
public String findAll() {
System.out.println("表现层:查询所有账户...");
// 调用service的方法
accountService.findAll();
return "list";
}
}
原文地址:https://www.cnblogs.com/kingchen/p/13027728.html