web.xml文件中配置如下:
- 可以通过
<param-value>classpath:application.xml</param-value>
显式指定spring配置文件的位置; - 如果不指定的话,spring的配置文件名必须是
applicationContext.xml
,且必须放在WEB-INF
下 <param-value>
中可以配置多个配置文件,每个配置文件路径使用,
分开,也可以使用*
通配符对相同前缀或者相同后缀的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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
在Servlet类中通过WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()
获取spring容器实例:
@WebServlet(name = "QueryStudentServlet",urlPatterns = {"/queryStudent"})
public class QueryStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
private WebApplicationContext getContext(){
return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
}