<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> 等等
定义web.xml
2.启动web项目时,web服务器首先会去读web项目的配置文件web.xml.读两个节点: <listener></listener> 和 <context-param></context-param> . 加载顺序为context-param -> listener -> filter -> servlet
1)配置context-param,应用范围内的初始化参数。
<!-- Spring ApplicationContext配置文件的路径,可使用通配符,用于后面的Spring Context Loader -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext.xml
</param-value>
</context-param>
在/src/main/resources目录下建applicationContext.xml。
<!-- 設定Spring Context的默认Profile 为了区分Test, Dev, Production环境 -->
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>production</param-value>
</context-param>
2)配置listener
spring除了添加必要的jar包,另外在web.xml一定要加上启动spring的监听器,这样配置在xml文件中的bean才会初始化
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文 .容器将<context-param></context-param>转化为键值对,并交给ServletContext。容器创建<listener>中的类实例,创建监听器。
4.设置字符过滤器
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
5.配置前端控制器(spring mvc的核心是DispatcherServlet),所以应用springmvc首先应该在web.xml中配置该servlet
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在/src/main/webapp/WEB-INF/spring-mvc.xml目录下新建spring-mvc.xml文件
6.定义出错页面访问初始页面
<!-- 出错页面定义 -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>