JavaWeb学习笔记(八):Spring集成web环境

  • 前面学习了一些spring的配置和注解的运用,今天来学习一下spring集成web环境

  • 和以前一样新建一个maven工程,写上所需要的实例类并在applicationContext.xml中进行配置

  • applicaContext.xml

<bean id="userDao" class="com.wang.dao.impl.UserDaoImpl"></bean>
    <bean id="userService" class="com.wang.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
  • web.xml中全局配置applicationContext.xml
 <!-- 全局配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
  • web.xml中配置全局监听,用于一次获取我们的配置文件。
<!-- 全局监听-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  • 创建配置servlet进行调用
  • web.xml中配置好servlet路径
 <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.wang.web.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>
  • 先进行原来的方式进行调用
public class UserServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    
    }
}
  • 用获取配置的监听里面的配置进行调用
public class UserServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext servletContext = this.getServletContext();
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = (UserService) app.getBean("userService");
        userService.save();
    }
}
  • 用原来的方式在每一个servlet中都要加载配置,配置文件基本不会变化进行了重复加载。每次都要输入配置文件,这个配置文件写死在代码中进行了强耦合。不利于代码的维护。
  • 下面的方式是spring给提供监听器的方式获取配置,只需要在web中进行配置,获取一次,能后进行全局的调用。修改配置只需要在web中进行修改,不需要去修改实际的代码

代码地址

猜你喜欢

转载自blog.csdn.net/weixin_43674113/article/details/121805203
今日推荐