在web应用中使用spring的基本思路

1、在pom.xml文件中必须加入如下配置

 1 <dependency>
 2      <groupId>org.springframework</groupId>
 3      <artifactId>spring-web</artifactId>
 4      <version>${spring.version}</version>
 5 </dependency>
 6 <dependency>
 7      <groupId>org.springframework</groupId>
 8      <artifactId>spring-webmvc</artifactId>
 9      <version>${spring.version}</version>
10 </dependency>

2、WEB应用下Spring的配置文件和非WEB应用下没有不同

3、如何创建IOC容器

  • 非web应用在main方法中直接创建
  • 应该在WEB应用被服务器加载时就创建IOC容器:在ServletContextListener#contextInitialized(ServletContextEvent sce)方法中创建IOC容器
  • 在web应用的其他组件中如何访问IOC容器:在ServletContextListener#contextInitialized(ServletContextEvent sce)方法中创建IOC容器后,可以把其放在ServletContext(即application域)的一个属性中
  • 实际上,spring配置文件的名字和位置也是可配置的,将其配置到当前web应用的初始化参数中(web.xml)

下面具体介绍实例:

1)首先新建Person类

 1 package com.wn.beans;
 2 
 3 public class Person {
 4     private String username;
 5 
 6     public void setUsername(String username) {
 7         this.username = username;
 8     }
 9 
10     public void hello() {
11         System.out.println("my name is:" + username);
12     }
13 }

2)spring配置文件与非web情况下一样

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6                            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 7                            http://www.springframework.org/schema/context 
 8                            http://www.springframework.org/schema/context/spring-context-3.2.xsd
 9                            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
10     <bean id="person" class="com.wn.beans.Person">
11         <property name="username" value="atguigu"></property>
12     </bean>
13 </beans>

 

3)创建SpringServletContextListener类使用ServletContextListener的监听器功能,在ServletContextListener#contextInitialized(ServletContextEvent sce)方法

    中创建IOC容器,然后将IOC容器放在ServletContext的一个属性中

 1 package com.wn.listener;
 2 
 3 import javax.servlet.ServletContext;
 4 import javax.servlet.ServletContextEvent;
 5 import javax.servlet.ServletContextListener;
 6 
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 /**
10  * Application Lifecycle Listener implementation class
11  * SpringServletContextListener
12  */
13 public class SpringServletContextListener implements ServletContextListener {
14     /**
15      * Default constructor.
16      */
17     public SpringServletContextListener() {
18         // TODO Auto-generated constructor stub
19     }
20     /**
21      * @see ServletContextListener#contextDestroyed(ServletContextEvent)
22      */
23     public void contextDestroyed(ServletContextEvent arg0) {
24         // TODO Auto-generated method stub
25     }
26     /**
27      * @see ServletContextListener#contextInitialized(ServletContextEvent)
28      */
29     public void contextInitialized(ServletContextEvent arg0) {
30         // 1、获取spring配置文件的名称和位置
31         ServletContext servletContext=arg0.getServletContext();
32         /**1、getInitParameter()方法是在GenericServlet接口中新定义的一个方法,用来调用初始化在web.xml中存放的参量。
33         如果通过在web.xml中的ServletContext上下文中定义参量,那么整个web应用程序中的servlet都可调用,web.xml中的格式为:
34          <context-param>
35                 <param-name>test</param-name>
36                 <param-value>Is it me</param-value>
37          < context -param>
38            2、调用<context-param>中的参量,调用格式为:
39         String name =getServletContext(). getInitParameter(“name”); 或
40         String name = getServletConfig().getServletContext().getInitParameter(“name”);
41          */
42         String config=servletContext.getInitParameter("configLocation");
43         // 2、创建IOC容器
44         ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
45         // 3、将IOC容器放在ServletContext的一个属性中
46         servletContext.setAttribute("ApplicationContext",ctx);
47     }
48 }

4)在web.xml文件中配置如下信息

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     version="2.5">
 6     <!-- 配置spring配置文件的名称和位置 -->
 7     <context-param>
 8         <param-name>configLocation</param-name>
 9         <param-value>applicationContext2.xml</param-value>
10     </context-param>
11     <!-- 启动IOC容器的ServletContextListener -->
12     <listener>
13         <listener-class>com.wn.listener.SpringServletContextListener</listener-class>
14     </listener>
15     <!-- 配置服务器运行路径 -->
16     <servlet>
17         <servlet-name>testServlet</servlet-name>
18         <servlet-class>com.wn.servlet.TestServlet</servlet-class>
19         <init-param>
20             <param-name>configLocation</param-name>
21             <param-value>classpath*:applicationContext2*.xml</param-value>
22         </init-param>
23         <load-on-startup>1</load-on-startup>
24     </servlet>
25     <servlet-mapping>
26         <servlet-name>testServlet</servlet-name>
27         <url-pattern>/TestServlet</url-pattern>
28     </servlet-mapping>
29 </web-app>

5)创建TestServlet类

 1 package com.wn.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletContext;
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import org.springframework.context.ApplicationContext;
13 
14 import com.wn.beans.Person;
15 
16 /**
17  * Servlet implementation class TestServlet
18  */
19 //@WebServlet("/TestServlet")
20 public class TestServlet extends HttpServlet {
21     private static final long serialVersionUID = 1L;
22     /**
23      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
24      *      response)
25      */
26     protected void doGet(HttpServletRequest request, HttpServletResponse response)
27             throws ServletException, IOException {
28         // 从application域对象中得到IOC容器的引用
29         ServletContext servletContext = getServletContext();
30         ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
31         // 从IOC容器中得到需要的bean
32         Person person = ctx.getBean(Person.class);
33         person.hello();
34         response.getWriter().append("Served at: ").append(request.getContextPath());
35     }
36 }

6)创建index.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <a href="TestServlet">TestServlet</a>
11 </body>
12 </html>

在浏览器中输入http://localhost:8080/second-ssmm/TestServlet,在console中打印出:

         my name is:atguigu

说明:配置浏览器路径可以通过上述在web.xml文件中配置,加上6)index.jsp运行,也可以去掉6)index.jsp和web中相关Servlet的配置,直接在5)中TestServlet类

        中第19行代码那样加注解@WebServlet("/TestServlet")

posted @ 2016-11-03 11:55  王小霞  阅读(2329)  评论(0编辑  收藏  举报