spring MVC 与 Hibernate

一、 导入Jar包

二、 配置applicationContext-core.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <!-- Spring IOC不扫描控制器 -->
    <context:component-scan base-package="cn">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>


    <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin://localhost:1521:orcl" />
        <property name="username" value="tsp" />
        <property name="password" value="admin" />
        <property name="maxActive" value="30" />
        <property name="initialSize" value="10" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>

        <property name="packagesToScan">
            <list>
                <value>cn.po</value>
            </list>
        </property>
    </bean>

    <!-- 事务管理器 -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>        
             <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="read*" read-only="true" />  
            <tx:method name="list*" read-only="true" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="modify*" propagation="REQUIRED" />  
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!-- 事务切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* cn.dao..*.*(..))"
            id="txPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

    <!-- 项目关闭清除session -->
    <context:annotation-config path="/"
        docBase="/" debug="0" reloadable="true">
            <Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
                <Store className="org.apache.catalina.session.FileStore"/>
            </Manager>
    </context:annotation-config>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>

三、 配置applicationContext-mvc.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- SpringMVC IOC描控制器 -->
    <context:component-scan base-package="cn"
        use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
            
    </context:component-scan>
    

    
    <!-- 开启SpringMVC注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>


    <!-- MVC配置资源映射 -->
    <mvc:resources location="/assets/" mapping="/assets/**" />
    <mvc:resources location="assets/" mapping="assets/**" />

    


    <!-- 视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

四、 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springMVC</display-name>
  <filter>
    <filter-name>charset</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>charset</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
      <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/applicationContext-core.xml</param-value>
  </context-param>
  <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:/applicationContext-mvc.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
   
    <welcome-file>listCity.do</welcome-file>

  </welcome-file-list>
  
</web-app>

五、 DAO 接口

package cn.dao;

import java.util.List;

import cn.po.Site;

public interface ISiteDAO {
    
    public Object findSite(Site site) throws Exception;
    
    public Object addSite(Site site) throws Exception;
    
    public Object deleteSite(Site site) throws Exception;
    
    public Object editSite(Site site) throws Exception;
    
    public List<Site> getList(); 

}

六、DAOImpl

package cn.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import cn.dao.ISiteDAO;
import cn.po.Site;

@Repository("siteDAO")
public class SiteDAOImpl implements ISiteDAO{
    
    @Resource(name = "hibernateTemplate")
    HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }


    @Override
    public Object findSite(Site site) throws Exception {
         return hibernateTemplate.get(Site.class, site.getsiteid());
    }

    @Override
    public Object addSite(Site site) throws Exception {
        
        hibernateTemplate.save(site);
        return null;
    }

    @Override
    public Object deleteSite(Site site) throws Exception {
        hibernateTemplate.delete(site);
        return "success";
    }

    @Override
    public Object editSite(Site site) throws Exception {
        hibernateTemplate.update(site);
        return null;
    }

    @Override
    public List<Site> getList() {
        
        
        return hibernateTemplate.execute(new HibernateCallback<List<Site>>() {

            @SuppressWarnings("unchecked")
            @Override
            public List<Site> doInHibernate(Session session)
                    throws HibernateException, SQLException {
                String hql="from Site";
                Query q=session.createQuery(hql);
                return (List<Site>)q.list();
            }
        });
    }


}

七、 SiteController

package cn.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.dao.ISiteDAO;
import cn.po.Site;


/**
 * 城市控制层
 * @author choiyubo
 *
 */
@Controller
public class SiteController {
    
    @Resource(name="siteDAO")
    ISiteDAO siteDAO;
    
   @RequestMapping("toAddSite.do")
    public String toAddsite(HttpServletRequest request,Site site) throws Exception{
        return "site-add";
    }
   @RequestMapping("addSite.do")
   public void addsite(Site site,HttpServletResponse response) throws Exception {
      siteDAO.addSite(site);
      response.sendRedirect("listSite.do");
    
}
   
   
   @RequestMapping("toUpdatesite.do")
   public String toUpdatesite(HttpServletRequest request,Site site) throws Exception {
       site=(Site) siteDAO.findSite(site);
       request.getSession().setAttribute("SITE", site);
       return "site-update";
   }
   @RequestMapping("updateSite.do")
   public void updatesite(Site site,HttpServletResponse response) throws Exception {
      siteDAO.editSite(site);
      response.sendRedirect("listSite.do");
}
   @RequestMapping("deleteSite.do")
   public void deletesite(Site site,HttpServletResponse response) throws Exception {
       siteDAO.deleteSite(site);
       response.sendRedirect("listSite.do");
   }
   
   @RequestMapping("listSite.do")
    public String getsiteList(HttpServletRequest request){
        List<Site> list=siteDAO.getList();
        request.getSession().setAttribute("SITELIST", list);//将结果放入session
        return "site-list";
    }
   
  

}

 

posted @ 2017-05-14 21:30  影子影  阅读(245)  评论(0编辑  收藏  举报