码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMvc注解整合mybatis+ExtJS5.0框架

时间:2015-09-10 13:19:11      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:

1先看整体结构

技术分享                                                   

2,使用到的配置文件

2.1 jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis?useUnicode=true&characterEncoding=UTF-8
username=root
password=mayude
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

 

2.2 log4j.properties

log4j.rootLogger = debug,stdout,D,E
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %d %p [%c] - %m%n

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout

 

2.3 spring-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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="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  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 开启注解-->  
    <mvc:annotation-driven />
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.myd.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>


    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
     
    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />  
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
    </bean>
    
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">    
         <property name="exceptionMappings">    
             <props>    
                 <prop key="java.lang.Exception">error</prop>    
                 <prop key="java.lang.Throwable">error</prop>    
             </props>    
         </property>    
         <property name="statusCodes">    
             <props>    
                 <prop key="error">500</prop>    
                 <prop key="error">404</prop>    
             </props>    
         </property>    
         <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 -->    
         <property name="warnLogCategory" value="WARN"></property>    
         <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 -->    
         <property name="defaultErrorView" value="error"></property>    
         <!-- 默认HTTP状态码 -->    
         <property name="defaultStatusCode" value="500"></property>    
     </bean> 
</beans>

 

2.4 spring-mybatis.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="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  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.myd" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>
 
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/myd/mapping/*.xml"></property>
    </bean>
 
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.myd.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
 
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
 
</beans>

 

3,涉及到的类

3.1 UserController .java

package com.myd.controller;

import java.util.List;

import javax.annotation.Resource;

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

import com.myd.entity.User;
import com.myd.service.UserService;

@Controller("userController")
@RequestMapping("/user")
public class UserController {
    /**
     * 注入service
     */
    @Resource(name = "userServiceImpl")
    public UserService userService;
    
    /**
     * 获取用户列表
     * @return
     */
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public List<User> list()
    {
        List<User> users=userService.getUser();
        for(User user:users)
        {
            System.out.println(user);
        }
        return users;
    }
}

3.2UserMapper .java

package com.myd.dao;

import java.util.List;

import com.myd.entity.User;


public interface UserMapper {
    /**
     * 根据id获取用户
     * @param id
     * @return User
     */
    List<User> getUser();
}

 

3.3User.java

package com.myd.entity;

/**
 * @author myd
 * 用户信息
 */

public class User {
    private String user_pk;//用户主键
    private String user_number;//用户编号
    private String user_name;//用户姓名
    private String user_password;//用户密码
    private String fk_roles_pk;//用户组(存储主键??
    private String user_sex;//用户性别
    private String user_birthday;//用户生日
    private String fk_station_pk;//用户工位
    private String user_intime;//入职时间
    private String user_phone;//电话
    private String user_email;//邮箱
    
    
    

    public String getUser_pk() {
        return user_pk;
    }
    public void setUser_pk(String user_pk) {
        this.user_pk = user_pk;
    }
    public String getUser_number() {
        return user_number;
    }
    public void setUser_number(String user_number) {
        this.user_number = user_number;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getUser_password() {
        return user_password;
    }
    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }
    
    public String getFk_roles_pk() {
        return fk_roles_pk;
    }
    public void setFk_roles_pk(String fk_roles_pk) {
        this.fk_roles_pk = fk_roles_pk;
    }
    public String getUser_sex() {
        return user_sex;
    }
    public void setUser_sex(String user_sex) {
        this.user_sex = user_sex;
    }
    public String getUser_birthday() {
        return user_birthday;
    }
    public void setUser_birthday(String user_birthday) {
        this.user_birthday = user_birthday;
    }
    public String getFk_station_pk() {
        return fk_station_pk;
    }
    public void setFk_station_pk(String fk_station_pk) {
        this.fk_station_pk = fk_station_pk;
    }
    public String getUser_intime() {
        return user_intime;
    }
    public void setUser_intime(String user_intime) {
        this.user_intime = user_intime;
    }
    public String getUser_phone() {
        return user_phone;
    }
    public void setUser_phone(String user_phone) {
        this.user_phone = user_phone;
    }
    public String getUser_email() {
        return user_email;
    }
    public void setUser_email(String user_email) {
        this.user_email = user_email;
    }
    @Override
    public String toString() {
        return "User [user_pk=" + user_pk + ", user_number=" + user_number
                + ", user_name=" + user_name + ", user_password="
                + user_password + ", fk_roles_pk=" + fk_roles_pk
                + ", user_sex=" + user_sex + ", user_birthday=" + user_birthday
                + ", fk_station_pk=" + fk_station_pk + ", user_intime="
                + user_intime + ", user_phone=" + user_phone + ", user_email="
                + user_email + "]";
    }

}

3.4 UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 为这个mapper指定一个唯一的namespace,namespace的值需要设置为和dao层的类相对应 -->
<mapper namespace="com.myd.dao.UserMapper">
    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
    resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
    User类就是users表所对应的实体类
    -->
    <!-- 
        根据id查询得到一个user对象
     -->
    <select id="getUser" parameterType="int" 
        resultType="com.myd.entity.User">
        select * from user
    </select>
</mapper>

 

3.5 UserService.java

package com.myd.service;

import java.util.List;

import com.myd.entity.User;

public interface UserService {
    
    /**
     * @param id
     * @return
     */
    List<User> getUser();
}

3.6 UserServiceImpl

package com.myd.serviceimpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myd.dao.UserMapper;
import com.myd.entity.User;
import com.myd.service.UserService;
@Service("userServiceImpl")
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;
    
    @Override
    public List<User> getUser() {
        System.out.println("service");
        return this.userMapper.getUser();
    }

}

 

3.7 UserControllerTest.java    junit测试文件

package com.myd.test;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

import com.alibaba.fastjson.JSON;
import com.myd.entity.User;
import com.myd.service.UserService;  
import com.sun.istack.internal.logging.Logger;


@RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class UserControllerTest {
    
     @Resource
     private UserService userService = null;
     
     private static Logger logger = Logger.getLogger(UserControllerTest.class);
//    @Before
//    public void init() throws Exception {
//        
//    }

    @Test
    public void testLogin() throws Exception {
          List<User> users = userService.getUser();
          System.out.println(users.size());
          for(User user:users)
          {
            // System.out.println(user.getUserName());
            // logger.info("值:"+user.getUserName());
              logger.info(JSON.toJSONString(user));
          }
    }
}

 

4数据库文件user.sql

/*
Navicat MySQL Data Transfer

Source Server         : MySql
Source Server Version : 50624
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50624
File Encoding         : 65001

Date: 2015-09-10 11:25:09
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `user_pk` varchar(32) NOT NULL,
  `fk_roles_pk` varchar(255) DEFAULT NULL,
  `fk_station_pk` varchar(255) DEFAULT NULL,
  `user_birthday` varchar(255) DEFAULT NULL,
  `user_email` varchar(255) DEFAULT NULL,
  `user_intime` varchar(255) DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `user_number` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  `user_phone` varchar(255) DEFAULT NULL,
  `user_sex` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_pk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO user VALUES (402880304e33e46e014e34087e440000, 5ac47af54e9502f4014e95f0406c0000, q, 2015-06-27T00:00:00, 123823@qq.com, 2015-06-27T00:00:00, 魏正, HX20105718, 11, 13381086775, );
INSERT INTO user VALUES (ff8081814e62293e014e627e8c050000, 5ac47af54e9502f4014e95f0406c0000, r, 2015-07-06T00:00:00, myd521@qq.com, 2015-07-06T00:00:00, 马玉, 211, 123, 13381086775, );
INSERT INTO user VALUES (ff8081814e70a670014e70a700c60000, 5ac47af54e9502f4014e95f0406c0000, ‘‘, 2015-07-09T00:00:00, myd521@qq.com, 2015-07-06T00:00:00, cs, cs, cs, 13381086775, );

5web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyCompany</display-name>
  <!-- Spring和mybatis的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring MVC servlet -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 此处可以可以配置成*.action,对应struts的后缀习惯 -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
    <!-- 配置SESSION超时,单位是分钟 -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
  
</web-app>

6.其余的都为ExtJs还有图片等的资源文件,在此不变说明,所以都在源码中,源码中不包括sql文件,所以需要使用上述的sql文件,其中数据库名为mybatis表明为user,可以根据自己需求修改

7.源码下载地址http://download.csdn.net/detail/myude/9094239

SpringMvc注解整合mybatis+ExtJS5.0框架

标签:

原文地址:http://my.oschina.net/mayude/blog/504304

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!