WEB开发框架配置文件和各层注解(SpringMVC + Spring + Hibernate)

7 篇文章 0 订阅
1 篇文章 0 订阅

SpringMVC + Spring + Hibernate

本文主要记录: 框架需要的配置文件的配置 + Dao层写法 + Service层写法 + Controller写法


spring的配置文件还有spring mvc的配置文件如下:


applicationContext.xml


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  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" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.          http://www.springframework.org/schema/context  
  8.          http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  9.          http://www.springframework.org/schema/tx  
  10.          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11.          http://www.springframework.org/schema/aop   
  12.          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
  13.   
  14.     <!-- 他的作用是隐式地向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor、   
  15.         CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor、  
  16.         RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。 -->  
  17.     <context:annotation-config />  
  18.       
  19.     <!-- 关于所在包注解的自动扫描配置(也会注入上面4个BeanPostProcessor)-->  
  20.     <context:component-scan base-package="cn.edu.fjnu.hubmis" />  
  21.       
  22.     <!-- 数据库对应的配置信息 -->  
  23.     <context:property-placeholder location="classpath:jdbc.properties" />  
  24.       
  25.     <!-- dataSource配置信息 -->  
  26.     <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">       
  27.          <property name="driver" value="${proxool.driverClassName}"/>         
  28.          <property name="driverUrl" value="${proxool.url}"/>         
  29.          <property name="user" value="${proxool.username}"/>         
  30.          <property name="password" value="${proxool.password}"/>         
  31.          <property name="alias" value="${proxool.alias}" />    
  32.          <property name="maximumActiveTime" value="${proxool.maximumActiveTime}" />    
  33.          <property name="prototypeCount" value="${proxool.prototypeCount}" />    
  34.          <property name="trace" value="${proxool.trace}" />    
  35.          <property name="verbose" value="${proxool.verbose}" />    
  36.          <property name="houseKeepingSleepTime" value="${proxool.houseKeepingSleepTime}"/>  
  37.          <property name="maximumConnectionCount" value="${proxool.maximumConnectionCount}" />    
  38.          <property name="minimumConnectionCount" value="${proxool.simultaneousBuildThrottle}" />    
  39.          <property name="simultaneousBuildThrottle" value="${proxool.simultaneousBuildThrottle}" />    
  40.          <property name="houseKeepingTestSql" value="${proxool.houseKeepingTestSql}" />    
  41.     </bean>  
  42.       
  43.     <!-- Spring整合hibernate主配置文件(hibernate.cfg.xml) -->  
  44.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  45.         <!-- 引用你自己Spring配置的数据库连接池 -->  
  46.         <property name="dataSource" ref="dataSource"/>  
  47.           
  48.         <!-- 扫描bean的包 -->  
  49.         <property name="packagesToScan" value="cn.edu.fjnu.hubmis.model"/>  
  50.           
  51.         <!-- 配置其他hibernate特性属性 -->  
  52.         <property name="hibernateProperties">  
  53.             <props>  
  54.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>  
  55.                 <prop key="hibernate.connection.pool_size">5</prop>  
  56.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  57.                 <prop key="hibernate.format_sql">false</prop>  
  58.                 <prop key="hibernate.show_sql">true</prop>  
  59.                 <prop key="current_session_context_class">thread</prop>  
  60.                 <prop key="hibernate.autoReconnect">true</prop>  
  61.             </props>  
  62.         </property>  
  63.     </bean>  
  64.       
  65.     <!-- 关于hibernateTemplate使用-->  
  66.     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  67.         <property name="sessionFactory" ref="sessionFactory"></property>  
  68.     </bean>  
  69.     <!-- 关于事务管理部分的配置 -->  
  70.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  71.         <property name="sessionFactory" ref="sessionFactory" />  
  72.     </bean>  
  73.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  
  74.       
  75. </beans>  


dispatcher-servlet.xml

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans default-lazy-init="true"  
  3.     xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans   
  8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.         http://www.springframework.org/schema/context   
  10.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11.         http://www.springframework.org/schema/mvc   
  12.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  13.   
  14.     <!-- 默认的注解映射的支持(方法一) -->  
  15.     <mvc:annotation-driven />    
  16.   
  17.     <!-- 手动配置注解映射支持的两个类(方法二) -->  
  18.     <!--Spring3.1开始的注解 HandlerMapping -->  
  19.     <!-- <bean  
  20.         class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />  
  21.      -->  
  22.     <!--Spring3.1开始的注解 HandlerAdapter -->  
  23.     <!--<bean  
  24.         class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />  
  25.     -->  
  26.       
  27.     <!-- 对静态资源文件的访问 方案一 (二选一) -->  
  28.     <mvc:default-servlet-handler />  
  29.   
  30.     <!-- 对静态资源文件的访问 方案二 (二选一)   
  31.     <mvc:resources mapping="/images/**" location="/images/"  
  32.         cache-period="31556926" />  
  33.     <mvc:resources mapping="/js/**" location="/js/"  
  34.         cache-period="31556926" />  
  35.     <mvc:resources mapping="/css/**" location="/css/"  
  36.         cache-period="31556926" />  
  37.     -->  
  38.       
  39.     <!-- 扫描哪一些包为controller -->  
  40.     <context:component-scan base-package="cn.edu.fjnu.hubmis.web.controller"/>   
  41.        
  42.     <!-- 视图解释类 -->  
  43.     <bean  
  44.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  45.         <property name="prefix" value="/WEB-INF/pages/" />  
  46.         <property name="suffix" value=".jsp" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->  
  47.         <property name="viewClass"  
  48.             value="org.springframework.web.servlet.view.JstlView" />  
  49.     </bean>  
  50.       
  51.       
  52. </beans>  

web.xml中的配置:

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" 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_2_5.xsd">  
  6.       
  7.     <welcome-file-list>  
  8.         <welcome-file>index.jsp</welcome-file>  
  9.     </welcome-file-list>  
  10.        
  11.     <!-- 统一错误页面去处 -->  
  12.     <error-page>  
  13.         <error-code>404</error-code>  
  14.         <location>/WEB-INF/public/404.jsp</location>  
  15.     </error-page>  
  16.     <error-page>  
  17.         <error-code>500</error-code>  
  18.         <location>/WEB-INF/public/404.jsp</location>  
  19.     </error-page>  
  20.       
  21.     <!-- 告诉listener,Spring配置文件路径 (applicationContext.xml) -->  
  22.     <context-param>  
  23.         <description>SpringXMLPath</description>  
  24.         <param-name>contextConfigLocation</param-name>  
  25.         <param-value>/WEB-INF/applicationContext.xml</param-value>  
  26.     </context-param>  
  27.   
  28.     <listener>  
  29.         <description>SpringContextLoaderListener</description>  
  30.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  31.     </listener>  
  32.   
  33.     <!-- 全站编码配置, 利用spring提供的编码过滤器 -->  
  34.     <filter>  
  35.         <filter-name>CharacterEncodingFilter</filter-name>  
  36.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  37.         <init-param>  
  38.             <param-name>encoding</param-name>  
  39.             <param-value>UTF-8</param-value>  
  40.         </init-param>  
  41.         <init-param>  
  42.             <param-name>forceEncoding</param-name>  
  43.             <param-value>true</param-value>  
  44.         </init-param>  
  45.     </filter>  
  46.     <filter-mapping>  
  47.         <filter-name>CharacterEncodingFilter</filter-name>  
  48.         <url-pattern>/*</url-pattern>  
  49.     </filter-mapping>  
  50.       
  51.       
  52.     <!-- SpringMVC 配置,告知配置文件路径(dispatcher-servlet.xml) -->  
  53.     <servlet>  
  54.         <servlet-name>dispatcher</servlet-name>  
  55.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  56.         <init-param>  
  57.             <param-name>contextConfigLocation</param-name>  
  58.             <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>  
  59.         </init-param>  
  60.         <load-on-startup>1</load-on-startup>  
  61.     </servlet>  
  62.     <servlet-mapping>  
  63.         <servlet-name>dispatcher</servlet-name>  
  64.         <url-pattern>/</url-pattern>  
  65.     </servlet-mapping>  
  66.       
  67.       
  68.     <!-- 避免Hibernate懒加载异常,能够让Session请求解释完成之后再关闭(所以才能够避免懒加载异常) -->  
  69.     <!-- <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>   
  70.         org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class>   
  71.         </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name>   
  72.         <url-pattern>/*</url-pattern> </filter-mapping> -->  
  73.           
  74.       
  75.       
  76.       
  77.   
  78. </web-app>  


Controller层写法

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package cn.demo;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8.   
  9. import cn.edu.fjnu.hubmis.model.personnel.Employee;  
  10. /** 
  11.  *  
  12.  * Simple to Introduction   
  13.  * 
  14.  * @ProjectName:  [HubMIS]  
  15.  * @Package:      [cn.edu.fjnu.hubmis.web.controller]   
  16.  * @ClassName:    [helloworldController]    
  17.  * @Description:  [测试:spring mvc,controller]    
  18.  * @Author:       [逍遥梦]    
  19.  * @CreateDate:   [2014-3-11 下午5:19:00]    
  20.  * @UpdateUser:   [逍遥梦]    
  21.  * @UpdateDate:   [2014-3-11 下午5:19:00]    
  22.  * @UpdateRemark: [说明本次修改内容]   
  23.  * @Version:      [v1.0]  
  24.  * 
  25.  */  
  26.   
  27.   
  28. /* 还可以加入@RequestMapping (   
  29.  *              财务部:@RequestMapping(value = "/finance") 
  30.  *              人事部:@RequestMapping(value = "/personnel") 
  31.  *              其他的根据需要来定 
  32.  * ) 
  33.  * @RequestMapping(value = "/monitor", method = RequestMethod.GET) 
  34.  * 表示此类接受  http://localhost:8080/monitor这类型的访问请求,请求的方式为Get请求, 
  35.  * 不写默认为两种请求方式都处理 
  36.  * */  
  37. @Controller    
  38. @RequestMapping(value = "/personnel")  
  39. public class employeeController {  
  40.       
  41.     /*你下面需要用到的ServiceImpl,由于之前已经把xxxxServiceImpl都写出来了,并通过了测试,所以直接用你之前注入的service就可以了 
  42.      * 如: 
  43.      *  我这里想完成一个员工的添加, 我要往helloworldController引入EmployeeServiceImpl对象,用IEmployeeService接口来定义它 
  44.      *  但名字为employeeServiceImpl(第一个字母小写) 
  45.      *   
  46.      *  
  47.      * */  
  48.     @Resource  
  49.     private IEmployeeService employeeServiceImpl;  
  50.       
  51.     //请求URL到处理器功能处理方法的映射,如果类名写了映射的地址如/monitor,这里又写了/hello  
  52.     //那么当访问http://localhost:8080/monitor/hello时,就会调用这个方法  
  53.     //如果类名头没写,则访问http://localhost:8080/hello时,调用此方法  
  54.     @RequestMapping(value = "/hello")   
  55.     public ModelAndView hello() {  
  56.           
  57.         /* jsp -> controller 传递的数据*/  
  58.         /*此处为传递过来的数据对象类(这个具体看你们开发的过程中需要哪些类,可以自己定义。) 
  59.          * 如: 
  60.          *  (data)  一般会传递JSON格式,接受  
  61.          *  Form -> javabean 
  62.          *   
  63.          * */  
  64.           
  65.         //这部分,我们要将前台的数据转换成我们需要的javabean的类.  
  66.         Employee employee = null;  
  67.           
  68.           
  69.         /* data -> service */  
  70.         employeeServiceImpl.addEmployee(employee);  
  71.           
  72.         //如果有一些是有返回值的,将返回的结果Result返回给jsp页面  
  73.           
  74.         /* Result -> return: jsp*/  
  75.         ModelAndView mv = new ModelAndView();  
  76.           
  77.         // 添加模型数据 可以是任意的POJO对象,我这里放了字符串  
  78.         // A项目的开发人员,你们可以放你们的Page,List<Page>或者单个javabean实体对象!  
  79.         mv.addObject("message""ResultObject");  
  80.           
  81.         // 设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面:   
  82.         //如这里,它会去找hello.jsp这个页面  
  83.         mv.setViewName("hello");  
  84.           
  85.         return mv; //模型数据和逻辑视图名  
  86.     }  
  87.       
  88.     /* 
  89.      *  @RequestBody  将HTTP请求正文转换为适合的HttpMessageConverter对象。 
  90.         @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。 
  91.      * */  
  92.     /* 
  93.      * 
  94.      * */  
  95.       
  96. }  


Service层写法

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package cn.demo;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8. import cn.edu.fjnu.hubmis.dao.personnel.IEmployeeDao;  
  9. import cn.edu.fjnu.hubmis.model.personnel.Employee;  
  10.   
  11. /** 
  12.  *  
  13.  * Simple to Introduction   
  14.  * 
  15.  * @ProjectName:  [HubMIS]  
  16.  * @Package:      [cn.demo]   
  17.  * @ClassName:    [EmployeeServiceImpl]    
  18.  * @Description:  [描述该类的功能]    
  19.  * @Author:       [逍遥梦]    
  20.  * @CreateDate:   [2014-3-19 上午8:35:02]    
  21.  * @UpdateUser:   [逍遥梦]    
  22.  * @UpdateDate:   [2014-3-19 上午8:35:02]    
  23.  * @UpdateRemark: [说明本次修改内容]   
  24.  * @Version:      [v1.0]  
  25.  * 
  26.  * Demo作用:大家来参考此XxxxxServiceImpl的写法 
  27.  *  
  28.  * 明白Service所处的位置: 
  29.      * Jsp -> Controller -> Service -> Dao -> hibernate -> DataBase 
  30.      * Result -> return: Service -> return: Controller -> return: Jsp 
  31.      * 
  32.      *  
  33.  * 现在会涉及到几个问题: 
  34.  *   1.springmvc中controller和jsp之间的几种传值(写到cn.demo.helloworldController中) 
  35.  *   2. 
  36.  * 即: 
  37.  * 如果Controller需要一个员工Employee, 这个JavaBean类已经存在,Controller将"表单" 
  38.  *  
  39.  */  
  40. /*Service的实现类要加上  Transactional事务处理注解 和 service注解*/  
  41. @Transactional  
  42. @Service  
  43. public class EmployeeServiceImpl implements IEmployeeService {  
  44.     /*注入dao对象*/  
  45.     @Resource  
  46.     private IEmployeeDao employeeDaoImpl;  
  47.       
  48.     public void addEmployee(Employee employee){  
  49.         //增加一个员工  
  50.         employeeDaoImpl.addEmployee(employee);  
  51.     }  
  52. }  


Dao层写法

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package cn.edu.fjnu.hubmis.dao.personnel.impl;  
  2.   
  3.   
  4. import javax.annotation.Resource;  
  5.   
  6. import org.springframework.stereotype.Repository;  
  7.   
  8. import cn.edu.fjnu.hubmis.dao.common.IGenericDao;  
  9. import cn.edu.fjnu.hubmis.dao.personnel.IEmployeeDao;  
  10. import cn.edu.fjnu.hubmis.model.personnel.Employee;  
  11. import cn.edu.fjnu.hubmis.utils.Page;  
  12.   
  13. @Repository  
  14. public class EmployeeDaoImpl implements IEmployeeDao{  
  15.   
  16.     @Resource  
  17.     private IGenericDao genericDAO;  
  18.   
  19.     public boolean addEmployee(Employee employee) {  
  20.         try {  
  21.             this.genericDAO.save(employee);  
  22.             return true;  
  23.         } catch (Exception e) {  
  24.             return false;  
  25.         }  
  26.     }  
  27.   
  28.     public Employee getEmployeeByEId(String eId) {  
  29.         return (Employee) this.genericDAO.get(Employee.class, eId);  
  30.     }  
  31.   
  32.     public boolean updateEmployee(Employee employee) {  
  33.         try {  
  34.             this.genericDAO.update(employee);  
  35.             return true;  
  36.         } catch (Exception e) {  
  37.             return false;  
  38.         }  
  39.     }  
  40.   
  41.     public Page<Employee> getAllEmployee(int cId, int pageSize, int index) {  
  42.           
  43.         return this.genericDAO.findPageBySQL(Employee.class,   
  44.                 "select * from T_employee where ER_company_id ="+cId,  
  45.                 pageSize, index);  
  46.     }  
  47.       
  48.     public boolean deleteEmployee(Employee employee) {  
  49.         try {  
  50.             this.genericDAO.delete(employee);  
  51.             return true;  
  52.         } catch (Exception e) {  
  53.             return false;  
  54.         }  
  55.     }  
  56. }  

出处:http://blog.csdn.net/ljphhj/article/details/21524703?utm_source=tuicool&utm_medium=referral
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值