加入Spring的jar包。(要加web.jar包)html
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml")來初始化Spring的上下文環境。java
在web.xml中添加監聽器(ContextLoaderListener繼承ContextLoader類,ContextLoader的靜態常量CONFIG_LOCATION_PARAM = "contextConfigLocation"
ContextLoaderListener讀取Spring默認文件的位置就是"contextConfigLocation"的值,而這個值能夠在web.xml <context-param>標籤裏設置contextConfigLocation): 以下:mysql
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
ContextLoaderListener讀取Spring默認文件的位置:/WEB-INF/applicationContext.xml
能夠改變讀取的位置。配置context-param參數。git
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param>
index.jspweb
<%@ 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.xmlspring
<?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>
<?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>
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(); } }
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(); } }
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; } }
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 "); } }
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='李四'"); } }
結果:sql
在Example類中調用TestService的update方法,這個方法又調用了UserDao的update_1方法和RoleDao的update_2方法,若是update_2方法出現異常,則update_1和update_2方法express
同時回滾。 本例實現了servlet+spring的事務管理。 編程
本題代碼在: 連接app