搭建第一个web项目:Struts+hibernate+spring配置(annotation)

Struts.xml的配置:

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

 2 <!DOCTYPE struts PUBLIC

 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

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

 5 

 6 <struts>

 7 

 8     <constant name="struts.enable.DynamicMethodInvocation" value="false" />

 9     <!-- 配置为开发模式 -->

10     <constant name="struts.devMode" value="true" />

11 

12     <!-- 配置后缀名为。action -->

13     <constant name="struts.action.extension" value="action,do" />

14 

15     <!-- 配置主题为simple 自己控制样式 -->

16     <constant name="struts.ui.theme" value="simple" />

17     

18     <!-- 默认所有的结果页面都存储在WEB-INF/content下,通过这个属性的值来改变到其他路径。 -->

19     <constant name="struts.convention.result.path" value="/jsp"/>

20     

21     <!-- 默认包路径包含action,actions,struts,struts2的所有包都会被struts作为含有Action类的路径来搜索。可以通过设置这个属性来修改这个配置。 -->

22     <constant name="struts.convention.package.locators" value="action"/>

23 

24     <!-- Add packages here -->

25 

26 </struts>

hibernate.cfg.xml的配置

 1 <!DOCTYPE hibernate-configuration PUBLIC

 2         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

 3         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 4 

 5 <hibernate-configuration>

 6 <session-factory>

 7     <!--数据库连接信息  -->

 8     <!-- <property name="dialect">org.hibernate.dialect.MySQl5InnoDBDialect</property>

 9         <property name="connection.driver_class">com.jdbc.mysql.Driver</property>

10         <property name="connection.username">root</property>

11         <property name="connection.password">123456</property>

12         <property name="connection.url">jdbc:mysql://localhost:3306/itcastoa0720</property> -->

13     <!--其他配置  -->

14     

15     <property name="hbm2ddl.auto">update</property>

16     <property name="show_sql">true</property>

17     <property name="format_sql">true</property>

18      <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个

19   bean-validation**包,但是找不到,所以beanvalitionFactory错误 -->

20     <property name="javax.persistence.validation.mode">none</property>

21 

22 </session-factory>

23 </hibernate-configuration>

其中,最后一条属性浪费了很多的时间,在进行hibernate和Spring整合的时候,通过junit测试一直出现“Unable to get the default Bean Validation”的错误,纠结了很久。

贴一下hibernate的官方解释:

  

By default, no configuration is necessary.

The Default group is validated on entity insert and update and the database model is updated accordingly based on the Default group as well.

You can customize the Bean Validation integration by setting the validation mode. Use thejavax.persistence.validation.mode property and set it up for example in your persistence.xml file or your hibernate.cfg.xml file. Several options are possible:

  • auto (default): enable integration between Bean Validation and Hibernate (callback and ddl generation) only if Bean Validation is present in the classpath.

  • none: disable all integration between Bean Validation and Hibernate

  • callback: only validate entities when they are either inserted, updated or deleted. An exception is raised if no Bean Validation provider is present in the classpath.

  • ddl: only apply constraints to the database schema when generated by Hibernate. An exception is raised if no Bean Validation provider is present in the classpath. This value is not defined by the Java Persistence spec and is specific to Hibernate.

 

applicationContext.xml的配置

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

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

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

 4     xmlns:context="http://www.springframework.org/schema/context"

 5     xmlns:tx="http://www.springframework.org/schema/tx"

 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 

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

 8                 http://www.springframework.org/schema/context 

 9                 http://www.springframework.org/schema/context/spring-context-2.5.xsd

10                 http://www.springframework.org/schema/tx 

11                 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

12 

13     <!-- 使用注解annotation必须添加的一项 -->

14     <context:annotation-config/>

15     <!-- 自动扫描与装配bean对象 子包和多包都可以 -->

16     <context:component-scan base-package="com.itcast.oa"></context:component-scan>

17 

18     <!-- 导入外部的properties文件 -->

19     <context:property-placeholder location="classpath:jdbc.properties" />

20 

21     <!-- 配置sessionFactory (默认是单例的)(原来是LocalSessionFactoryBean这个类 改成注解形式变成下面的类) -->

22     <bean id="sessionFactory"

23         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

24         

25         <!-- 指定hibernate配置文件路径 -->

26         <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

27         

28         <!-- 针对注解,找到它的实体类们 -->

29         <property name="packagesToScan">

30             <list>

31                 <value>com.itcast.oa.domain</value>

32             </list>

33         </property>

34         

35         <!-- 配置c3p0数据库连接池 -->

36         <property name="dataSource">

37             <!-- 匿名bean 只给datasource用的 不用写id name (通过反射调用默认构造方法构造bean) -->

38             <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">

39                 <!-- 数据连接信息 (通过该对象的getset的方法注入属性) -->

40                 <property name="jdbcUrl" value="${jdbcUrl}"></property>

41                 <property name="driverClass" value="${driverClass}"></property>

42                 <property name="user" value="${user}"></property>

43                 <property name="password" value="${password}"></property>

44                 <!-- 其他配置(数据库连接池的个数等) -->

45                 <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->

46                 <property name="initialPoolSize" value="3"></property>

47                 <!--连接池中保留的最小连接数。Default: 3 -->

48                 <property name="minPoolSize" value="3"></property>

49                 <!--连接池中保留的最大连接数。Default: 15 -->

50                 <property name="maxPoolSize" value="5"></property>

51                 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->

52                 <property name="acquireIncrement" value="3"></property>

53                 <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 

54                     0 -->

55                 <property name="maxStatements" value="8"></property>

56                 <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 

57                     0 -->

58                 <property name="maxStatementsPerConnection" value="5"></property>

59                 <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->

60                 <property name="maxIdleTime" value="1800"></property>

61             </bean>

62         </property>

63     </bean>

64 

65     <!-- 配置声明式事务管理(采用注解方式) -->

66     <bean id="txManager"

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

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

69     </bean>

70     <!-- 注解驱动 -->

71     <tx:annotation-driven transaction-manager="txManager" />

72 </beans>

web.xml的配置

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

 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"

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

 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

 5     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 6     <display-name></display-name>

 7     <welcome-file-list>

 8         <welcome-file>index.jsp</welcome-file>

 9     </welcome-file-list>

10 

11     <!-- 配置spring用于初始化容器对象的监听器 -->

12     <listener>

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

14     </listener>

15     <context-param>

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

17         <param-value>classpath:applicationContext*.xml</param-value>

18     </context-param>

19 

20     <!-- 配置Struts2核心过滤器 -->

21     <filter>

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

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

24     </filter>

25 

26     <filter-mapping>

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

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

29     </filter-mapping>

30 

31 </web-app>

通过以上四部分的配置,基本可以实现向数据库存储数据和在前台通过Struts显示页面:

通过注解的形式配置的action:

 1 package com.itcast.oa.action;

 2 

 3 import org.apache.struts2.convention.annotation.Action;

 4 import org.apache.struts2.convention.annotation.Namespace;

 5 import org.apache.struts2.convention.annotation.ParentPackage;

 6 import org.apache.struts2.convention.annotation.Result;

 7 

 8 import com.opensymphony.xwork2.ActionSupport;

 9 

10 @Namespace("/")

11 @ParentPackage("struts-default")

12 @Action(value = "/testAction", results = { @Result(name = "input", location = "test.jsp") })

13 public class TestAction extends ActionSupport {

14 

15     private static final long serialVersionUID = 1L;

16 

17     @Override

18     public String execute() throws Exception {

19         System.out.println("TestAction.execute()");

20         return "input";

21 

22     }

23 

24 }

对命名空间的理解与解释:

namespace:命名空间。从定义的.package.locators标示开始到包结束的部分,就是命名空间。举个例子:
Com.ustb.web.user.userAction的命名空间是:”/user”。Com.ustb.web.user.detail.UserAction的命名空间是:”/user/detail”。

对hibernate和spring整合的测试(使用junit测试):

测试代码:

package com.itcast.oa.test;



import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.junit.*;



public class SpringTest {

    private ApplicationContext ac = new ClassPathXmlApplicationContext(

            "applicationContext.xml");



    // 测试事务

    @Test

    public void testTransaction() throws Exception {

        TestService testService = (TestService) ac.getBean("testService");

        testService.saveTwouser();

    }

}

service类,交由spring容器进行管理:

package com.itcast.oa.test;



import javax.annotation.Resource;



import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;



import com.itcast.oa.domain.User;

@Service("testService")

public class TestService {

    

    @Resource//注入bean的资源,按名称,再按类型

    private SessionFactory sessionFactory;

    

    public void saveTwouser() {

        User user = new User();

        user.setDescription("123");

        user.setName("haojiahong");

        System.out.println("sessionfactoty gogogogogog===============================");

        Session session = sessionFactory.openSession();

        session.beginTransaction();

        session.save(user);

        session.getTransaction().commit();

        System.out.println("user saved=====================");

    }

}

user类,使用注解形式的实体类:

package com.itcast.oa.domain;



import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;



@Entity

@Table(name = "my_user")

public class User {

    @Id

    @GeneratedValue

    @Column(name = "USER_ID")

    private int id;

    @Column(name = "USER_NAME")

    private String name;

    @Column(name = "USER_DESCRIPTION")

    private String description;



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public String getDescription() {

        return description;

    }



    public void setDescription(String description) {

        this.description = description;

    }



    public int getId() {

        return id;

    }



    public void setId(int id) {

        this.id = id;

    }



}

最后运行MyEclipse,使用junit进行测试,在控制台打印结果为:

sessionfactoty gogogogogog===============================

Hibernate: 

    insert 

    into

        my_user

        (USER_DESCRIPTION, USER_NAME) 

    values

        (?, ?)

user saved=====================

成功!!!

至此整体框架搭建完成,开始实现每个功能,仿照传智播客中的oa管理进行升级更改。请看下一章喽^-^

 

你可能感兴趣的:(annotation)