一、Spring与Servlet的整合

  • 1.1:

    加入Spring的jar包。(要加web.jar包)

  • 1.2:

    •   java工程中获取Spring的上下文对象。

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml")来初始化Spring的上下文环境。

    •   WEB工程中初始化Spring的上下文环境。

在web.xml中添加监听器(ContextLoaderListener继承ContextLoader类,ContextLoader的静态常量CONFIG_LOCATION_PARAM = "contextConfigLocation"
    ContextLoaderListener读取Spring默认文件的位置就是"contextConfigLocation"的值,而这个值可以在web.xml <context-param>标签里设置contextConfigLocation):    如下:

  1. <listener>
  2. <listener-class>
  3. org.springframework.web.context.ContextLoaderListener
  4. </listener-class>
  5. </listener>

ContextLoaderListener读取Spring默认文件的位置:/WEB-INF/applicationContext.xml
    可以改变读取的位置。配置context-param参数。

  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>classpath:spring.xml</param-value>
  4. </context-param>
  • 如上配置,ContextLoaderListener类负责初始化spring的上下文环境,其路径为spring.xml。

  1.3  spring与servlet 的整合

  • sping有三大特性: IOC(控制反转)/DI(依赖注入)/AOP(面向切面编程、代理模式),而servlet是单例模式只实例一次,一般我们使用servlet的时候并不定义成员属性,因为成员属性会被所有用户所共用,而DI是通过属性注入的方式这样就会冲突,所以servlet+spring只能使用spring中的IOC和AOP两种特性进行编程。

  1.4  案例

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. <% String path=request.getContextPath(); %>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <a href="<%=path%>/servlet/exam"> spring和servlet整合</a>
  12. </body>
  13. </html>

web.xml

  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_2_5.xsd" id="WebApp_ID" version="2.5">
  3. <display-name>spring_servlet</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12.  
  13. <context-param>
  14. <param-name>contextConfigLocation</param-name>
  15. <param-value>classpath:spring.xml</param-value>
  16. </context-param>
  17.  
  18. <listener>
  19. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  20. </listener>

  21.  <!-- 这个servlet只用于创建ApplicationContext对象,并不被人访问所以无须配置servlet-mapping -->
      <servlet>
          <servlet-name>loderServlet</servlet-name>
          <servlet-class>servlet.LoderServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
     <!-- end -->
  22.  
  23. <servlet>
  24. <servlet-name>exam</servlet-name>
  25. <servlet-class>servlet.Example</servlet-class>
  26. </servlet>
  27.  
  28. <servlet-mapping>
  29. <servlet-name>exam</servlet-name>
  30. <url-pattern>/servlet/exam</url-pattern>
  31. </servlet-mapping>
  32.  
  33. </web-app>
  • spring.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xmlns:aop="http://www.springframework.org/schema/aop"
  8. xmlns:tx="http://www.springframework.org/schema/tx"
  9. xsi:schemaLocation="http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  15. http://www.springframework.org/schema/aop
  16. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  17.  
  18. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  19. <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver" ></constructor-arg>
  20. <constructor-arg index="1" name="url" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&amp;characterEncoding=UTF-8" ></constructor-arg>
  21. <constructor-arg index="2" name="username" value="root"></constructor-arg>
  22. <constructor-arg index="3" name="password" value=""></constructor-arg>
  23. </bean>
  24.  
  25. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  26. <property name="dataSource" ref="dataSource"></property>
  27. </bean>
  28.  
  29. <tx:advice id="advice_1" transaction-manager="transactionManager">
  30. <tx:attributes>
  31. <tx:method name="update*" propagation="REQUIRED"/>
  32. </tx:attributes>
  33. </tx:advice>
  34. <aop:config proxy-target-class="true">
  35. <aop:pointcut expression="execution(* service..*.*(..))" id="poin_1"/>
  36. <aop:advisor advice-ref="advice_1" pointcut-ref="poin_1"/>
  37. </aop:config>
  38.  
  39. <bean id="testService" class="service.TestService">
  40. <property name="roledao">
  41. <bean class="dao.RoleDao">
  42. <property name="dataSource" ref="dataSource"></property>
  43. </bean>
  44. </property>
  45. <property name="userdao">
  46. <bean class="dao.UserDao">
  47. <property name="dataSource" ref="dataSource"></property>
  48. </bean>
  49. </property>
  50. </bean>
  51.  
  52. </beans>
  • Example.java
  1. package servlet;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9.  
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.web.context.support.WebApplicationContextUtils;
  12.  
  13. import service.TestService;
  14.  
  15. public class Example extends HttpServlet{
  16.  
  17. @Override
  18. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19. this.doPost(req, resp);
  20. }
  21.  
  22. @Override
  23. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  24.  
  25. TestService testService=(TestService)LoderServlet.getBean("testService");
            
            testService.update();
  26.  
  27. }
  28. }
  • LoderServlet.java
  1. package servlet;
  2.  
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5.  
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.web.context.support.WebApplicationContextUtils;
  8. import org.springframework.web.jsf.el.WebApplicationContextFacesELResolver;
  9.  
  10. public class LoderServlet extends HttpServlet {
  11.  
  12. private static ApplicationContext context=null;
  13.  
  14. @Override
  15. public void init() throws ServletException {
  16.  
  17. System.out.println("初始化servlet");
  18.  
  19. if(context==null){
  20. context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
  21.  
  22. }
  23. }
  24.  
  25. public static Object getBean(String beanName){
  26. Object bean=null;
  27.  
  28. bean=context.getBean(beanName);
  29.  
  30. return bean;
  31. }
  32.  
  33. @Override
  34. public void destroy() {
  35. // TODO Auto-generated method stub
  36. super.destroy();
  37. }
  38.  
  39. }
  • TestService.java
  1. package service;
  2.  
  3. import dao.RoleDao;
  4. import dao.UserDao;
  5.  
  6. public class TestService {
  7. private UserDao userdao;
  8. private RoleDao roledao;
  9. public void setUserdao(UserDao userdao) {
  10. this.userdao = userdao;
  11. }
  12. public void setRoledao(RoleDao roledao) {
  13. this.roledao = roledao;
  14. }
  15.  
  16. public boolean update(){
  17.  
  18. boolean flag=false;
  19. try {
  20.  
  21. this.userdao.update_1();
  22. this.roledao.update_2();
  23. flag=true;
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. flag=false;
  27. throw new RuntimeException(e);
  28. }
  29.  
  30. return flag;
  31. }
  32. }
  • RoleDao.java
  1. package dao;
  2.  
  3. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  4.  
  5. public class RoleDao extends JdbcDaoSupport {
  6.  
  7. public void update_2(){
  8.  
  9. this.getJdbcTemplate().update("update role set role_name='aa' where role_id=1 ");
  10. this.getJdbcTemplate().update("update role set role_name='bb' where role_id=2 ");
  11. }
  12. }
  • UserDao.java
  1. package dao;
  2.  
  3. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  4.  
  5. public class UserDao extends JdbcDaoSupport{
  6.  
  7. public void update_1(){
  8.  
  9. this.getJdbcTemplate().update("update user set age=111 where userName='张三'");
  10. this.getJdbcTemplate().update("update user set age=111 where userName='李四'");
  11. }
  12. }

结果:

在Example类中调用TestService的update方法,这个方法又调用了UserDao的update_1方法和RoleDao的update_2方法,如果update_2方法出现异常,则update_1和update_2方法

同时回滚。 本例实现了servlet+spring的事务管理。

本题代码在:   链接

(四)spring+servlet 整合的更多相关文章

  1. Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档

    0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...

  2. Spring Boot2 系列教程(二十四)Spring Boot 整合 Jpa

    Spring Boot 中的数据持久化方案前面给大伙介绍了两种了,一个是 JdbcTemplate,还有一个 MyBatis,JdbcTemplate 配置简单,使用也简单,但是功能也非常有限,MyB ...

  3. Spring boot 入门四:spring boot 整合mybatis 实现CRUD操作

    开发环境延续上一节的开发环境这里不再做介绍 添加mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</grou ...

  4. (转)SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合

    http://blog.csdn.net/yerenyuan_pku/article/details/72231763 之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBa ...

  5. spring boot整合servlet、filter、Listener等组件方式

    创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...

  6. Spring Boot(十四):spring boot整合shiro-登录认证和权限管理

    Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...

  7. mybatis 学习笔记(四):mybatis 和 spring 的整合

    mybatis 学习笔记(四):mybatis 和 spring 的整合 尝试一下整合 mybatis 和 spring. 思路 spring通过单例方式管理SqlSessionFactory. sp ...

  8. Spring Boot 整合Servlet

    冷知识,几乎用不到 在spring boot中使用Servlet有两种实现方法: 方法一: 正常创建servlet,然后只用注解@ServletComponentScan package clc.us ...

  9. spring boot 2.x 系列 —— spring boot 整合 servlet 3.0

    文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...

随机推荐

  1. Beta冲刺(2/4)

    队名:福大帮 组长博客链接:https://www.cnblogs.com/mhq-mhq/p/11990570.html 作业博客 : https://edu.cnblogs.com/campus/ ...

  2. 对Zlib单元进行再封装

    对Zlib单元进行再封装 低版本DELPHI,如D7,ZLIB.pas单元封装的很简陋,因此有必要再封装,以增加使用的便利性. 高版本DELPHI,zlib.pas本身提供的接口已经相当完善. Zli ...

  3. PyMouse、PyKeyboard用python操作鼠标和键盘

    1.PyUserInput 简介 PyUserInput是一个使用python的跨平台的操作鼠标和键盘的模块,非常方便使用.支持的平台及依赖如下: Linux - Xlib Mac - Quartz, ...

  4. 记一次被DDoS敲诈的历程 糖果LUA FreeBuf 今天 0x01 背景

    记一次被DDoS敲诈的历程 糖果LUA FreeBuf 今天 0x01 背景

  5. tornado异步请求响应速度的实例测试

    tornado异步请求响应速度的实例测试

  6. 单硬盘根分区扩容(非LVM)

    单用户模式(内核参数末尾加single)救援模式(用光盘启动,选第三个,rescue installed system) 救援模式有什么作用: 1可以更改root密码:2恢复硬盘.文件系统操作:3系统 ...

  7. linux简单命令1

    1:-rw-r--r-- 第一位"-"表示文件类型("-"文件,"d"表示目录,"|"软连接,相当win7的快捷方式) ...

  8. Ubuntu 16.04 haproxy + keeplive

    WEB架构

  9. c# 调用mysql数据库验证用户名和密码

    使用mysql数据库验证用户名和密码时,如果用户名是中文,一直查不到数据 需要把app.config 中修改为 数据库统一设置utf8编码格式,连接数据库的时候设置编码Charset=utf8可以避免 ...

  10. python使用退格键时出现^H解决方法

    Linux 使用退格键时出现^H解决方法 1.临时解决 按ctrl 2.永久解决 基本现象 进入 Python shell,按下 Delete/Backspace 键: Python 3.5.2 (d ...