JavaEE-Spring

JavaEE-Spring

[email protected]

2015年10月19日

 

1  目标:解耦逻辑和实现。

2 原理:逻辑由Bean和接口定义。实现由POJO定义。Bean和POJO之间由配置文件连接。

面向接口编程和组件解耦:IoC。

工作流:AOP。

可维护性更强,更新时只需更新Bean和配置文件,逻辑和接口无需更改。

Spring是于2003 年兴起的一个轻量级的Java 开源框架,面向接口编程和面向切面编程,减少模块间的耦合,提高可维护性和复用性。

参考:http://baike.baidu.com/subview/23023/11192342.htm

3 流程:Java Application和Java Web Application

3.1 JavaApplication:安装Spring库,构造接口和POJO。配置接口与实现之间的映射。使用Spring执行IoC。

3.1.1构建Java Application,创建lib文件夹。

3.1.2安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的lib目录下。配置BuildPath,将lib下的jar全部加入buildpath。

参考:http://blog.csdn.net/seven_3306/article/details/7881336

3.1.3 构造接口和POJO

//ISum.java

package lee;

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

public class Sumimplements ISum {

 

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

//Sum2.java

package lee;

 

public class Sum2implements ISum {

 

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b+1;

      }

 

}

3.1.4配置映射文件:id指定bean的id,class指定实现此bean的POJO。

id指xml的id(必须唯一,命名有限定),name是id的更加可读性名称。

参考:

http://stackoverflow.com/questions/874505/difference-between-using-bean-id-and-name-in-spring-configuration-file

//bean.java

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

 

 

      <bean id="sum" name="sum1"class="lee.Sum"></bean>

</beans>

3.1.5执行IoC:ApplicationContext加载配置文件,接口和bean实现逻辑。

//Test.java

package lee;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Test{

 

      public static void main(String[] args) {

           // TODO Auto-generated method stub

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

      }

 

}

结果:

可以将bean.xml修改为由Sum2实现,其它都不改,结果也相应改变。

3.2 Java Web:创建JavaEE,后台使用Spring(同JavaApplication)

3.2.1创建Dynamic Web Application

3.2.2安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的WEB-INF/lib目录下。将WEB-INF/lib下的jar加入buildpath。

3.2.3构造接口和POJO

参见:构造接口和POJO

3.2.4配置映射文件:id指定bean的id,class指定实现此bean的POJO。

参见:配置映射文件:id指定bean的id,class指定实现此bean的POJO。

3.2.5执行IoC:ApplicationContext加载配置文件,接口和bean实现逻辑。

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

3.2.6示例:手动控制Spring容器开闭

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID"version="3.1">

      <display-name>SpringWeb</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>

      <servlet>

           <servlet-name>HelloServlet</servlet-name>

           <servlet-class>lee.Hello</servlet-class>

      </servlet>

 

      <servlet-mapping>

           <servlet-name>HelloServlet</servlet-name>

           <url-pattern>/h</url-pattern>

      </servlet-mapping>

 

</web-app>

//Hello.java(Servlet)

package lee;

 

importjava.io.IOException;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

        System.out.println("Hello,Servlet!");//writeto server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

((ClassPathXmlApplicationContext)ctx).close();

      }

}

//ISum.java

package lee;

 

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("lee.Sum.Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           System.out.println("lee.Sum.sum(a,b)");

           return a+b;

      }

     

      public void init(){

           System.out.println("lee.Sum.init().");

      }

     

      public void destroy(){

           System.out.println("lee.Sum.destroy().");

      }

 

}

3.3 JavaWeb:Http服务器托管的Spring容器

3.3.1目标:Spring容器将随Http服务器的开启而开启。随着Http服务器的关闭而关闭。

3.3.2原理:在Servlet容器中添加Spring监听器,监听到容器启动后自动启动Spring容器。

3.3.3流程:在web.xml中设置Spring监听器,在applicationContext.xml中设置bean,创建bean的接口的实现类,在Servlet中使用bean。

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID"version="3.1">

      <display-name>SpringWeb</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>

      <servlet>

           <servlet-name>HelloServlet</servlet-name>

           <servlet-class>lee.Hello</servlet-class>

      </servlet>

 

      <servlet-mapping>

           <servlet-name>HelloServlet</servlet-name>

           <url-pattern>/h</url-pattern>

      </servlet-mapping>

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

 

</web-app>

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="person"class="lee.Person">       

      </bean>

      <bean id="sum"name="sum1" class="lee.Sum" init-method="init"

           destroy-method="destroy">

      </bean>

</beans>

 

//Hello.java(Servlet)

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring with web

           WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

      }

}

//ISum.java

package lee;

 

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("lee.Sum.Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           System.out.println("lee.Sum.sum(a,b)");

           return a+b;

      }

     

      public void init(){

           System.out.println("lee.Sum.init().");

      }

     

      public void destroy(){

           System.out.println("lee.Sum.destroy().");

      }

 

}

3.3.4方法:

3.3.4.1  设置Spring为web监听器:org.springframework.web.context.ContextLoaderListener。

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

3.3.4.2  加载Spring配置文件:默认加载applicationContext.xml。

如果有多个xml,则需要指定context-param参数contextConfigLoaction。

      <context-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>/WEB-INF/bean.xml</param-value>

      </context-param>

4 方法:bean实例化、映射文件配置

4.1 bean实例化:容器ApplicationContext

目标:根据配置文件,获取bean的信息,并能够实例化bean。

流程:创建配置文件,加载配置文件,实例化。

原理:使用反射和工厂模式实例化类。

方法:

能够实例化bean,称之为容器。最基本的是BeanFactory,一般使用其扩展子类ApplicationContext。

ApplicactionContext是BeanFactory的子类,提供Spring IoC所需的功能。有两个子类,FileSystemXmlApplicationContext(加载文件系统的配置文件)和ClassPathXmlApplicationContext(加载类路径中的配置文件)。

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

实例化:getBean()。

获取信息:getType(),containBean()。

4.2 映射文件配置:

4.2.1组织结构:根beans。其中是包含各个bean。

<?xmlversion="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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

 

 

      <bean id="sum" name="sum1"class="lee.Sum2"></bean>

      <bean id="calc" name="calc"class="lee.Calc">

<!--       <property name="sum"ref="sum"></property> -->

           <constructor-argname="sum" ref="sum"></constructor-arg>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

</beans>

4.2.2bean:目标是映射bean的id和实现类。

注意:bean的实现类必须具有无参数构造函数和getter/setter(如果有属性)。

id是唯一标识,作为xml的id存在,name是bean的更加人性名的命名(可选,如果只有name,没有id,则默认将name作为id)。

      <bean id="sum"name="sum1" class="lee.Sum2"></bean>

4.2.3注入方式:属性注入和构造参数注入。

4.2.3.1  属性注入:使用配置文件为属性成员设置值。

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc"name="calc" class="lee.Calc">

           <property name="sum"ref="sum"></property>

           <propertyname="a" value="10"></property>

           <propertyname="b" value="2"></property>

      </bean>

</beans>

//Calc.java

package lee;

 

public class Calcimplements ICalc {

      public Calc() {}

      public Calc(ISum sum) {

           super();

           this.sum = sum;

      }

      private int a;

      private int b;

      private ISumsum;

 

      public ISum getSum() {

           return sum;

      }

 

      public void setSum(ISum sum) {

           this.sum = sum;

      }

 

      public int getA() {

           return a;

      }

 

      public void setA(int a) {

           this.a = a;

      }

 

      public int getB() {

           return b;

      }

 

      public void setB(int b) {

           this.b = b;

      }

 

      @Override

      public int calc() {

           // TODO Auto-generated method stub

           return sum.sum(a, b);

      }

}

//ICalc.java

package lee;

 

public interfaceICalc {

      public int calc();

}

//ISum.java

package lee;

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

public class Sumimplements ISum {

 

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

//Hello.java

 

package lee;

 

importjava.io.IOException;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

           //spring ioc

           ICalc calc=ctx.getBean("calc",ICalc.class);

           System.out.print("calc()="+calc.calc());

           pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");

      }

}

4.2.3.2  构造参数注入:使用配置文件为构建函数设置值。

 

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc"name="calc" class="lee.Calc">

            <constructor-argname="sum" ref="sum"></constructor-arg>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

</beans>

//Calc.xml

package lee;

 

public class Calcimplements ICalc {

      public Calc() {}

      public Calc(ISum sum) {

           super();

           this.sum = sum;

      }

      private int a;

      private int b;

      private ISum sum;

 

      public ISum getSum() {

           return sum;

      }

 

      public void setSum(ISum sum) {

           this.sum = sum;

      }

 

      public int getA() {

           return a;

      }

 

      public void setA(int a) {

           this.a = a;

      }

 

      public int getB() {

           return b;

      }

 

      public void setB(int b) {

           this.b = b;

      }

 

      @Override

      public int calc() {

           // TODO Auto-generated method stub

           return sum.sum(a, b);

      }

}

//ICalc.java

package lee;

 

public interfaceICalc {

      public int calc();

}

//ISum.java

package lee;

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

public class Sumimplements ISum {

 

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

//Hello.java

 

package lee;

 

importjava.io.IOException;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

        System.out.println("Hello,Servlet!");//writeto server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

           //spring ioc

           ICalc calc=ctx.getBean("calc",ICalc.class);

           System.out.print("calc()="+calc.calc());

           pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");

      }

}

4.2.4实例化方式:singleton(默认),prototype(手动生成),request,session,globalsession()。

使用bean的scope属性指定。

<beanid="calc" name="calc" class="lee.Calc"scope="prototype">

4.2.5自动装配:byName,byType,constructor,no。

指定根据何种规则自动生成bean与属性配对。

      <bean id="calc"name="calc" class="lee.Calc"      autowire="byName">

4.2.6复杂属性:可以使用集合或复合属性。

4.2.7实例化顺序:先实例化依赖对象,最后实例化目标对象。

示例:Calc依赖Sum,则先初始化Sum,实例化Calc,然后设值。

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc" name="calc"class="lee.Calc">

           <propertyname="sum" ref="sum"></property>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

</beans>

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

 

//Calc.java

package lee;

 

public class Calcimplements ICalc {

      public Calc() {

           System.out.println("Calc().");

      }

      public Calc(ISum sum) {

           super();

           this.sum = sum;

      }

      private int a;

      private int b;

      private ISum sum;

 

      public ISum getSum() {

           return sum;

      }

 

      public void setSum(ISum sum) {

           this.sum = sum;

           System.out.println("setSum().");

      }

 

      public int getA() {

           return a;

      }

 

      public void setA(int a) {

           this.a = a;

      }

 

      public int getB() {

           return b;

      }

 

      public void setB(int b) {

           this.b = b;

      }

 

      @Override

      public int calc() {

           // TODO Auto-generated method stub

           return sum.sum(a, b);

      }

}

4.2.8实例化方法:默认实例化(构造函数)、工厂类静态方法、自定义工厂bean。

4.2.8.1  目标:根据配置文件,创建bean实例。

4.2.8.2  原理:指定方法调用类型的构造函数。

4.2.8.3  方法:

默认实例化:Spring默认调用bean的构造函数生成实例。

工厂静态方法:指定一个工厂类和静态方法创建实例。

      <bean id="calc" name="calc"class="lee.Person" factory-method="createCalc">

           <constructor-argvalue="sum2"></constructor-arg>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

自定义工厂bean:定义一个工厂bean,指定工厂bean和创建方法。

      <bean id="person"class="lee.Person"></bean>

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc" name="calc"factory-bean="person" factory-method="createCalc">

           <constructor-argvalue="sum2"></constructor-arg>

4.2.8.4  示例:静态工厂实例化

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc" name="calc"class="lee.Person" factory-method="createCalc">

           <constructor-argvalue="sum2"></constructor-arg>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

</beans>

//Person.java工厂类

package lee;

 

public classPerson {

      public static ICalc createCalc(String msg){

           System.out.println("createCalc="+msg);

           if (msg.equals("sum2")) {

                 System.out.println("createCalc=createsum2");

                 return new Calc(new Sum2());

           } else {

                 System.out.println("createCalc=createsum");

                 return new Calc(new Sum());

           }

      }

}

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

//Calc.java

package lee;

 

public class Calcimplements ICalc {

      public Calc() {

           System.out.println("Calc().");

      }

      public Calc(ISum sum) {

           super();

           this.sum = sum;

      }

      private int a;

      private int b;

      private ISum sum;

 

      public ISum getSum() {

           return sum;

      }

 

      public void setSum(ISum sum) {

           this.sum = sum;

           System.out.println("setSum().");

      }

 

      public int getA() {

           return a;

      }

 

      public void setA(int a) {

           this.a = a;

      }

 

      public int getB() {

           return b;

      }

 

      public void setB(int b) {

           this.b = b;

      }

 

      @Override

      public int calc() {

           // TODO Auto-generated method stub

           return sum.sum(a, b);

      }

}

//Hello.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

           //spring ioc

           ICalc calc=ctx.getBean("calc",ICalc.class);

           System.out.print("calc()="+calc.calc());

           pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");

      }

}

//Sum2.java

package lee;

 

 

public class Sum2implements ISum {

 

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b+1;

      }

 

}

 

4.2.8.5  示例:自定义工厂bean实例化

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="person"class="lee.Person"></bean>

      <bean id="sum"name="sum1" class="lee.Sum"></bean>

      <bean id="calc" name="calc"factory-bean="person" factory-method="createCalc">

           <constructor-argvalue="sum2"></constructor-arg>

           <property name="a"value="10"></property>

           <property name="b"value="2"></property>

      </bean>

</beans>

 //Person.java工厂类

package lee;

 

public classPerson {

      public ICalc createCalc(String msg) {

           System.out.println("createCalc="+msg);

           if (msg.equals("sum2")) {

                 System.out.println("createCalc=createsum2");

                 return new Calc(new Sum2());

           } else {

                 System.out.println("createCalc=createsum");

                 return new Calc(new Sum());

           }

      }

}

 //Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

 

}

//Calc.java

package lee;

 

public class Calcimplements ICalc {

      public Calc() {

           System.out.println("Calc().");

      }

      public Calc(ISum sum) {

           super();

           this.sum = sum;

      }

      private int a;

      private int b;

      private ISum sum;

 

      public ISum getSum() {

           return sum;

      }

 

      public void setSum(ISum sum) {

           this.sum = sum;

           System.out.println("setSum().");

      }

 

      public int getA() {

           return a;

      }

 

      public void setA(int a) {

           this.a = a;

      }

 

      public int getB() {

           return b;

      }

 

      public void setB(int b) {

           this.b = b;

      }

 

      @Override

      public int calc() {

           // TODO Auto-generated method stub

           return sum.sum(a, b);

      }

}

//Hello.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

           //spring ioc

           ICalc calc=ctx.getBean("calc",ICalc.class);

           System.out.print("calc()="+calc.calc());

           pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");

      }

}

4.2.9生命周期:容器初始化、Bean初始化

【BeanFactory后处理器】:如果有则在容器属性配置完成后执行postProcessBeanFactory()。

创建实例:new。

注入:执行属性注入。

【Bean后处理器】:如果有则在初始化前执行postProcessBeforeInitialization(),初始化完成后执行postProcessAfterInitialization()。

初始化方法:注入完成后执行init-method。

执行各自操作。

销毁方法:执行destroy-method。

4.2.9.1  初始化方法、销毁方法:执行bean在注入完成后执行的方法,在容器关闭时调用销毁方法。

方法:配置Bean的init-method为方法名,destroy-method为方法名。

参考:http://outofmemory.cn/java/spring/spring-bean-init-method-and-destroy-method

      <bean id="sum"name="sum1" class="lee.Sum" init-method="init"      destroy-method="destroy">

4.2.9.2  容器BeanFactory后处理器:实现BeanFactoryPostProcessor的bean。

目标:在spring容器初始化后执行动作。

原理:回调函数。

流程:创建BeanFactoryPostProcessor的实现类,配置Bean,Spring自动检测并执行。

            <beanclass="lee.FactoryBeanProcess"></bean>

4.2.9.3  Bean后处理器:实现BeanPostProcessor的bean。

目标:在Bean初始化后执行动作。

原理:回调函数。

流程:创建BeanPostProcessor的实现类,配置Bean,Spring自动检测并执行。

      <beanclass="lee.FactoryBeanProcess"></bean>

4.2.9.4  示例:

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="sum" name="sum1"class="lee.Sum" init-method="init"

           destroy-method="destroy">

      </bean>

      <bean class="lee.PostProcess"></bean>

      <beanclass="lee.FactoryBeanProcess"></bean>

</beans>

//Hello.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

          

           ((ClassPathXmlApplicationContext)ctx).close();

      }

}

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           return a+b;

      }

     

      public void init(){

           System.out.println("init().");

      }

     

      public void destroy(){

           System.out.println("destroy().");

      }

 

}

//PostProcess.java

package lee;

 

importorg.springframework.beans.BeansException;

importorg.springframework.beans.factory.config.BeanPostProcessor;

 

public classPostProcess implements BeanPostProcessor {

 

      @Override

      public ObjectpostProcessAfterInitialization(Object arg0, String arg1) throws BeansException{

           // TODO Auto-generated method stub

           System.out.println("postProcessAfterInitialization:"+arg0+","+arg1);

           return arg0;

      }

 

      @Override

      public ObjectpostProcessBeforeInitialization(Object arg0, String arg1) throws BeansException{

           // TODO Auto-generated method stub

           System.out.println("postProcessBeforeInitialization:"+arg0+","+arg1);

           return arg0;

      }

 

}

//FactoryPostProcess.java

package lee;

 

importorg.springframework.beans.BeansException;

importorg.springframework.beans.factory.config.BeanFactoryPostProcessor;

importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;

 

public classFactoryBeanProcess implements BeanFactoryPostProcessor {

 

      @Override

      public voidpostProcessBeanFactory(ConfigurableListableBeanFactory arg0) throwsBeansException {

           // TODO Auto-generated method stub

           System.out.println("postProcessBeanFactory:"+arg0);

      }

 

}

4.3 方法:资源访问Resource接口

目标:实现访问各种资源,统一处理。

原理:各种不同的资源实现Resource接口,统一操作方法。

方法:

UrlResource,ClassPathResource,FileSystemResource,ServletContextResource,InputStreamResource,ByteArrayResource。

打开文件:getFile(),getURL(),getInputStream()。

判断状态:isOpen()。

判断是否存在:exists()。

描述信息:getDescription()。

示例:

5 方法:工作流-面向切面编程AOP

5.1 目标:将工作流程进行整合,重组,复用类,生成各种类组成的工作流。

5.2 原理:重新编译和组织已有的基本功能类。

5.3 流程:配置切入点及操作,切入点执行时自动执行相应切入点操作。

参考:http://blog.csdn.net/z69183787/article/details/8110948

5.3.1安装AOP支持库:aspectj.jar,aopalliance.jar

下载aspectj.jar,解压后,将lib中的jar复制到工程的lib文件夹中,将jar加入到classpath。

下载aopalliance.jar,复制到工程的lib文件夹中,将jar加入到classpath。

5.3.2创建目标Bean:各种进行基础处理的Bean。

基本的Bean,执行常规操作。

//Sum.java

package lee;

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("lee.Sum.Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           System.out.println("lee.Sum.sum(a,b)");

           return a+b;

      }

     

      public void init(){

           System.out.println("lee.Sum.init().");

      }

     

      public void destroy(){

           System.out.println("lee.Sum.destroy().");

      }

}

5.3.3创建切面Bean:进行切面操作的Bean。

用于执行各个切入点的操作。

//Person.java

package lee;

importorg.aspectj.lang.JoinPoint;

importorg.aspectj.lang.ProceedingJoinPoint;

public classPerson {

      public Person() {

           super();

           // TODO Auto-generated constructorstub

           System.out.println("Person().");

      }    

      public void beforeAop(JoinPoint jp){

           System.out.println("beforeaop..."+jp.getTarget());

      }

      public void afterAop(JoinPoint jp){

           System.out.println("afteraop..."+jp.getTarget());

      }

}

5.3.4配置AOP:bean.xml中配置AOP。

配置切入点和切入操作。

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns:aop="http://www.springframework.org/schema/aop"

      xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd

           http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="person"class="lee.Person"></bean>

      <bean id="sum"name="sum1" class="lee.Sum" init-method="init"

           destroy-method="destroy">

      </bean>

      <aop:config>

           <aop:aspectref="person" id="afterAdviceAspect">

                 <aop:pointcutid="sumAop" expression="execution(* *.*(..))" />

                 <aop:beforemethod="beforeAop" pointcut-ref="sumAop" />

                 <aop:aftermethod="afterAop" pointcut-ref="sumAop" />

           </aop:aspect>

      </aop:config>

</beans>

5.4 方法:AOP概念和配置

5.4.1基本概念:aspect,pointcut,joinpoint,advice

切面aspect:一个具体的工作流单位。其中包括切入点,各个切入点对应的处理。

切入点pointcut:工作流的切入位置。具体指一个函数调用时机,可以设置多个,如servlet的url。可以在此切入点设置各种处理。

处理Advice:对切入点进行各种操作。可以在切入点之前、之后等多种时机设置处理。

连接点JoinPoint:工作流的具体切入的函数。

参数arg-names:连接点的实参,可以在这里指定名称。

参考:http://blog.csdn.net/zuyi532/article/details/7992323

http://blog.csdn.net/awangz/article/details/7750081

http://blog.csdn.net/wangpeng047/article/details/8556800

5.4.2aop配置

5.4.2.1  组织结构:根aop:config,其中包括各个aspect。

5.4.2.2  切面:aop:aspect;指定处理bean:ref。

5.4.2.3  切入点:aop:pointcut。指定处理模式execution。

5.4.2.4  处理:aop:before/after/around/after-returning/after-throwing。

5.4.2.5  around:指定整个切入点调用的处理。使用指定ProceedingJoinPoint作为参数。

proceed()将执行切入点调用。

      public ObjectaroundAop(ProceedingJoinPoint jp) throws Throwable{

           System.out.println("aroundaop:before..."+jp.getTarget());

            Object obj=jp.proceed();

           System.out.println("aroundaop:after..."+jp.getTarget());

           return obj;

      }

5.4.2.6  返回值处理:注意,需要增加一个returning指定返回值的参数名(在处理函数中使用)。

                 <aop:after-returningmethod="afterRet" pointcut-ref="sumAop"

                      returning="ret" />

      public void afterRet(JoinPoint jp,Object ret){

           System.out.println("afterRetaop..."+jp.getTarget()+"="+ret);

      }

5.4.2.7  异常处理:注意,需要增加一个throwing指定抛出的异常参数名(在处理函数中使用)。

                 <aop:after-throwingmethod="afterThrowing"

                      pointcut-ref="sumAop"throwing="ex"/>

 

      public void afterThrowing(JoinPoint jp,Throwable ex) throwsThrowable{

           System.out.println("throwingaop..."+jp.getTarget()+"="+ex.getMessage());

      }

5.5 示例:AOP控制基本Bean的流程

//bean.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns:aop="http://www.springframework.org/schema/aop"

      xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd

           http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="person"class="lee.Person">

          

      </bean>

      <bean id="sum"name="sum1" class="lee.Sum" init-method="init"

           destroy-method="destroy">

      </bean>

      <aop:config>

           <aop:aspect ref="person"id="afterAdviceAspect">

                 <aop:pointcutid="sumAop" expression="execution(* *.*(..))" />

                 <aop:beforemethod="beforeAop"

                      pointcut="execution(intlee.Sum.sum(..)); args(int,int)" />

                 <aop:aftermethod="afterAop" pointcut-ref="sumAop" />

                 <aop:aroundmethod="aroundAop" pointcut-ref="sumAop" />

                 <aop:after-returningmethod="afterRet" pointcut-ref="sumAop"

                      returning="ret"/>

                 <aop:after-throwingmethod="afterThrowing"

                      pointcut-ref="sumAop"throwing="ex" />

           </aop:aspect>

      </aop:config>

</beans>

//Person.java

package lee;

importorg.aspectj.lang.JoinPoint;

importorg.aspectj.lang.ProceedingJoinPoint;

public classPerson {

      public Person() {

           super();

           // TODO Auto-generated constructorstub

           System.out.println("Person().");

      }

 

      public ICalc createCalc(String msg) {

           System.out.println("createCalc="+msg);

           if (msg.equals("sum2")) {

                 System.out.println("createCalc=createsum2");

                 return new Calc(new Sum2());

           } else {

                 System.out.println("createCalc=createsum");

                 return new Calc(new Sum());

           }

      }

     

      public void beforeAop(JoinPoint jp){

           System.out.println("beforeaop..."+jp.getTarget()+"="+jp.getArgs().length+",0="+jp.getArgs()[0]);

      }

      public void afterAop(JoinPoint jp){

           System.out.println("after aop..."+jp.getTarget());

      }

      public ObjectaroundAop(ProceedingJoinPoint jp) throws Throwable{

           System.out.println("aroundaop:before..."+jp.getTarget());

           Object obj=jp.proceed();

           System.out.println("aroundaop:after..."+jp.getTarget());

           return obj;

      }

      public void afterThrowing(JoinPointjp,Throwable ex) throws Throwable{

           System.out.println("throwingaop..."+jp.getTarget()+"="+ex.getMessage());

      }

     

      public void afterRet(JoinPoint jp,Objectret){

           System.out.println("afterRetaop..."+jp.getTarget()+"="+ret);

      }

}

//ISum.java

package lee;

 

 

public interfaceISum {

      public int sum(int a,int b);

}

//Sum.java

package lee;

 

 

public class Sumimplements ISum {

      public Sum(){

           System.out.println("lee.Sum.Sum().");

      }

      @Override

      public int sum(int a, int b) {

           // TODO Auto-generated method stub

           System.out.println("lee.Sum.sum(a,b)");

           return a+b;

      }

     

      public void init(){

           System.out.println("lee.Sum.init().");

      }

     

      public void destroy(){

           System.out.println("lee.Sum.destroy().");

      }

 

}

//Hello.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Helloextends HttpServlet {

      protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

           // TODO Auto-generated method stub

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

          

           //spring

           ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");

           ISumsum=ctx.getBean("sum",ISum.class);

           System.out.print("1+2="+sum.sum(1,2));

           pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");

     

           ((ClassPathXmlApplicationContext)ctx).close();

      }

}

6 方法:事务- AOP的声明式事务管理tx

 

7 Spring Web 应用

7.1 目标:在Web应用中使用Spring,并由Web容器管理Spring。

7.2 原理:将Spring作为监听器,随Web容器开闭。

7.3 流程:

参见:Java Web:Http服务器托管的Spring容器

7.4 方法:web容器托管spring

7.4.1设置Spring为web监听器:org.springframework.web.context.ContextLoaderListener。

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

7.4.2加载Spring配置文件:默认加载applicationContext.xml。

如果有多个xml,则需要指定context-param参数contextConfigLoaction。

      <context-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>/WEB-INF/bean.xml</param-value>

      </context-param>

7.5 方法:Struts集成

7.5.1目标:使用struts能够调用spring的bean。

7.5.2原理:Struts使用内部扩展插件,将bean的生产托管到spring完成。

7.5.3流程:安装Struts的spring插件库,创建action的bean,在Struts的配置文件中使用Bean。

7.5.3.1  安装spring插件库:struts2-spring-plugin-2.3.16.jar,在Struts的lib目录下,copy到web-inf/lib下,并加入classpath。

7.5.3.2  创建action的bean:实现Action(本来就是个Action)的Bean(让Spring管理)。

注意:scope是prototype,每次请求才生成实例。

      <bean id="beanAction" class="lee.BeanAction" scope="prototype">

      </bean>

 

//BeanAction.java.xml

package lee;

 

importcom.opensymphony.xwork2.Action;

 

public classBeanAction implements Action {

//    private ISum sm;

      @Override

      public String execute() throws Exception {

           // TODO Auto-generated method stub

           System.out.println("lee.BeanAction.execute()...");

          

           return ERROR;

      }

7.5.3.3  在Struts的配置文件中使用Bean

//struts.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEstruts PUBLIC

    "-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"

   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

      <package name="lee"extends="struts-default">

           <action name="h"class="beanAction">

                 <resultname="success">/success.jsp</result>

                 <resultname="error">/error.jsp</result>

           </action>

      </package>

</struts>

7.5.3.4  示例

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID"version="3.1">

      <display-name>SpringWeb</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>

      <!-- spring -->

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

      <!-- struts -->

      <filter>

           <filter-name>struts2</filter-name>

           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

      </filter>

      <filter-mapping>

           <filter-name>struts2</filter-name>

           <url-pattern>/*</url-pattern>

      </filter-mapping>

</web-app>

//struts.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPEstruts PUBLIC

    "-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"

   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

      <package name="lee"extends="struts-default">

           <action name="h"class="beanAction">

                 <resultname="success">/success.jsp</result>

                 <resultname="error">/error.jsp</result>

           </action>

      </package>

</struts>

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="beanAction" class="lee.BeanAction" scope="prototype">

      </bean>

</beans>

//BeanAction.java

package lee;

 

importcom.opensymphony.xwork2.Action;

 

public class BeanAction implements Action {

//    private ISum sm;

      @Override

      public String execute() throws Exception {

           // TODO Auto-generated method stub

           System.out.println("lee.BeanAction.execute()...");

          

           return ERROR;

      }

7.5.4方法:自动装配

Spring默认使用name自动装配,如果property的name与bean的id相同,则自动进行装配,如果不同,则需要使用ref指定。

      <bean id="beanAction"class="lee.BeanAction" scope="prototype">

           <property name="sm" ref="sum"/>

      </bean>

7.5.5示例:

7.6 方法:Hibernate集成

7.6.1目标:使用Spring的Bean管理Hibernate的SessionFactory,业务只需要使用Session就好。

7.6.2原理:Spring IoC自动生成SessionFactory。

7.6.3流程:安装Spring和Hibernate库;配置Spring和Servlet;使用Spring配置Hibernate的SessionFactory;创建表的映射实体类和映射文件;在Servlet中使用SessionFactory。

7.6.3.1  安装Spring和Hibernate库

参见:安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的WEB-INF/lib目录下。将WEB-INF/lib下的jar加入buildpath。

参见:JavaEE-ORM映射器Hibernate.docx中Hibernate库安装部分。

7.6.3.2  配置Spring和Servlet:在Web.xml中配置。

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID"version="3.1">

      <display-name>SpringWeb</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>

      <servlet>

           <servlet-name>beanAction</servlet-name>

           <servlet-class>lee.BeanAction</servlet-class>

      </servlet>

      <servlet-mapping>

           <servlet-name>beanAction</servlet-name>

           <url-pattern>/h</url-pattern>

      </servlet-mapping>

     

      <!-- spring -->

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

</web-app>

7.6.3.3  Spring中配置Hibernate的SessionFactory:在applicationContext.xml中配置。

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="beanAction" class="lee.BeanAction"scope="prototype">

      <propertyname="sf" ref="sessionFactory"></property>

      </bean>

      <!-- hibernate -->

 <beanid="dataSource"

  class="org.springframework.jdbc.datasource.DriverManagerDataSource">

  <propertyname="driverClassName">

  <value>com.mysql.jdbc.Driver</value>

  </property>

  <propertyname="url">

  <value>jdbc:mysql://localhost:3306/hib4</value>

  </property>

  <property name="username">

  <value>root</value>

  </property>

  <propertyname="password">

  <value>sf</value>

  </property>

 </bean>

 <beanid="sessionFactory"

 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

  <propertyname="dataSource" ref="dataSource">

  </property>

  <propertyname="mappingResources">

   <list>

    <!--

     !这里填写hibernate的映射文件路径

    -->

   <value>lee/Employee.hbm.xml</value>

   </list>

  </property>

  <propertyname="hibernateProperties">

   <props>

    <!--

     配置Hibernate的方言

    -->

    <propkey="hibernate.dialect">

    org.hibernate.dialect.MySQLDialect

    </prop>

    <propkey="hibernate.hbm2ddl.auto">update</prop>

    <!--

     输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false

    -->

    <propkey="hibernate.show_sql">true</prop>

   </props>

  </property>

 </bean>

</beans>

7.6.3.4  创建表的实体类和映射文件:

//employee.java

package lee;

 

public classEmployee {

      private int id; 

      private String empName;

      private String empAddress;   

      private String empMobileNos;

      public int getId() {

           return id;

      }

      public void setId(int id) {

           this.id = id;

      }

      public String getEmpName() {

           return empName;

      }

      public void setEmpName(String empName) {

           this.empName = empName;

      }

      public String getEmpAddress() {

           return empAddress;

      }

      public void setEmpAddress(StringempAddress) {

           this.empAddress = empAddress;

      }

      public String getEmpMobileNos() {

           return empMobileNos;

      }

      public void setEmpMobileNos(StringempMobileNos) {

           this.empMobileNos = empMobileNos;

      }

 

}

//Employee.hbm.xml

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- GeneratedOct 29, 2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping>

    <class name="lee.Employee"table="employee">

        <id name="id"type="int">

            <column name="ID"/>

            <generatorclass="assigned" />

        </id>

        <property name="empName"type="java.lang.String">

            <columnname="EMP_NAME" />

        </property>

        <propertyname="empAddress" type="java.lang.String">

            <columnname="EMP_ADDRESS" />

        </property>

        <propertyname="empMobileNos" type="java.lang.String">

            <columnname="EMP_MOBILE_NOS" />

        </property>

    </class>

</hibernate-mapping>

7.6.3.5  在Servlet中使用SessionFactory

//BeanAction.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServlet;

 

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public classBeanAction extends HttpServlet {

     

      public void service(ServletRequestrequest, ServletResponse response) throws IOException{

        System.out.println("Hello,Servlet!");//writeto server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

           //spring with web

           WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);

           Session session=sf.openSession();

           // read

           {

                 Employee obj = (Employee)session.load(Employee.class, 1);

                 System.out.println(obj.getEmpName()+ ":" + obj.getEmpMobileNos());

                 System.out.println("yes,read");

           }

session.close();

 

           pw.println("<h1>Spring="+sf+"</h1>");

      }

}

7.6.4方法:

7.6.4.1  CRUD标准操作模板HibernateTemplate:Spring提供的Hibernate数据操作模板类。

注意:每条操作都自动执行事务。

参考:http://bbs.csdn.net/topics/370262876

//BeanAction.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServlet;

 

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.springframework.orm.hibernate3.HibernateTemplate;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public classBeanAction extends HttpServlet {

     

      public void service(ServletRequestrequest, ServletResponse response) throws IOException{

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

           //spring with web

           WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);

           Session session=sf.openSession();

           // read

           {

                 Employee obj = (Employee)session.load(Employee.class, 1);

                 System.out.println(obj.getEmpName()+ ":" + obj.getEmpMobileNos());

                 System.out.println("yes,read");

           }

           //template

           {

                 HibernateTemplate temp=new HibernateTemplate(sf);

                 Employee emp1=new Employee();

                 emp1.setId(18);

                 emp1.setEmpName("newEmp");

                 emp1.setEmpAddress("new addr");

                 emp1.setEmpMobileNos("1223378");

                 temp.save(emp1);//Create

                 Employee obj=temp.get(Employee.class, 18);// Retrieve

                 System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());

                 obj.setEmpAddress("updateaddr");

                 temp.update(obj);//Update

                 Employeeobj2=temp.get(Employee.class, 18);

                 System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());

                 temp.delete(emp1);//Delete

           }

          

           session.close();

 

           pw.println("<h1>Spring="+sf+"</h1>");

      }

}

//结果

7.6.4.2  自定义HibernateTemplate的执行方法:execute(session)

目标:在execute中自定义执行方法,可以使用Hibernate的原生方法。

方法:实现HibernateCallback接口,调用execute()。

//MyGet.java

package lee;

 

importjava.sql.SQLException;

 

importorg.hibernate.HibernateException;

importorg.hibernate.Session;

importorg.springframework.orm.hibernate3.HibernateCallback;

 

public class MyGet implementsHibernateCallback<Employee> {

 

      @Override

      public Employee doInHibernate(Sessionsession) throws HibernateException, SQLException {

           // TODO Auto-generated method stub

           System.out.println("HibernateCallback:getsession.");

           Employee obj = (Employee)session.load(Employee.class, 1);

           System.out.println(obj.getEmpName() +":" + obj.getEmpMobileNos());

           System.out.println("yes,Callback");

           return obj;

      }

 

}

//BeanAction.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServlet;

 

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.springframework.orm.hibernate3.HibernateTemplate;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public classBeanAction extends HttpServlet {

     

      public void service(ServletRequestrequest, ServletResponse response) throws IOException{

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

           //spring with web

           WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);

           Session session=sf.openSession();

           //template

           {

                 HibernateTemplate temp=newHibernateTemplate(sf);

                 temp.execute(new MyGet());

                 Employee emp1=new Employee();

                 emp1.setId(18);

                 emp1.setEmpName("newEmp");

                 emp1.setEmpAddress("newaddr");

                 emp1.setEmpMobileNos("1223378");

                 temp.save(emp1);

                 Employeeobj=temp.get(Employee.class, 18);

                 System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());

                 obj.setEmpAddress("updateaddr");

                 temp.update(obj);

                 Employeeobj2=temp.get(Employee.class, 18);

                 System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());

                 temp.delete(emp1);

           }

          

           session.close();

 

           pw.println("<h1>Spring="+sf+"</h1>");

      }

}

7.6.4.3  DAO快捷类HibernateDAOSupport:自动管理SessionFactory,Session,HibernateTemplate。

目标:自动管理SessionFactory的读写,Session的开关,HibernateTemplate的生成。

原理:封装固定操作。

流程:配置Spring和Servlet;使用Spring配置Hibernate的SessionFactory;创建表的映射实体类和映射文件;创建HibernateDaoSupport的Bean,直接使用HibernateTemplate;在Servlet中使用HibernateDaoSupport的Bean。

配置Spring和Servlet

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID"version="3.1">

      <display-name>SpringWeb</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>

      <servlet>

           <servlet-name>beanAction</servlet-name>

           <servlet-class>lee.BeanAction</servlet-class>

      </servlet>

      <servlet-mapping>

           <servlet-name>beanAction</servlet-name>

           <url-pattern>/h</url-pattern>

      </servlet-mapping>

     

      <!-- spring -->

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

</web-app>

使用Spring配置Hibernate的SessionFactory

//applicationContext.xml

<?xmlversion="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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="beanAction"class="lee.BeanAction" scope="prototype">

      </bean>

      <bean id="daoTest" class="lee.DaoTest"scope="prototype">

           <propertyname="sessionFactory"ref="sessionFactory"></property>

      </bean>

      <!-- hibernate -->

 <bean id="dataSource"

  class="org.springframework.jdbc.datasource.DriverManagerDataSource">

  <propertyname="driverClassName">

  <value>com.mysql.jdbc.Driver</value>

  </property>

  <property name="url">

  <value>jdbc:mysql://localhost:3306/hib4</value>

  </property>

  <property name="username">

   <value>root</value>

  </property>

  <property name="password">

   <value>sf</value>

  </property>

 </bean>

 <bean id="sessionFactory"

 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

  <property name="dataSource"ref="dataSource">

  </property>

  <propertyname="mappingResources">

   <list>

    <!--

     !这里填写hibernate的映射文件路径

    -->

   <value>lee/Employee.hbm.xml</value>

   </list>

  </property>

  <propertyname="hibernateProperties">

   <props>

    <!--

     配置Hibernate的方言

    -->

   <prop key="hibernate.dialect">

     org.hibernate.dialect.MySQLDialect

    </prop>

    <propkey="hibernate.hbm2ddl.auto">update</prop>

    <!--

     输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false

    -->

    <prop key="hibernate.show_sql">true</prop>

   </props>

  </property>

 </bean>

</beans>

创建表的映射实体类和映射文件

//employee.java

package lee;

 

public classEmployee {

      private int id; 

      private String empName;

      private String empAddress;   

      private String empMobileNos;

      public int getId() {

           return id;

      }

      public void setId(int id) {

           this.id = id;

      }

      public String getEmpName() {

           return empName;

      }

      public void setEmpName(String empName) {

           this.empName = empName;

      }

      public String getEmpAddress() {

           return empAddress;

      }

      public void setEmpAddress(StringempAddress) {

           this.empAddress = empAddress;

      }

      public String getEmpMobileNos() {

           return empMobileNos;

      }

      public void setEmpMobileNos(StringempMobileNos) {

           this.empMobileNos = empMobileNos;

      }

 

}

//Employee.hbm.xml

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- GeneratedOct 29, 2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping>

    <class name="lee.Employee"table="employee">

        <id name="id"type="int">

            <column name="ID"/>

            <generatorclass="assigned" />

        </id>

        <property name="empName"type="java.lang.String">

            <column name="EMP_NAME"/>

        </property>

        <propertyname="empAddress" type="java.lang.String">

            <columnname="EMP_ADDRESS" />

        </property>

        <propertyname="empMobileNos" type="java.lang.String">

            <columnname="EMP_MOBILE_NOS" />

        </property>

    </class>

</hibernate-mapping>

创建HibernateDaoSupport的Bean

//DaoTest.java

package lee;

 

importorg.springframework.orm.hibernate3.HibernateTemplate;

importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

public class DaoTest extends HibernateDaoSupport {

      public void test(){

           HibernateTemplate temp=getHibernateTemplate();

           System.out.println(temp);

           temp.execute(new MyGet());

           Employee emp1=new Employee();

           emp1.setId(18);

           emp1.setEmpName("new Emp");

           emp1.setEmpAddress("newaddr");

           emp1.setEmpMobileNos("1223378");

           temp.save(emp1);

           Employee obj=temp.get(Employee.class,18);

           System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());

           obj.setEmpAddress("updateaddr");

           temp.update(obj);

           Employeeobj2=temp.get(Employee.class, 18);

           System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());

           temp.delete(emp1);

      }

}

在Servlet中使用HibernateDaoSupport的Bean

//BeanAction.java

package lee;

 

importjava.io.IOException;

importjava.io.PrintWriter;

 

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServlet;

 

importorg.hibernate.Session;

importorg.hibernate.SessionFactory;

importorg.springframework.orm.hibernate3.HibernateTemplate;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

public classBeanAction extends HttpServlet {

     

      public void service(ServletRequestrequest, ServletResponse response) throws IOException{

       System.out.println("Hello,Servlet!");//write to server

        //write to client

      response.setContentType("text/html");

           PrintWriter pw=response.getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

           //spring with web

           WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());

           DaoTestdt=ctx.getBean("daoTest",DaoTest.class);

           dt.test();

            pw.println("<h1>Spring="+dt.getSessionFactory()+"</h1>");

      }

}

方法:

设置SessionFactory:使用Bean设置,将此bean设置为sessionFactory属性。

设置Session:自动管理,每次事件开闭一次。

7.7 事务控制:未成功测试???

目标:使用声明式的事务管理程序的事务流程。

原理:AOP进行事务控制。

流程:在bean配置中设置aop的事务切点,切点使用事务tx处理。

    <beanid="txManager"

           class="org.springframework.orm.hibernate3.HibernateTransactionManager">

           <property name="sessionFactory"ref="sessionFactory"></property>

      </bean>

<tx:adviceid="txAdvice" transaction-manager="txManager">

           <tx:attributes>

                 <tx:methodname="*" />

           </tx:attributes>

      </tx:advice>

      <aop:config >

           <aop:pointcutid="sumAop" expression="execution(* lee.DaoTest.test(..))"/>

           <aop:advisor pointcut-ref="sumAop"advice-ref="txAdvice"></aop:advisor>

      </aop:config>

方法:

参考:http://www.cnblogs.com/rushoooooo/archive/2011/08/28/2155960.html

事务性处理:<tx:advice>

事务管理器:需要设置sessionFactory属性。

示例:

7.8 方法:SSH集成

7.8.1目标:使用Spring管理IoC,使用Struts管理过滤器,使用Hibernate管理DAO。

7.8.2原理:Tomcat中设置Spring的监听器以自动启动Spring,设置Struts为全局过滤器,并使用Struts的Spring插件以使用Spring的Bean。在Spring中配置Hibernate集成Hibernate管理。

7.8.3流程:引入SSH的库;配置SSH;创建Action的Bean实现类;创建Hibernate的实体类和DAO Bean。

7.8.3.1  引入SSH库:

安装Struts库:参见:JavaEE-控制器Struts2.docx安装库部分。

安装spring插件库:struts2-spring-plugin-2.3.16.jar,在Struts的lib目录下,copy到web-inf/lib下,并加入classpath。

安装Spring库:参见:安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的lib目录下。配置BuildPath,将lib下的jar全部加入buildpath。

安装Hibernate库:参见:JavaEE-ORM映射器Hibernate.docx中Hibernate库安装部分

7.8.3.2  配置SSH

配置Spring监听器:在web.xml中配置。

配置Struts过滤器:在web.xml中配置过滤器,配置struts.xml。

配置Hibernate连接参数:在applicationContext.xml中配置。

//web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID" version="3.1">

      <display-name>SpringWeb</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>

      <!--spring -->

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

      <!-- struts -->

      <filter>

           <filter-name>struts2</filter-name>

           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

      </filter>

      <filter-mapping>

           <filter-name>struts2</filter-name>

           <url-pattern>/*</url-pattern>

      </filter-mapping>

//struts.xml

<?xml version="1.0"encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"

   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

      <package name="lee" extends="struts-default">

           <actionname="h" class="beanAction">

                 <resultname="success">/success.jsp</result>

                 <resultname="error">/error.jsp</result>

           </action>

      </package>

</struts>

//applicationContext.xml

</web-app>

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"

      xmlns:aop="http://www.springframework.org/schema/aop"

      xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd

           http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd

           http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

      <!--hibernate -->

      <beanid="dataSource"

           class="org.springframework.jdbc.datasource.DriverManagerDataSource">

           <propertyname="driverClassName">

                 <value>com.mysql.jdbc.Driver</value>

           </property>

           <propertyname="url">

                 <value>jdbc:mysql://localhost:3306/hib4</value>

           </property>

           <propertyname="username">

                 <value>root</value>

           </property>

           <propertyname="password">

                 <value>sf</value>

           </property>

      </bean>

      <beanid="sessionFactory"

           class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

           <propertyname="dataSource" ref="dataSource">

           </property>

           <propertyname="mappingResources">

                 <list>

                      <!-- !这里填写hibernate的映射文件路径 -->

                      <value>lee/Employee.hbm.xml</value>

                 </list>

           </property>

           <propertyname="hibernateProperties">

                 <props>

                      <!-- 配置Hibernate的方言 -->

                      <propkey="hibernate.dialect">

                            org.hibernate.dialect.MySQLDialect

                      </prop>

                      <propkey="hibernate.hbm2ddl.auto">update</prop>

                      <!-- 输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false-->

                      <propkey="hibernate.show_sql">true</prop>

                 </props>

           </property>

      </bean>

      <bean id="beanAction"class="lee.BeanAction" scope="prototype">

      </bean>

      <bean id="daoTest"class="lee.DaoTest" scope="prototype">

           <propertyname="sessionFactory"ref="sessionFactory"></property>

      </bean>

</beans>

 

7.8.3.3  创建Action的Bean实现类:继承ActionSupport

获取Bean:一种是使用属性在配置文件中设置,另一种是使用context直接获取。

WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());

DaoTestdt=ctx.getBean("daoTest",DaoTest.class);

//BeanAction.java

package lee;

 

import java.io.PrintWriter;

 

importorg.apache.struts2.ServletActionContext;

importorg.springframework.web.context.WebApplicationContext;

importorg.springframework.web.context.support.WebApplicationContextUtils;

 

importcom.opensymphony.xwork2.ActionSupport;

 

public class BeanAction extendsActionSupport {

      @Override

      public String execute() throws Exception {

           // TODO Auto-generated method stub

        //write to client

      ServletActionContext.getResponse().setContentType("text/html");

           PrintWriter pw=ServletActionContext.getResponse().getWriter();

           pw.println("<h1>Hello,I amServlet.</h1>");

           //spring with web

           WebApplicationContextctx=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());

           DaoTest dt=ctx.getBean("daoTest",DaoTest.class);

            dt.test();

           pw.println("<h1>Spring="+dt.getSessionFactory()+"</h1>");

           return null;

      }

}

7.8.3.4  创建Hibernate的实体类及映射和DAO Bean:

//Employee.java

package lee;

 

public class Employee {

      private int id; 

      private String empName;

      private String empAddress;   

      private String empMobileNos;

      public int getId() {

           return id;

      }

      public void setId(int id) {

           this.id = id;

      }

      public String getEmpName() {

           return empName;

      }

      public void setEmpName(String empName) {

           this.empName = empName;

      }

      public String getEmpAddress() {

           return empAddress;

      }

      public void setEmpAddress(String empAddress) {

           this.empAddress = empAddress;

      }

      public String getEmpMobileNos() {

           return empMobileNos;

      }

      public void setEmpMobileNos(String empMobileNos) {

           this.empMobileNos = empMobileNos;

      }

 

}

//Employee.hbm.xml

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated Oct 29,2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping>

    <class name="lee.Employee"table="employee">

        <id name="id"type="int">

            <column name="ID"/>

            <generatorclass="assigned" />

        </id>

        <property name="empName"type="java.lang.String">

            <columnname="EMP_NAME" />

        </property>

        <propertyname="empAddress" type="java.lang.String">

            <columnname="EMP_ADDRESS" />

        </property>

        <propertyname="empMobileNos" type="java.lang.String">

            <columnname="EMP_MOBILE_NOS" />

        </property>

    </class>

</hibernate-mapping>

//DaoTest.java

package lee;

 

importorg.hibernate.SQLQuery;

import org.hibernate.Session;

importorg.hibernate.Transaction;

importorg.springframework.orm.hibernate3.HibernateTemplate;

importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

public class DaoTest extends HibernateDaoSupport{

      public void test(){

           HibernateTemplate temp=getHibernateTemplate();

           System.out.println(temp);

           Employee emp1=new Employee();

           emp1.setId(18);

           emp1.setEmpName("new Emp");

           emp1.setEmpAddress("new addr");

           emp1.setEmpMobileNos("1223378");

           temp.save(emp1);

           Employee obj=temp.get(Employee.class, 18);

           System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());

           obj.setEmpAddress("update addr");

           temp.update(obj);

           Employee obj2=temp.get(Employee.class, 18);

           System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());

           temp.delete(emp1);

      }

}

7.8.4方法:

7.8.5示例:使用属性设置的方法管理SessionFactory

//Web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns="http://xmlns.jcp.org/xml/ns/javaee"

      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id="WebApp_ID" version="3.1">

      <display-name>SpringWeb</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>

      <!--spring -->

      <listener>

           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

      </listener>

      <!-- struts -->

      <filter>

           <filter-name>struts2</filter-name>

           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

      </filter>

      <filter-mapping>

           <filter-name>struts2</filter-name>

           <url-pattern>/*</url-pattern>

      </filter-mapping>

</web-app>

//Struts.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"

   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

      <package name="lee"extends="struts-default">

           <action name="login"class="lee.LoginAction">

                 <result name="success">/success.jsp</result>

                 <resultname="error">/error.jsp</result>

           </action>

           <action name="h"class="beanAction">

                 <resultname="success">/success.jsp</result>

                 <resultname="error">/error.jsp</result>

           </action>

      </package>

</struts>

//applicationContext.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

      <beanid="beanAction" class="lee.BeanAction"scope="prototype">

      <propertyname="sf" ref="sessionFactory"></property>

      </bean>

      <!--hibernate -->

 <bean id="dataSource"

  class="org.springframework.jdbc.datasource.DriverManagerDataSource">

  <propertyname="driverClassName">

  <value>com.mysql.jdbc.Driver</value>

  </property>

  <propertyname="url">

  <value>jdbc:mysql://localhost:3306/hib4</value>

  </property>

  <property name="username">

   <value>root</value>

  </property>

  <propertyname="password">

   <value>sf</value>

  </property>

 </bean>

 <beanid="sessionFactory"

 class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

  <propertyname="dataSource" ref="dataSource">

  </property>

  <propertyname="mappingResources">

   <list>

    <!--

     !这里填写hibernate的映射文件路径

    -->

   <value>lee/Employee.hbm.xml</value>

   </list>

  </property>

  <propertyname="hibernateProperties">

   <props>

    <!--

     配置Hibernate的方言

    -->

    <propkey="hibernate.dialect">

    org.hibernate.dialect.MySQLDialect

    </prop>

    <propkey="hibernate.hbm2ddl.auto">update</prop>

    <!--

     输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false

    -->

    <propkey="hibernate.show_sql">true</prop>

   </props>

  </property>

 </bean>

</beans>

//Employee.hbm.xml

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- Generated Oct 29,2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping>

    <class name="lee.Employee" table="employee">

        <id name="id"type="int">

            <column name="ID"/>

            <generatorclass="assigned" />

        </id>

        <property name="empName"type="java.lang.String">

            <columnname="EMP_NAME" />

        </property>

        <propertyname="empAddress" type="java.lang.String">

            <column name="EMP_ADDRESS"/>

        </property>

        <propertyname="empMobileNos" type="java.lang.String">

            <columnname="EMP_MOBILE_NOS" />

        </property>

    </class>

</hibernate-mapping>

 

//BeanAction.java

package lee;

 

import org.hibernate.Session;

importorg.hibernate.SessionFactory;

importcom.opensymphony.xwork2.Action;

 

public class BeanActionimplements Action {

      privateSessionFactory sf;

 

      @Override

      public String execute() throws Exception {

           // TODO Auto-generated method stub

           System.out.println("lee.BeanAction.execute()...");

           // hibernate

           SessionFactorysf=getSf();

           Session session = sf.openSession();

 

           // read

           {

                 Employee obj = (Employee)session.load(Employee.class, 1);

                 System.out.println(obj.getEmpName() + ":"+ obj.getEmpMobileNos());

                 System.out.println("yes,read");

           }

 

           return ERROR;

      }

 

      publicSessionFactory getSf() {

           return sf;

      }

 

      public voidsetSf(SessionFactory sf) {

           this.sf = sf;

      }

}

//Employee.java

package lee;

 

public class Employee {

      private int id; 

      private String empName;

      private String empAddress;   

      private String empMobileNos;

      public int getId() {

           return id;

      }

      public void setId(int id) {

           this.id = id;

      }

      public String getEmpName() {

           return empName;

      }

      public void setEmpName(String empName) {

           this.empName = empName;

      }

      public String getEmpAddress() {

           return empAddress;

      }

      public void setEmpAddress(String empAddress) {

           this.empAddress = empAddress;

      }

      public String getEmpMobileNos() {

           return empMobileNos;

      }

      public void setEmpMobileNos(String empMobileNos) {

           this.empMobileNos = empMobileNos;

      }

 

}

 

你可能感兴趣的:(java,spring,javaee,ssh)