(四)spring+servlet 整合
一、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): 如下:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
ContextLoaderListener读取Spring默认文件的位置:/WEB-INF/applicationContext.xml
可以改变读取的位置。配置context-param参数。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</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
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<% String path=request.getContextPath(); %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="<%=path%>/servlet/exam"> spring和servlet整合</a>
</body>
</html>
web.xml
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>spring_servlet</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:spring.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 这个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 --> <servlet>
<servlet-name>exam</servlet-name>
<servlet-class>servlet.Example</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>exam</servlet-name>
<url-pattern>/servlet/exam</url-pattern>
</servlet-mapping> </web-app>
- spring.xml
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver" ></constructor-arg>
<constructor-arg index="1" name="url" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8" ></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <tx:advice id="advice_1" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* service..*.*(..))" id="poin_1"/>
<aop:advisor advice-ref="advice_1" pointcut-ref="poin_1"/>
</aop:config> <bean id="testService" class="service.TestService">
<property name="roledao">
<bean class="dao.RoleDao">
<property name="dataSource" ref="dataSource"></property>
</bean>
</property>
<property name="userdao">
<bean class="dao.UserDao">
<property name="dataSource" ref="dataSource"></property>
</bean>
</property>
</bean> </beans>
- Example.java
package servlet; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import service.TestService; public class Example extends HttpServlet{ @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { TestService testService=(TestService)LoderServlet.getBean("testService");
testService.update(); }
}
- LoderServlet.java
package servlet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.jsf.el.WebApplicationContextFacesELResolver; public class LoderServlet extends HttpServlet { private static ApplicationContext context=null; @Override
public void init() throws ServletException { System.out.println("初始化servlet"); if(context==null){
context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); }
} public static Object getBean(String beanName){
Object bean=null; bean=context.getBean(beanName); return bean;
} @Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
} }
- TestService.java
package service; import dao.RoleDao;
import dao.UserDao; public class TestService {
private UserDao userdao;
private RoleDao roledao;
public void setUserdao(UserDao userdao) {
this.userdao = userdao;
}
public void setRoledao(RoleDao roledao) {
this.roledao = roledao;
} public boolean update(){ boolean flag=false;
try { this.userdao.update_1();
this.roledao.update_2();
flag=true;
} catch (Exception e) {
e.printStackTrace();
flag=false;
throw new RuntimeException(e);
} return flag;
}
}
- RoleDao.java
package dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class RoleDao extends JdbcDaoSupport {
public void update_2(){
this.getJdbcTemplate().update("update role set role_name='aa' where role_id=1 ");
this.getJdbcTemplate().update("update role set role_name='bb' where role_id=2 ");
}
}
- UserDao.java
package dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class UserDao extends JdbcDaoSupport{
public void update_1(){
this.getJdbcTemplate().update("update user set age=111 where userName='张三'");
this.getJdbcTemplate().update("update user set age=111 where userName='李四'");
}
}
结果:
在Example类中调用TestService的update方法,这个方法又调用了UserDao的update_1方法和RoleDao的update_2方法,如果update_2方法出现异常,则update_1和update_2方法
同时回滚。 本例实现了servlet+spring的事务管理。
本题代码在: 链接
(四)spring+servlet 整合的更多相关文章
- Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档
0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...
- Spring Boot2 系列教程(二十四)Spring Boot 整合 Jpa
Spring Boot 中的数据持久化方案前面给大伙介绍了两种了,一个是 JdbcTemplate,还有一个 MyBatis,JdbcTemplate 配置简单,使用也简单,但是功能也非常有限,MyB ...
- Spring boot 入门四:spring boot 整合mybatis 实现CRUD操作
开发环境延续上一节的开发环境这里不再做介绍 添加mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</grou ...
- (转)SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合
http://blog.csdn.net/yerenyuan_pku/article/details/72231763 之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBa ...
- spring boot整合servlet、filter、Listener等组件方式
创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...
- Spring Boot(十四):spring boot整合shiro-登录认证和权限管理
Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...
- mybatis 学习笔记(四):mybatis 和 spring 的整合
mybatis 学习笔记(四):mybatis 和 spring 的整合 尝试一下整合 mybatis 和 spring. 思路 spring通过单例方式管理SqlSessionFactory. sp ...
- Spring Boot 整合Servlet
冷知识,几乎用不到 在spring boot中使用Servlet有两种实现方法: 方法一: 正常创建servlet,然后只用注解@ServletComponentScan package clc.us ...
- spring boot 2.x 系列 —— spring boot 整合 servlet 3.0
文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...
随机推荐
- Java List 和 Array 转化
List to Array List 提供了toArray的接口,所以可以直接调用转为object型数组 List<String> list = new ArrayList<Stri ...
- android中SpannableString之富文本显示效果
SpannableString其实和String一样,都是一种字符串类型,SpannableString可以直接作为TextView的显示文本,不同的是SpannableString可以通过使用其方法 ...
- osg::NodeVisitor osg3.4.0
x:-89.4588 y:-12.1245 z:-11.7807x:-89.4588 y:-6.44823 z:-11.7807x:-89.2164 y:-9.07239 z:-11.811x:-89 ...
- 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_07-用户认证-认证服务查询数据库-解析申请令牌错误信息
1.2.5.4 解析申请令牌错误信息 当账号输入错误应该返回用户不存在的信息,当密码错误要返回用户名或密码错误信息,业务流程图如下: 修改申请令牌的程序解析返回的错误: 由于restTemplate收 ...
- java设置北京时间的时区
java设置北京时间的时区 解决方法: 设置北京时间的时区,消除时间差. TimeZone timeZone = TimeZone.getTimeZone("GMT+8"); ...
- React Native 中的 Flex Box 的用法(水平布局、垂直布局、水平居中、垂直居中、居中布局)
版权声明:本文仅供个人学习. CSS 中 Flex-Box 语法链接 http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html Flex 是 ...
- (四)UML之顺序图(时序图)
一.概念 顺序图是交互图的一种形式,它显示对象沿生命线发展,对象之间随时间的交互表示为从源生命线指向目标生命线的消息.顺序图能很好地显示那些对象与其它那些对象通信,什么消息触发了这些通信,顺序图不能很 ...
- 【数据库开发】MySQL命令大全
1.连接Mysql 格式: mysql -h主机地址 -u用户名 -p用户密码1.连接到本机上的MYSQL. 首先打开DOS窗口,然后进入目录mysql\bin,再键入命令mysql -u root ...
- RH124-3 目录结构_转
在linux里安装的时候,是可以指定某分区装在某文件夹里 目录意义 /bin 存放命令,不可以在装系统单独挂载分区 /home /dev 存放硬件设备 不可以单独挂载分区 /boot 500M 和系统 ...
- jqGrid刷新不取消选中
也就是说,刷新前选中的行,刷新后还是选中 var jqGrid = $("#jqGrid"); // 获取刷新前选中的行id var jqGridRowid=jqGrid.jqGr ...