基於Spring + SpringMVC + Hibernate (ssh)搭建JAVAEE框架

1、首先讓我們看一下搭建好的框架結構: 我們可以看到有controller層 和 service層 和 entity層

> 引用塊內容


1、我們先來看一下springMVC的配置文件applicationContext-mvc.xml:

<!-- 啓動註解驅動的Spring MVC功能,註冊請求url和註解POJO類方法的映射-->    
<mvc:annotation-driven/>

  <!-- 啓動包掃描功能,以便註冊帶有@Controller、@Service、@repository、@Component等註解的類成爲spring的bean -->
 <context:component-scan base-package="com.xiaoyu.ssh.*" >
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
 </context:component-scan>
 <!-- http請求映射關係配置 -->

<!-- 對模型視圖名稱的解析,在請求時模型視圖名稱添加前後綴 -->  
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/"/>
    <property name="suffix" value=".jsp"/>
    <!-- 註解驅動用來控制編譯靜態模型  -->
</bean>

 <!-- 對於靜態資源的的處理 -->
<context:annotation-config/> 
<mvc:default-servlet-handler/>
<mvc:resources location="/" mapping="/**/*.js"/>
<mvc:resources location="/" mapping="/**/*.css"/>
<mvc:resources location="/" mapping="/**/*.png"/>
<mvc:resources location="/" mapping="/**/*.gif"/>
<mvc:resources location="/" mapping="/**/*.jpg"/>

2、接下來我們再來看一下spring的配置文件applicationContext.xml:

<!-- 加載數據源 -->
<context:property-placeholder location="classpath:/resources/jdbc.properties"/>
<aop:aspectj-autoproxy/>

<!-- 配置spring的作用域 -->
<context:component-scan base-package="com">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- jdbc數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${driverClassName}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
</bean>

<!-- 配置Hibernate Seesion 把hibernate 的sessionFactory 交給spring處理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="hibernateProperties">  
           <props>  
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
               <prop key="hibernate.show_sql">true</prop>  
               <prop key="hibernate.format_sql">true</prop>  
               <prop key="hibernate.cache.use_second_level_cache">false</prop>
               <prop key="hibernate.cache.use_query_cache">false</prop>
               <prop key="current_session_context_class">thread</prop>
               <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
           </props>  
       </property>  
    <property name="packagesToScan">
        <list>
            <value>com.xiaoyu.ssh.entity</value>
        </list>
    </property>
 </bean>

<!-- 配置spring 事物聲明-->
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
      <property name="sessionFactory" ref="sessionFactory"></property>  
  </bean>  

<!-- 配置事物屬性 ,需要事物管理器-->  
 <tx:advice id="txAdvice" transaction-manager="transactionManager">  
     <tx:attributes>  
        <tx:method name="get*" read-only="true"/>  
        <tx:method name="purchase" propagation="REQUIRES_NEW"/>  
        <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>  
     </tx:attributes>  
 </tx:advice>  

3、接下來我們看一下jdbc數據源jdbc.properties:

#數據庫的路徑
url = jdbc:mysql://localhost/people
#連接mysql的驅動#
driverClassName = com.mysql.jdbc.Driver
#用戶名#
username = root
#密碼#
password = 123456

4、寫好spring和springMVC的些配置文件後我們再來看一下web.xml文件:

<context-param>  
       <param-name>contextConfigLocation</param-name>  
       <!-- 應用上下文配置文件 -->  
       <param-value>classpath*:resources/ApplicationContext.xml</param-value>  
    </context-param> 

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

    <!-- springMVC 核心控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath*:resources/ApplicationContext-MVC.xml</param-value>  
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- springMVC 核心控制器 -->

    <!--定義攔截器自動攔截中文字符編碼並設置爲UTF-8編碼-->
     <filter>
    <filter-name>charsetEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>


  <filter-mapping>
    <filter-name>charsetEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <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>

5、我們來實現entity層的代碼:

@Entity
@Table(name = "person")
public class Person {
    private int id;
    private String name;
    private int age;
    private int sex;

    public Person(){};

    @Id
    @Column(name="id",nullable=false,length=32,unique=true)
    @GenericGenerator(name="generator",strategy="uuid.hex")
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @Column(name="name",nullable=false,length=32)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Column(name="age",nullable=false,length=32)
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Column(name="sex",nullable=false,length=32)
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }

    public Person(int id, String name, int age, int sex) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "person [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

**

6、我們來實現service層代碼:

**

@Repository
public class ServiceDaoImplement {

    @Resource private SessionFactory sessionFactory;

    public Session getSessionFactory(){
        return sessionFactory.getCurrentSession();
    }

    public void addPerson(Person p){
        this.getSessionFactory().save(p);
    }

    public void deletePersonById(String id){
        this.getSessionFactory().createQuery("delete Person id = ?").setParameter(0, id).executeUpdate();
    }

    public Person findPersonById(String id){
        return  (Person) this.getSessionFactory().createQuery("from person where id = ?").setParameter(0, id).uniqueResult();
    }

    public void updatePerson(Person p){
        this.getSessionFactory().update(p);
    }

}

7、在Controller層調用這個方法:


    @Autowired private ServiceDao personDao;

    @RequestMapping(value="/text")
    public String test(){
        Person p = new Person ();
        p.setId(1);
        p.setName("張三");
        p.setAge(18);
        p.setSex(0);

        personDao.addPerson(p);
        System.out.println("添加用戶張三完畢!");
        return "/main";
    }

最後我們來看一下效果:

這裏寫圖片描述

最後:至此這個項目的框架就已經搭建完成了,通過spring和hibernate的整合使得controller和service層能夠很好的互通。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章