当前位置: 代码迷 >> JavaScript >> mybatis3+spring 3+ext js调整套路
  详细解决方案

mybatis3+spring 3+ext js调整套路

热度:515   发布时间:2012-09-09 09:27:54.0
mybatis3+spring 3+ext js整合套路
mybatis3+spring 3+ext js整合套路,可以小结一下.先来看mybatis 3及模型

 
1 首先是MODEL层,比如对于用户管理
   先来个user.java,是个POJO

2 再搞一个persisten层,存放mybatis 3的mapper接口和文件,注意把它们都放
入一个包中,比如
 
public interface UserMapper {
	Long getId();
	User login(Map<String,Object> param);
	User getUser(Map<String,Object> param);
	List<User> getUserList();
	List<Map<String,Object>> getUserNameList();
	void insertUser(User user);


   usermapper.xml:
  <mapper namespace="com.user.persistence.UserMapper">
   <insert id="insertUser" parameterType="User" >
  	INSERT INTO t_user (id,name, password, create_date)
    VALUES (#{id},#{name}, #{password}, #{createDate,jdbcType=TIMESTAMP})
  </insert>
   



3 userdao层

 

@Component
public class UserDao extends SqlSessionDaoSupport {
public void insertUser(User user) {
		getSqlSession().insert("com.liao.user.persistence.UserMapper.insertUser", user);
	}

 ..............


  
4 service层
   
@Service
//默认将类中的所有函数纳入事务管理.
@Transactional
public class UserService{
	@Autowired
	private UserMapper userMapper;

 public void insertUser(User user,Map<String,Object> param) {
		//新增用户
		userMapper.insertUser(user);




5 controller层
  
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody Map<String,Object> saveOrUpdate(HttpServletRequest request,   
            HttpServletResponse response){
		Map<String,Object> responseMap = new HashMap<String,Object>();

  User user = new User();
				Long newId = userService.getId();
								user.setId(newId);
				user.setCreateDate(new Date());
				user.setName(name);
				user.setPassword(password);
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("user_id", newId);
								userService.insertUser(user, param);
				responseMap.put("method", "Create");
				responseMap.put("success", "true");
				responseMap.put("info", "新增成功!");
			}
			return responseMap;




  注意,由于要返回相关的信息JSON格式给前端EXT,因此注意这里使用了
spring mvc 3中的很多技术,加个@responsebody就能生成JSON了,十分方便
,所以返回时,用一个MAP保存了要给前端显示的EXT JS信息了.


6 前端EXT JS要点:
    getForm: function() {
            var form = new Ext.form.FormPanel({
url:'user/save',
                        ....................
            ..........
  
  submit: function() {
            if (this.form.getForm().isValid()) {
                var id = this.form.getForm().findField("id").getValue();
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.form.getForm().reset();
                            } else {
                                this.dlg.hide();
                            }
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });




7 mybatis3 跟spring 的配置整合
  1) 搞个jdbc.properties,存放datasoruce
    jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/springibatisextjs3
jdbc.username=root
jdbc.password=33333

  2)web.xml
   

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


3)先看root-context.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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="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.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:location="/WEB-INF/jdbc.properties" />
		
	<!-- 数据源配置, 使用应用中的DBCP数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<!-- Connection Info -->
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.databaseurl}" />
           .................		
	</bean>

	<!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.liao" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.kimho" />
    </bean>
    
	<!-- enable transaction demarcation with annotations-->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
	 
	<!-- transaction manager, use JtaTransactionManager for global tx-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 激活annotation功能 -->
	<context:annotation-config />
	<!-- 激活annotation功能 -->
	<context:spring-configured/>
	
	<!-- 不扫描带有@Controller注解的类。因为这些类已经随容器启动时,在servlet-context中扫描过一遍了 -->
	<context:component-scan base-package="com.liao">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
</beans>


4) 业务类的servlet.xml
    

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
	
	<!-- Configures the @Controller programming model 必须加上这个,不然请求controller时会出现no mapping url错误-->
	<mvc:annotation-driven />
	
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
	<resources mapping="/images/**" location="/images/" />
    <resources mapping="/scripts/**" location="/scripts/" />
    <resources mapping="/styles/**" location="/styles/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/jsp directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/jsp/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- 扫描业务组件,让spring不扫描带有@Service注解的类(留在root-context.xml中扫描@Service注解的类),防止事务失效 -->
	<context:component-scan base-package="com.liao">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	</context:component-scan>
	
</beans:beans


  相关解决方案