WEB开发框架配置文件和各层注解


记录一点关于这次“项目管理”课程做的轻量级企业ERP的关于框架部分的知识


我们采取的是SpringMVC + Spring + Hibernate开发的

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

注:有一些非关乎框架的主要部分,所以博主没有列出来,所以不是直接copy就可以运行,只是参考学习哈!

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


applicationContext.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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/tx
     	 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 他的作用是隐式地向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor、 
		CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor、
		RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。 -->
	<context:annotation-config />
	
	<!-- 关于所在包注解的自动扫描配置(也会注入上面4个BeanPostProcessor)-->
	<context:component-scan base-package="cn.edu.fjnu.hubmis" />
	
	<!-- 数据库对应的配置信息 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	
	<!-- dataSource配置信息 -->
	<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">     
         <property name="driver" value="${proxool.driverClassName}"/>       
         <property name="driverUrl" value="${proxool.url}"/>       
         <property name="user" value="${proxool.username}"/>       
         <property name="password" value="${proxool.password}"/>       
         <property name="alias" value="${proxool.alias}" />  
		 <property name="maximumActiveTime" value="${proxool.maximumActiveTime}" />  
         <property name="prototypeCount" value="${proxool.prototypeCount}" />  
         <property name="trace" value="${proxool.trace}" />  
		 <property name="verbose" value="${proxool.verbose}" />  
		 <property name="houseKeepingSleepTime" value="${proxool.houseKeepingSleepTime}"/>
		 <property name="maximumConnectionCount" value="${proxool.maximumConnectionCount}" />  
		 <property name="minimumConnectionCount" value="${proxool.simultaneousBuildThrottle}" />  
		 <property name="simultaneousBuildThrottle" value="${proxool.simultaneousBuildThrottle}" />  
		 <property name="houseKeepingTestSql" value="${proxool.houseKeepingTestSql}" />  
	</bean>
	
	<!-- Spring整合hibernate主配置文件(hibernate.cfg.xml) -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<!-- 引用你自己Spring配置的数据库连接池 -->
		<property name="dataSource" ref="dataSource"/>
		
		<!-- 扫描bean的包 -->
		<property name="packagesToScan" value="cn.edu.fjnu.hubmis.model"/>
		
		<!-- 配置其他hibernate特性属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.connection.pool_size">5</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.format_sql">false</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="current_session_context_class">thread</prop>
				<prop key="hibernate.autoReconnect">true</prop>
			</props>
		</property>
	</bean>
	
	<!-- 关于hibernateTemplate使用-->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 关于事务管理部分的配置 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
    
</beans>


dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
	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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 默认的注解映射的支持(方法一) -->
	<mvc:annotation-driven />  

	<!-- 手动配置注解映射支持的两个类(方法二) -->
	<!--Spring3.1开始的注解 HandlerMapping -->
	<!-- <bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
	 -->
	<!--Spring3.1开始的注解 HandlerAdapter -->
	<!--<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
	-->
	
	<!-- 对静态资源文件的访问 方案一 (二选一) -->
	<mvc:default-servlet-handler />

	<!-- 对静态资源文件的访问 方案二 (二选一) 
	<mvc:resources mapping="/images/**" location="/images/"
		cache-period="31556926" />
	<mvc:resources mapping="/js/**" location="/js/"
		cache-period="31556926" />
	<mvc:resources mapping="/css/**" location="/css/"
		cache-period="31556926" />
	-->
	
	<!-- 扫描哪一些包为controller -->
	<context:component-scan base-package="cn.edu.fjnu.hubmis.web.controller"/> 
	 
	<!-- 视图解释类 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
	</bean>
	
	
</beans>

web.xml中的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	 
	<!-- 统一错误页面去处 -->
	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/public/404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/public/404.jsp</location>
	</error-page>
	
	<!-- 告诉listener,Spring配置文件路径 (applicationContext.xml) -->
	<context-param>
		<description>SpringXMLPath</description>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>

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

	<!-- 全站编码配置, 利用spring提供的编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	<!-- SpringMVC 配置,告知配置文件路径(dispatcher-servlet.xml) -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	
	<!-- 避免Hibernate懒加载异常,能够让Session请求解释完成之后再关闭(所以才能够避免懒加载异常) -->
	<!-- <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class> 
		org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> 
		</filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> 
		<url-pattern>/*</url-pattern> </filter-mapping> -->
		
	
	
	

</web-app>


Controller层写法

package cn.demo;

import javax.annotation.Resource;

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

import cn.edu.fjnu.hubmis.model.personnel.Employee;
/**
 * 
 * Simple to Introduction  
 *
 * @ProjectName:  [HubMIS] 
 * @Package:      [cn.edu.fjnu.hubmis.web.controller]  
 * @ClassName:    [helloworldController]   
 * @Description:  [测试:spring mvc,controller]   
 * @Author:       [逍遥梦]   
 * @CreateDate:   [2014-3-11 下午5:19:00]   
 * @UpdateUser:   [逍遥梦]   
 * @UpdateDate:   [2014-3-11 下午5:19:00]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *
 */


/* 还可以加入@RequestMapping (  
 *				财务部:@RequestMapping(value = "/finance")
 *				人事部:@RequestMapping(value = "/personnel")
 *				其他的根据需要来定
 * )
 * @RequestMapping(value = "/monitor", method = RequestMethod.GET)
 * 表示此类接受  http://localhost:8080/monitor这类型的访问请求,请求的方式为Get请求,
 * 不写默认为两种请求方式都处理
 * */
@Controller  
@RequestMapping(value = "/personnel")
public class employeeController {
	
	/*你下面需要用到的ServiceImpl,由于之前已经把xxxxServiceImpl都写出来了,并通过了测试,所以直接用你之前注入的service就可以了
	 * 如:
	 * 	我这里想完成一个员工的添加, 我要往helloworldController引入EmployeeServiceImpl对象,用IEmployeeService接口来定义它
	 *  但名字为employeeServiceImpl(第一个字母小写)
	 *  
	 * 
	 * */
	@Resource
	private IEmployeeService employeeServiceImpl;
	
	//请求URL到处理器功能处理方法的映射,如果类名写了映射的地址如/monitor,这里又写了/hello
	//那么当访问http://localhost:8080/monitor/hello时,就会调用这个方法
	//如果类名头没写,则访问http://localhost:8080/hello时,调用此方法
	@RequestMapping(value = "/hello") 
	public ModelAndView hello() {
		
		/* jsp -> controller 传递的数据*/
		/*此处为传递过来的数据对象类(这个具体看你们开发的过程中需要哪些类,可以自己定义。)
		 * 如:
		 *  (data)  一般会传递JSON格式,接受 
		 * 	Form -> javabean
		 *  
		 * */
		
		//这部分,我们要将前台的数据转换成我们需要的javabean的类.
		Employee employee = null;
		
		
		/* data -> service */
		employeeServiceImpl.addEmployee(employee);
		
		//如果有一些是有返回值的,将返回的结果Result返回给jsp页面
		
		/* Result -> return: jsp*/
		ModelAndView mv = new ModelAndView();
		
		// 添加模型数据 可以是任意的POJO对象,我这里放了字符串
		// A项目的开发人员,你们可以放你们的Page,List<Page>或者单个javabean实体对象!
		mv.addObject("message", "ResultObject");
		
		// 设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面: 
		//如这里,它会去找hello.jsp这个页面
		mv.setViewName("hello");
		
		return mv; //模型数据和逻辑视图名
	}
	
	/*
	 *  @RequestBody  将HTTP请求正文转换为适合的HttpMessageConverter对象。
		@ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。
	 * */
	/*
	 * 还想学习的可以看:http://snowolf.iteye.com/blog/577989
	 * */
	
}


Service层写法

package cn.demo;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.fjnu.hubmis.dao.personnel.IEmployeeDao;
import cn.edu.fjnu.hubmis.model.personnel.Employee;

/**
 * 
 * Simple to Introduction  
 *
 * @ProjectName:  [HubMIS] 
 * @Package:      [cn.demo]  
 * @ClassName:    [EmployeeServiceImpl]   
 * @Description:  [描述该类的功能]   
 * @Author:       [逍遥梦]   
 * @CreateDate:   [2014-3-19 上午8:35:02]   
 * @UpdateUser:   [逍遥梦]   
 * @UpdateDate:   [2014-3-19 上午8:35:02]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *
 * Demo作用:大家来参考此XxxxxServiceImpl的写法
 * 
 * 明白Service所处的位置:
	 * Jsp -> Controller -> Service -> Dao -> hibernate -> DataBase
	 * Result -> return: Service -> return: Controller -> return: Jsp
	 *
	 * 
 * 现在会涉及到几个问题:
 * 	 1.springmvc中controller和jsp之间的几种传值(写到cn.demo.helloworldController中)
 * 	 2.
 * 即:
 * 如果Controller需要一个员工Employee, 这个JavaBean类已经存在,Controller将"表单"
 * 
 */
/*Service的实现类要加上  Transactional事务处理注解 和 service注解*/
@Transactional
@Service
public class EmployeeServiceImpl implements IEmployeeService {
	/*注入dao对象*/
	@Resource
	private IEmployeeDao employeeDaoImpl;
	
	public void addEmployee(Employee employee){
		//增加一个员工
		employeeDaoImpl.addEmployee(employee);
	}
}


Dao层写法

package cn.edu.fjnu.hubmis.dao.personnel.impl;


import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import cn.edu.fjnu.hubmis.dao.common.IGenericDao;
import cn.edu.fjnu.hubmis.dao.personnel.IEmployeeDao;
import cn.edu.fjnu.hubmis.model.personnel.Employee;
import cn.edu.fjnu.hubmis.utils.Page;

@Repository
public class EmployeeDaoImpl implements IEmployeeDao{

	@Resource
	private IGenericDao genericDAO;

	public boolean addEmployee(Employee employee) {
		try {
			this.genericDAO.save(employee);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Employee getEmployeeByEId(String eId) {
		return (Employee) this.genericDAO.get(Employee.class, eId);
	}

	public boolean updateEmployee(Employee employee) {
		try {
			this.genericDAO.update(employee);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Page<Employee> getAllEmployee(int cId, int pageSize, int index) {
		
		return this.genericDAO.findPageBySQL(Employee.class, 
				"select * from T_employee where ER_company_id ="+cId,
				pageSize, index);
	}
	
	public boolean deleteEmployee(Employee employee) {
		try {
			this.genericDAO.delete(employee);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值