概述

在日常的开发中Web项目集成Spring框架,已经越来越重要,而Spring框架已经成为web开发的主流框架之一。本文主要讲解Java开发Web项目集成Spring框架的简单使用,以及使用Spring和不使用Spring框架,两者之间的差异。 仅供学习分享使用,如有不足之处,还请指正。

页面访问流程图

本示例的页面访问流程图如下所示:

不使用Spring框架的开发流程

步骤如下:

1. 新增Service和Dao对应的类及接口实现

如下所示:在Service中对Dao进行了强关联

  1. package com.hex.Dao;
  2.  
  3. /**
  4. * 学生Dao
  5. * @author Administrator
  6. *
  7. */
  8. public interface IStudentDao {
  9. public String GetStudentById(int id);
  10. }
  11. ////////////////////////////////////////
  12. package com.hex.Dao;
  13.  
  14. /**
  15. * 学生Dao
  16. * @author Administrator
  17. *
  18. */
  19. public class StudentDaoImpl implements IStudentDao {
  20.  
  21. /**
  22. * 查询学生信息
  23. */
  24. @Override
  25. public String GetStudentById(int id) {
  26.  
  27. return "hex";
  28. }
  29.  
  30. }
  31. ////////////////////////////////////////
  32. package com.hex.Service;
  33.  
  34. /**
  35. * 学生服务接口
  36. * @author Administrator
  37. *
  38. */
  39. public interface IStudentService {
  40. public String GetStudentById(int id);
  41. }
  42. ////////////////////////////////////////
  43. package com.hex.Service;
  44.  
  45. import com.hex.Dao.IStudentDao;
  46. import com.hex.Dao.StudentDaoImpl;
  47.  
  48. /**
  49. * 学生服务实现类
  50. * @author Administrator
  51. *
  52. */
  53. public class StudentServiceImpl implements IStudentService {
  54.  
  55. private IStudentDao studentDao;
  56.  
  57. public void setStudentDao(IStudentDao studentDao) {
  58. this.studentDao = studentDao;
  59. }
  60.  
  61. @Override
  62. public String GetStudentById(int id) {
  63. //studentDao=new StudentDaoImpl();
  64. return studentDao.GetStudentById(id);
  65. }
  66.  
  67. }

2. 新增HomeServlet类,并需要通过new的方式声明studentService对象

如下所示:

  1. package com.hex.servlet;
  2.  
  3. /**
  4. * 访问Servlet实现类
  5. */
  6. public class HomeServlet extends HttpServlet {
  7. private static final long serialVersionUID = 1L;
  8.  
  9. private IStudentService studentService;
  10.  
  11. /**
  12. * 构造函数 */
  13. public HomeServlet() {
  14.  
  15. }
  16.  
  17. /**
  18. * 初始化时声明studentService对象
  19. */
  20. @Override
  21. public void init() throws ServletException {
  22. studentService=new StudentServiceImpl();
  23. }
  24.  
  25. /**
  26. * Get方法
  27. */
  28. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29.  
  30. String studentName=studentService.GetStudentById(0);
  31. request.setAttribute("studentName", studentName);
  32. request.getRequestDispatcher("/jsp/Home.jsp").forward(request, response);
  33. }
  34.  
  35. /**
  36. * Post方法,此处和Get方法同
  37. */
  38. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  39. // TODO Auto-generated method stub
  40. doGet(request, response);
  41. }
  42.  
  43. }

3. 前端页面进行访问即可

如下所示:

  1. <a href="../HomeServlet">点击进入</a>

4. 缺点:

此处形成了强依赖,即HomeServlet需要StudentServiceImpl对象。且StudentServiceImpl需要StudentDao的支持。

采用Spring的方式进行访问

0. Spring框需要的Jar包

Spring框架支持web项目需要的Jar包共7个,如下所示:

  1. //日志包
  2. commons-logging-1.1.1.jar
  3. //spring核心包
  4. spring-aop-4.0.6.RELEASE.jar
  5. spring-beans-4.0.6.RELEASE.jar
  6. spring-context-4.0.6.RELEASE.jar
  7. spring-core-4.0.6.RELEASE.jar
  8. spring-expression-4.0.6.RELEASE.jar
  9. //web包
  10. spring-web-4.0.6.RELEASE.jar

1. 需要在web.xml文件中配置Spring对应的监听器

如下所示:

applicationContext.xml 位于src目录,所以需要加上classpath,是Spring容器的配置文件

  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>classpath:applicationContext.xml
  4. </param-value>
  5. </context-param>
  6. <!-- 配置spring-web.jar对应的监听器 ,Tomcat启动时,自动初始化IOC容器 -->
  7. <listener>
  8. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  9. </listener>

2. 配置Spring的IOC容器

如下所示:依赖引用对象属性采用ref方式,如果是值对象,则采用value方式。

  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"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- Dao依赖于数据库的底层操作,本示例不予深入 -->
  7. <bean id="studentDao" class="com.hex.Dao.StudentDaoImpl"></bean>
  8. <!-- Service层依赖于StudentDao,采用set的方式注入 -->
  9. <bean id="studentService" class="com.hex.Service.StudentServiceImpl">
  10. <property name="studentDao" ref="studentDao"></property>
  11. </bean>
  12. </beans>

3. 在Servlet中,引入ApplicationContext对象,将Tomcat容器和Spring的IOC容器进行关联

如下所示:其他方法保持不变,增加studentService对象的getter和setter方法,然后通过容器注入的声明方式产生对象。在StudentServiceImpl中对StudengDao的依赖采用同样方法进行注入。

  1. package com.hex.servlet;
  2.  
  3. /**
  4. * Servlet实现类
  5. */
  6. public class HomeServlet extends HttpServlet {
  7. private static final long serialVersionUID = 1L;
  8.  
  9. private IStudentService studentService;
  10.  
  11. public IStudentService getStudentService() {
  12. return studentService;
  13. }
  14.  
  15. public void setStudentService(IStudentService studentService) {
  16. this.studentService = studentService;
  17. }
  18.  
  19. /**
  20. * 初始化时获取Sping的IOC容器中的bean对象
  21. */
  22. @Override
  23. public void init() throws ServletException {
  24. //Web项目获取Spring上下文对象。
  25. ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
  26. studentService=(IStudentService)context.getBean("studentService");
  27. }
  28. }

4. 优势:

此方式将Servlet和Service及Dao之间进行了解耦,灵活扩展性大大增强。

小知识

如果Spring的IOC容器文件有多个,可以采用Import的方式进行引入,如下所示:

  1. <!-- 第二种方式,采用import方式引入其他容器文件 -->
  2. <import resource="applicationContext2.xml"/>

在web.xml中配置servlet的方式,如下所示:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <display-name>FirstWebSpring</display-name>
  4. <servlet>
  5. <description>
  6. </description>
  7. <display-name>HomeServlet</display-name>
  8. <servlet-name>HomeServlet</servlet-name>
  9. <servlet-class>com.hex.servlet.HomeServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>HomeServlet</servlet-name>
  13. <url-pattern>/HomeServlet</url-pattern>
  14. </servlet-mapping>
  15. <welcome-file-list>
  16. <welcome-file>index.html</welcome-file>
  17. <welcome-file>index.htm</welcome-file>
  18. <welcome-file>index.jsp</welcome-file>
  19. <welcome-file>default.html</welcome-file>
  20. <welcome-file>default.htm</welcome-file>
  21. <welcome-file>default.jsp</welcome-file>
  22. </welcome-file-list>
  23. <!-- 配置容器地址 -->
  24. <!-- 第一种方式如果要加载多个配置文件,可以写多个,如下所示:
  25. <param-value>
  26. classpath:applicationContext.xml,
  27. classpath:applicationContext2.xml
  28. </param-value>
  29. -->
  30. <context-param>
  31. <param-name>contextConfigLocation</param-name>
  32. <param-value>
  33. classpath:applicationContext.xml
  34. </param-value>
  35. </context-param>
  36. <!-- 配置spring-web.jar对应的监听器 ,Tomcat启动时,自动初始化IOC容器 -->
  37. <listener>
  38. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  39. </listener>
  40. </web-app>

备注

绳锯木断,水滴石穿。

一起学Spring之Web基础篇的更多相关文章

  1. SQL必学必会笔记 —— 基础篇

    基础篇 SQL语言按照功能划分 DDL(DataDefinitionLanguage),也就是数据定义语言,它用来定义我们的数据库对象,包括 数据库.数据表和列.通过使用DDL,可以创建,删除和修改数 ...

  2. 从零开始学spring cloud(四) -------- 基础项目搭建

    1.创建一个spring cloud项目 1.1.使用工具创建--idea 点击creat new project,选择spring initializr 点击next,选择下一步 填入自己的Grou ...

  3. 从零开始学AB测试:基础篇

    什么是AB测试? 通俗点理解,AB测试就是比较两个东西好坏的一套方法,这种A和B的比较在我们的生活和人生中非常常见,所以不难理解.具体到AB测试这个概念,它和我们比较哪个梨更大.比较哪个美女更漂亮.比 ...

  4. MyEclipse配置Spring框架(基础篇)

    一.新建项目,添加spring的相关jar包等 二.创建相关类以及属性和方法 Student.java package com.yh; public class Student implements ...

  5. java-随学随记之基础篇

    一.Java是一门高级语言,具有跨平台性(一次编译到处运行) 1.javac.exe命令,编译器   javac 源文件名.java 2.java.exe命令,启动虚拟机 java 类名 二.环境变量 ...

  6. 58. Spring Boot国际化(i18n)【从零开始学Spring Boot】

    国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式.它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素.换言之,应用程序的功能和代码设计考虑在不 ...

  7. Linux系统文件系统及文件基础篇

    学习Linux,重难点在于掌握不同类别的文件系统及其作用.通过对Linux系统的安装,我们首先来了解下Linux系统里各个目录文件夹下的大致功能:主要的目录树的有/./root./home./usr. ...

  8. 54. spring boot日志升级篇—logback【从零开始学Spring Boot】

    在<44. Spring Boot日志记录SLF4J>章节中有关相关的介绍,这里我们在深入的了解下logback框架. 为什么要使用logback ? --在开发中不建议使用System. ...

  9. 50. Spring Boot日志升级篇—log4j【从零开始学Spring Boot】

    如果你使用的是spring boot 1.4.0版本的话,那么你可能需要配合以下文章进行学习 90.Spring Boot 1.4 使用log4j错误[从零开始学Spring Boot] Log4j是 ...

随机推荐

  1. Python函数的默认参数的设计【原创】

    在Python教程里,针对默认参数,给了一个“重要警告”的例子: def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print( ...

  2. 【日常错误】spring-boot配置文件读取不到

    最近在用spring-boot做项目时,遇到自定义的配置文件无法读取到的问题,通过在appcation.java类上定义@PropertySource(value = {"classpath ...

  3. 2753:走迷宫(dfs+初剪)//可以说是很水了。。。

    总时间限制:  1000ms 内存限制:  65536kB 描述 一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走:有的格子是空地,可以走.给定一个迷宫,求从左上角走到右下角最少需要走多少步(数 ...

  4. 【Android - 控件】之MD - CoordinatorLayout的使用

    CoordinatorLayout是Android 5.0新特性——Material Design中的一个布局控件,主要用来协调各个子视图之间的工作,也可以用来作为顶部布局.CoordinatorLa ...

  5. kubeadm join 超时报错 error execution phase kubelet-start: error uploading crisocket: timed out waiting for the condition

    解决: swapoff -a kubeadm reset systemctl daemon-reload systemctl restart kubelet iptables -F && ...

  6. CCNA 之 八 交换基础 VLAN TRUNK VTP

    交换基础 主要知识点: 二层交换基础 Vlan的概念 Trunk的概念 VTP 二层交换基本配置 首先来看下园区网分层结构 交换机的主要功能: Address learning 学习MAC地址 会维护 ...

  7. 能避开很多坑的mysql面试题,你知道吗?

    最近有一些朋友问我一些mysql相关的面试题,有一些比较基础,有些比较偏.这里就总结一些常见的mysql面试题吧,都是自己平时工作的总结以及经验.大家看完,能避开很多坑.而且很多问题,都是面试中也经常 ...

  8. C# 自然周,月,季度计算。

    /// <summary> /// 判断时间是否和服务器时间是一天 /// </summary> /// <param name="cs">&l ...

  9. KubeSphere 日志备份与恢复实践

    为什么需要日志备份 KubeSphere 日志系统使用 Fluent Bit + ElasticSearch 的日志采集存储方案,并通过 Curator 实现对 Index 的生命周期管理,定期清理久 ...

  10. openlayers5-webpack 入门开发系列结合 echarts4 实现散点图(附源码下载)

    前言 openlayers5-webpack 入门开发系列环境知识点了解: node 安装包下载webpack 打包管理工具需要依赖 node 环境,所以 node 安装包必须安装,上面链接是官网下载 ...