概述

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

页面访问流程图

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

不使用Spring框架的开发流程

步骤如下:

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

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

 package com.hex.Dao;

 /**
* 学生Dao
* @author Administrator
*
*/
public interface IStudentDao {
public String GetStudentById(int id);
}
////////////////////////////////////////
package com.hex.Dao; /**
* 学生Dao
* @author Administrator
*
*/
public class StudentDaoImpl implements IStudentDao { /**
* 查询学生信息
*/
@Override
public String GetStudentById(int id) { return "hex";
} }
////////////////////////////////////////
package com.hex.Service; /**
* 学生服务接口
* @author Administrator
*
*/
public interface IStudentService {
public String GetStudentById(int id);
}
////////////////////////////////////////
package com.hex.Service; import com.hex.Dao.IStudentDao;
import com.hex.Dao.StudentDaoImpl; /**
* 学生服务实现类
* @author Administrator
*
*/
public class StudentServiceImpl implements IStudentService { private IStudentDao studentDao; public void setStudentDao(IStudentDao studentDao) {
this.studentDao = studentDao;
} @Override
public String GetStudentById(int id) {
//studentDao=new StudentDaoImpl();
return studentDao.GetStudentById(id);
} }

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

如下所示:

 package com.hex.servlet;

 /**
* 访问Servlet实现类
*/
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private IStudentService studentService; /**
* 构造函数 */
public HomeServlet() { } /**
* 初始化时声明studentService对象
*/
@Override
public void init() throws ServletException {
studentService=new StudentServiceImpl();
} /**
* Get方法
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String studentName=studentService.GetStudentById(0);
request.setAttribute("studentName", studentName);
request.getRequestDispatcher("/jsp/Home.jsp").forward(request, response);
} /**
* Post方法,此处和Get方法同
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

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

如下所示:

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

4. 缺点:

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

采用Spring的方式进行访问

0. Spring框需要的Jar包

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

 //日志包
commons-logging-1.1.1.jar
//spring核心包
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar
//web包
spring-web-4.0.6.RELEASE.jar

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

如下所示:

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

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

2. 配置Spring的IOC容器

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

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Dao依赖于数据库的底层操作,本示例不予深入 -->
<bean id="studentDao" class="com.hex.Dao.StudentDaoImpl"></bean>
<!-- Service层依赖于StudentDao,采用set的方式注入 -->
<bean id="studentService" class="com.hex.Service.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
</beans>

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

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

 package com.hex.servlet;

 /**
* Servlet实现类
*/
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private IStudentService studentService; public IStudentService getStudentService() {
return studentService;
} public void setStudentService(IStudentService studentService) {
this.studentService = studentService;
} /**
* 初始化时获取Sping的IOC容器中的bean对象
*/
@Override
public void init() throws ServletException {
//Web项目获取Spring上下文对象。
ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
studentService=(IStudentService)context.getBean("studentService");
}
}

4. 优势:

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

小知识

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

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

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

 <?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>FirstWebSpring</display-name>
<servlet>
<description>
</description>
<display-name>HomeServlet</display-name>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>com.hex.servlet.HomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/HomeServlet</url-pattern>
</servlet-mapping>
<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>
<!-- 配置容器地址 -->
<!-- 第一种方式如果要加载多个配置文件,可以写多个,如下所示:
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext2.xml
</param-value>
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- 配置spring-web.jar对应的监听器 ,Tomcat启动时,自动初始化IOC容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</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. [FPGA]Verilog利用PWM调制巧妙完成RGB三色彩虹呼吸灯(给简约的题目以美妙的解答)

    概述 实现彩虹呼吸灯 题目就是这么简短,但这是目前我碰到的最有意思的一道题目,因为他有无数种解决方法,并且每一种都是那么高级或者巧妙,比如 可以利用3路不同初相的PWM调制信号驱动三颗RGB灯重叠呼吸 ...

  2. 04_seaborn基本使用

    1.seaborn设置整体风格 seaborn提供5中主题风格: darkgrid whitegrid dark white ticks 主要通过set()和set_style()两个函数对整体风格进 ...

  3. Java多线程——线程间通信

    Java多线系列文章是Java多线程的详解介绍,对多线程还不熟悉的同学可以先去看一下我的这篇博客Java基础系列3:多线程超详细总结,这篇博客从宏观层面介绍了多线程的整体概况,接下来的几篇文章是对多线 ...

  4. Spring源码分析之AOP

    1.AOP简介 AOP即面向切面编程(Aspect Oriented Programming),通过预编译方式及运行期动态代理实现程序功能的统一维护的一种技术.使用aop对业务逻辑的各个部分进行隔离, ...

  5. 完全理解JS原型指南

    目录 Table of Contents generated with DocToc 目录 一.参考书籍和数据 二.原型,[[prototype]]和.prototype以及constructor 三 ...

  6. SpringBoot 使用IDEA 配置热部署

    在开发中稍微更改一点内容就要重启,很麻烦.这个时候使用Spring Boot的热部署就能解决你的问题. 上图: 1,在pom.xml文件中添加依赖: <dependency> <gr ...

  7. SpringBoot使用拦截器、过滤器、监听器

    目录 ## 过滤器 PS: 原文链接https://www.cnblogs.com/haixiang/p/12000685.html,转载请注明出处 过滤器简介 过滤器的使用 拦截器 拦截器介绍 使用 ...

  8. 【Luogu P3174 】[HAOI2009]毛毛虫

    前言: 虽然很多人和我想法一样 ,但我还是不要脸地写了这题解 题目: 链接 大意: 在一棵树上取一条最长链以及它所连接的结点总共的结点个数 思路: 取链: 用树形\(DP\)就可以轻而易举的解决这个问 ...

  9. Java数组与C/C++数组的区别

    C数组一维数组: 定义方式:datatype arrayname[length]数组是一个整体,在内存中是连续的: 初始化:1:可以只给部分赋值int a[5] = {1,2}; 剩下的自动赋值为02 ...

  10. PAT甲级专题|树的遍历

    PAT甲级专题-树的遍历 涉及知识点:树.建树.深度优先搜索.广度优先搜索.递归 甲级PTA 1004 输出每一层的结点,邻接表vector建树后.用dfs.bfs都可以边搜边存当前层的数据, #in ...