[刘阳Java]_Spring整合Servlet【补充】_第14讲

这篇内容我们给大家介绍一下Spring框架如何整合Servlet。光看表面现象这个问题感觉没有什么太大难度,但是实际在整合过程中不是那么轻松

既然是以补充的方式来介绍,那么我们就直接上一个案例来说明整合实现的步骤

1. 案例要求

  • 通过Spring框架注解方式来打通控制层,业务逻辑层,数据访问层之间的依赖关系
  • 控制层采用Servlet来完成对用户请求与相应的处理
  • 然后在Servlet中通过@Autowired方式来依赖注入业务逻辑层
  • 业务逻辑层也是通过@Autowired方式来依赖注入数据访问层
  • 数据访问层采用Spring对JDBC支持方式来获取数据,编辑数据等操作

2. 技术难点

  • 如何让Servlet被Spring框架管理
  • 如何让Tomcat服务器加载Spring框架(即:如何加载Spring的配置文件)
  • 一旦Servlet被Spring框架管理,但是@Autowired注解是不能自动依赖注入业务逻辑层中的对象,这个该如何解决

3. Tomcat服务器加载Spring配置文件的实现步骤

  • 导入spring-web.jar包
  • 在web.xml文件中添加<listener.../>监听标签
  • 利用Spring框架的ContextLoaderListener来加载Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring</display-name>
  <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>

  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:com/gxa/spring/day02/spring-controller.xml</param-value>
  </context-param>

  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

4. 在Spring配置文件中使用<context:componet-scan .../>来扫描注解类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.gxa.spring.day02"></context:component-scan>

</beans> 

5. 创建UserServlet,通过覆盖HttpServlet中init方法来测试UserServlet是否被Spring框架所管理。因为@Autowired在Servlet中会失效,所以我们需要加入Spring框架中AutowireCapableBeanFactory来让@Autowired起作用。这一步非常重要

package com.gxa.spring.day02;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Controller
@WebServlet("/user.do")
public class UserServlet extends HttpServlet {

    /**
     * Servlet和Spring框架整合时候, Servlet本身是不能自动依赖注入
     * 解决方案:
     * 1. Spring框架提供的接口, AutowireCapableBeanFactory
     * 2. 就可以完成Servlet中依赖对象的自动装配
     */
    @Autowired
    private UserService userService;

    @Override
    public void init() throws ServletException {
        /**
         * 利用init方法来调用Spring容器BeanFactory
         * 看看UserServlet是否能够通过Spring容器获取对象
         */
        WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); //通过Web容器去得到BeanFactory对象
        AutowireCapableBeanFactory autowireCapableBeanFactory = wc.getAutowireCapableBeanFactory();
        autowireCapableBeanFactory.autowireBean(this);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        userService.getUser();
    }
}

6. 创建业务逻辑层接口和实现类

  • 注意:由于这篇文章是对Spring整合Servlet的一个补充,我就没有进行MVC的分包。所以后面创建的业务层代码和Dao层都和Controller在同一个包里面
  • 业务逻辑层实现类中要定义好注解的bean id名称,这样子Servlet通过@Autowired才能找到依赖的bean。不然会出现NoSuchDefinitionException
package com.gxa.spring.day02;

public interface UserService {
    public void getUser();
}
package com.gxa.spring.day02;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void getUser() {
        userDao.getUser();
    }

}

7. 创建Dao层接口和它的实现类。因为想Dao层能够获取到数据库中数据,所以这里用了JdbcTemplate来搞定数据查询

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.gxa.spring.day02"></context:component-scan>
    <context:property-placeholder location="classpath:com/gxa/spring/day02/jdbc.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${mysql.driver}"></property>
        <property name="url" value="${mysql.url}"></property>
        <property name="username" value="${mysql.username}"></property>
        <property name="password" value="${mysql.password}"></property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans> 
package com.gxa.spring.day02;

public interface UserDao {
    public void getUser();
}
package com.gxa.spring.day02;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void getUser() {
        String sql = "select * from student";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        System.out.println(list);
    }

}
时间: 2024-08-24 08:43:38

[刘阳Java]_Spring整合Servlet【补充】_第14讲的相关文章

[刘阳Java]_Spring常用注解介绍_第6讲

Spring的注解是在Spring2.5的版本中引入的,目的简化XML配置.在企业开发过程中使用注解的频率非常高,但是学习注解的前提是大家一定要对Spring基于XML配置要熟悉,这是我个人建议,因为在Spring2.0的版本时候是没有出现注解的使用 1. Spring常用注解如下 @Component @Autowired @Qualifier @Scope @Controller @Service @Repository 2. 使用Spring注解的时候一定关注Spring框架需要加入的包[

[刘阳Java]_Spring相关配置介绍_第5讲

这一节我们介绍一下Spring框架的相关常用配置 Spring依赖注入的两种方式(构造方法注入和setter方式注入) p-namespace方式配置 properties属性文件配置方式 集合对象配置方式 Bean scopes作用域(单例作用域和原生作用域) 1. Spring依赖注入方式 构造方法注入,它相当于在Spring初始化对象的时候调用构造方法将其对象之间的依赖关系给注入到对象中 先在类中定义好依赖对象 再去定义构造方法,通过在构造方法的参数中设置对象的依赖关系 最后在Spring

[刘阳Java]_SpringMVC方法静态资源_第9讲

有些时候我们在使用SpringMVC的时候造成无法访问静态资源文件(如:html,js,css,image等等).其主要的原因出在web.xml文件我们设置SpringMVC前端控制器的映射路径 <servlet> <servlet-name>spmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> &

[刘阳Java]_InternalResourceViewResolver视图解析器_第6讲

SpringMVC在处理器方法中通常返回的是逻辑视图,如何定位到真正的页面,就需要通过视图解析器 InternalResourceViewResolver是SpringMVC中比较常用视图解析器. 网上有一篇文章写得不错,我们也推荐大家去看看,当然要谢谢这篇博客提供的内容,转发地址:http://www.cnblogs.com/liruiloveparents/p/5054605.html 1. InternalResourceViewResolver的配置文件代码如下 <?xml versio

[刘阳Java]_Spring AOP基于XML配置介绍_第9讲

基于注解配置的Spring AOP固然简单,但是这节我们会给大家介绍基于XML配置的AOP是如何应用的.为什么这么说了,因为后面我们还会介绍到Spring对Dao操作的事务管理(基于AOP的XML文件方式来配置事务) 1. 基于XML文件方式来配置Spring的AOP,则我们需要的一些基本元素如下 <aop:config.../>,此标签很重要.它是在XML里配置AOP功能的核心标签 all aspect and advisor elements must be placed within a

[刘阳Java]_Spring入门_第1讲

Spring框架在企业中的使用非常多,优势明显.所以学好Spring框架肯定不言而喻.今天我们给大家介绍Spring的入门 1. 对于初学者来说我们要学习Spring框架中的哪些技术,这个有必要了解一下 Spring中的IOC Spring中的AOP Spring是如何对Dao层进行封装的 Spring对Java Web的技术支持 Spring配置文件中的各类标签元素的应用 Spring的注解 Spring的事务管理机制 Spring自身的MVC框架是如何应用的 2. 我们先不要去讲Spring

[刘阳Java]_Spring AOP入门_第7讲

AOP技术个人认为是能够完善(改善)面向对象编程OOP.为什么这么说,我们得先从AOP的概念说起,然后通过一段简单的例子加以佐证.这样子大家就可以慢慢地了解AOP 1. AOP概念 AOP为Aspect Oriented Programming的缩写,含义:面向切面的编程. 2. AOP主要作用是什么,为什么要提出AOP概念,AOP技术到底能用到哪些实际的开发场景里面去 AOP技术主要的用做在日志记录,性能统计,安全控制,事务处理,异常处理等等 例如日志功能,日志代码往往横向地散布在所有对象层次

[刘阳Java]_Spring MVC中ModelAndView的用法_第3讲

通过前面两篇博客我们已经学习到SpringMVC框架快速搭建和@RequestMapping注解的用法,今天我们来介绍一下SpringMVC框架中的ModelAndView.我个人理解对于快速入门SpringMVC可以按照如下思路学习 SpringMVC框架环境快速搭建 @RequestMapping的用法 ModelAndView的用法 整合Spring+SpringMVC+MyBatis 然后在学习SpringMVC框架高级部分

[刘阳Java]_Spring对Dao的支持_第10讲

Spring框架优秀就是在于MVC开发的时候一旦需要对底层的数据库操作,它可以很好的支持JDBC技术,还有现在主流的ORM框架(Hibernate, MyBatis)技术. 重点先介绍Spring对JDBC支持.在Spring对JDBC支持中提供了一个模板JdbcTemplate,此模板封装了对JDBC操作的许多方法,且消除了忽视资源释放而引起的漏洞 1. Spring对JDBC操作需要导入的jar(开发环境配置) common-dbcp.jar:提供数据源的第三方包 common-pool.j