Spring+SpringMVC+Mybatis 的一种配置方式

依赖的jar包

  1 <dependencies>
  2     <!-- ehcache的jar -->
  3     <dependency>
  4         <groupId>net.sf.ehcache</groupId>
  5         <artifactId>ehcache</artifactId>
  6         <version>2.8.0</version>
  7     </dependency>
  8     <dependency>
  9         <groupId>org.mybatis</groupId>
 10         <artifactId>mybatis-ehcache</artifactId>
 11         <version>1.0.0</version>
 12     </dependency>
 13     
 14     <!-- cglib的jar -->
 15     <dependency>
 16         <groupId>cglib</groupId>
 17         <artifactId>cglib</artifactId>
 18         <version>3.1</version>
 19     </dependency>
 20     <dependency>
 21         <groupId>asm</groupId>
 22         <artifactId>asm</artifactId>
 23         <version>3.3.1</version>
 24     </dependency>
 25     
 26     <!-- spring webmvc相关jar包 -->
 27     <dependency>
 28         <groupId>org.springframework</groupId>
 29         <artifactId>spring-webmvc</artifactId>
 30         <version>4.0.0.RELEASE</version>
 31     </dependency>
 32     <dependency>
 33         <groupId>org.springframework</groupId>
 34         <artifactId>spring-web</artifactId>
 35         <version>4.0.0.RELEASE</version>
 36     </dependency>
 37     
 38     <!-- aspectj的jar -->
 39     <dependency>
 40         <groupId>org.aspectj</groupId>
 41         <artifactId>aspectjrt</artifactId>
 42         <version>1.7.4</version>
 43     </dependency>
 44     <dependency>
 45         <groupId>org.aspectj</groupId>
 46         <artifactId>aspectjweaver</artifactId>
 47         <version>1.7.4</version>
 48     </dependency>
 49     
 50     <!-- dbpool的jar -->
 51     <dependency>
 52         <groupId>com.alibaba</groupId>
 53         <artifactId>druid</artifactId>
 54         <version>1.0.2</version>
 55     </dependency>
 56     
 57     <!-- Mybatis的jar -->
 58     <dependency>
 59         <groupId>org.mybatis</groupId>
 60         <artifactId>mybatis</artifactId>
 61         <version>3.2.3</version>
 62     </dependency>
 63     <dependency>
 64         <groupId>org.mybatis</groupId>
 65         <artifactId>mybatis-spring</artifactId>
 66         <version>1.2.2</version>
 67     </dependency>
 68     
 69     <!-- spring相关jar包 -->
 70     <dependency>
 71         <groupId>org.springframework</groupId>
 72         <artifactId>spring-context</artifactId>
 73         <version>4.0.0.RELEASE</version>
 74     </dependency>
 75     <dependency>
 76         <groupId>org.springframework</groupId>
 77         <artifactId>spring-context-support</artifactId>
 78         <version>4.0.0.RELEASE</version>
 79     </dependency>
 80     <dependency>
 81         <groupId>org.springframework</groupId>
 82         <artifactId>spring-jdbc</artifactId>
 83         <version>4.0.0.RELEASE</version>
 84     </dependency>
 85     <dependency>
 86         <groupId>org.springframework</groupId>
 87         <artifactId>spring-orm</artifactId>
 88         <version>4.0.0.RELEASE</version>
 89     </dependency>
 90     <dependency>
 91         <groupId>org.springframework</groupId>
 92         <artifactId>spring-tx</artifactId>
 93         <version>4.0.0.RELEASE</version>
 94     </dependency>
 95     
 96     <!-- 日志的jar -->
 97     <dependency>
 98         <groupId>org.slf4j</groupId>
 99         <artifactId>slf4j-api</artifactId>
100         <version>1.7.5</version>
101     </dependency>
102     <dependency>
103         <groupId>ch.qos.logback</groupId>
104         <artifactId>logback-classic</artifactId>
105         <version>1.0.13</version>
106     </dependency>
107     
108     <!-- mysql的jar -->
109     <dependency>
110         <groupId>mysql</groupId>
111         <artifactId>mysql-connector-java</artifactId>
112         <version>5.1.28</version>
113     </dependency>
114     
115     <!-- web jstld的jar -->
116     <dependency>
117         <groupId>taglibs</groupId>
118         <artifactId>standard</artifactId>
119         <version>1.1.2</version>
120     </dependency>
121     <dependency>
122         <groupId>jstl</groupId>
123         <artifactId>jstl</artifactId>
124         <version>1.2</version>
125     </dependency>
126     
127     <!-- json -->
128         <dependency>
129             <groupId>com.fasterxml.jackson.core</groupId>
130             <artifactId>jackson-core</artifactId>
131             <version>2.3.0</version>
132         </dependency>
133         <dependency>
134             <groupId>com.fasterxml.jackson.core</groupId>
135             <artifactId>jackson-annotations</artifactId>
136             <version>2.3.0</version>
137         </dependency>
138         <dependency>
139             <groupId>com.fasterxml.jackson.core</groupId>
140             <artifactId>jackson-databind</artifactId>
141             <version>2.3.0</version>
142             <exclusions>
143                 <exclusion>
144                     <artifactId>jackson-annotations</artifactId>
145                     <groupId>com.fasterxml.jackson.core</groupId>
146                 </exclusion>
147             </exclusions>
148         </dependency>
149     
150     <!-- 测试dejar -->
151     <dependency>
152         <groupId>junit</groupId>
153         <artifactId>junit</artifactId>
154         <version>4.11</version>
155         <scope>test</scope>
156     </dependency>
157   </dependencies>
dependencies

 

spring配置

 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"
 4         xmlns:context="http://www.springframework.org/schema/context"
 5         xmlns:aop="http://www.springframework.org/schema/aop"
 6         xmlns:tx="http://www.springframework.org/schema/tx"
 7         xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
10         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
11         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
12         "
13         >
14     <context:component-scan base-package="com.zhou">
15         <context:exclude-filter type="annotation"
16             expression="org.springframework.stereotype.Controller" />
17     </context:component-scan>    
18 
19     <aop:aspectj-autoproxy proxy-target-class="true"/> 
20     <tx:annotation-driven transaction-manager="transactionManager"    proxy-target-class="true" />
21     
22     <bean id="transactionManager"
23         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
24         <property name="dataSource" ref="dataSource" />
25     </bean>         
26     <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
27         <property name="driverClassName">
28             <value>com.mysql.jdbc.Driver</value>
29         </property>
30         <property name="url">
31             <value>jdbc:mysql://localhost:3306/arch1?useUnicode=true&amp;characterEncoding=UTF-8
32             </value>
33         </property>
34         <property name="username">
35             <value>root</value>
36         </property>
37         <property name="password" value="123456" />
38     </bean>
39     
40     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
41         <property name="dataSource" ref="dataSource" />
42         <property name="configLocation" value="classpath:MybatisConf.xml"/>
43         <property name="mapperLocations" value="classpath*:com/zhou/**/*Mapper.xml" />
44     </bean>
45     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
46         <property name="basePackage" value="com.zhou" />
47         <property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
48     </bean>
49  </beans>
applicationContext

MyBatis配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 3 <configuration>
 4     <typeAliases>
 5         <typeAlias type="com.zhou.architecture1.customermgr.vo.CustomerModel" alias="CM"/>
 6         <typeAlias type="com.zhou.architecture1.customermgr.vo.CustomerQueryModel" alias="CQM"/>
 7     </typeAliases>
 8     <plugins>
 9         <plugin interceptor="com.zhou.pageutil.PagePlugin">
10             <property name="dialect" value="mysql"/>
11             <property name="pageSqlId" value=".*Page.*"/>
12         </plugin>
13     </plugins>
14 </configuration>     
MybatisConf.xml

分页插件用到的三个类

  1 package com.zhou.pageutil;
  2 
  3 import java.lang.reflect.Field;
  4 import java.sql.Connection;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 import java.util.List;
  9 import java.util.Properties;
 10 
 11 import org.apache.ibatis.executor.ErrorContext;
 12 import org.apache.ibatis.executor.ExecutorException;
 13 import org.apache.ibatis.executor.statement.BaseStatementHandler;
 14 import org.apache.ibatis.executor.statement.RoutingStatementHandler;
 15 import org.apache.ibatis.executor.statement.StatementHandler;
 16 import org.apache.ibatis.mapping.BoundSql;
 17 import org.apache.ibatis.mapping.MappedStatement;
 18 import org.apache.ibatis.mapping.ParameterMapping;
 19 import org.apache.ibatis.mapping.ParameterMode;
 20 import org.apache.ibatis.plugin.Interceptor;
 21 import org.apache.ibatis.plugin.Intercepts;
 22 import org.apache.ibatis.plugin.Invocation;
 23 import org.apache.ibatis.plugin.Plugin;
 24 import org.apache.ibatis.plugin.Signature;
 25 import org.apache.ibatis.reflection.MetaObject;
 26 import org.apache.ibatis.reflection.property.PropertyTokenizer;
 27 import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
 28 import org.apache.ibatis.session.Configuration;
 29 import org.apache.ibatis.type.TypeHandler;
 30 import org.apache.ibatis.type.TypeHandlerRegistry;
 31 
 32 @Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
 33 public class PagePlugin implements Interceptor {
 34     private static String dialect = "";    //数据库方言
 35     private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)
 36     
 37     public Object intercept(Invocation ivk) throws Throwable {
 38         if(ivk.getTarget() instanceof RoutingStatementHandler){
 39             RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
 40             BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
 41             MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
 42 
 43             if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL
 44                 BoundSql boundSql = delegate.getBoundSql();
 45                 Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
 46                 if(parameterObject==null){
 47                     throw new NullPointerException("parameterObject尚未实例化!");
 48                 }else{
 49                     Connection connection = (Connection)ivk.getArgs()[0];
 50                     String sql = boundSql.getSql();
 51                     String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
 52                     PreparedStatement countStmt = connection.prepareStatement(countSql);
 53                     BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
 54                     setParameters(countStmt,mappedStatement,countBS,parameterObject);
 55                     ResultSet rs = countStmt.executeQuery();
 56                     int count = 0;
 57                     if (rs.next()) {
 58                         count = rs.getInt(1);
 59                     }
 60                     rs.close();
 61                     countStmt.close();
 62 
 63                     Page page = null;
 64                     if(parameterObject instanceof Page){    //参数就是Page实体
 65                          page = (Page) parameterObject;
 66                         page.setTotalCount(count);
 67                     }else{    //参数为某个实体,该实体拥有Page属性
 68                         Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
 69                         if(pageField!=null){
 70                             page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
 71                             if(page==null)
 72                                 page = new Page();
 73                             page.setTotalCount(count);
 74                             ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象
 75                         }else{
 76                             throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");
 77                         }
 78                     }
 79                     String pageSql = generatePageSql(sql,page);
 80                     ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.
 81                 }
 82             }
 83         }
 84         return ivk.proceed();
 85     }
 86 
 87     
 88     /**
 89      * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
 90      * @param ps
 91      * @param mappedStatement
 92      * @param boundSql
 93      * @param parameterObject
 94      * @throws SQLException
 95      */
 96     private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
 97         ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
 98         List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
 99         if (parameterMappings != null) {
100             Configuration configuration = mappedStatement.getConfiguration();
101             TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
102             MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
103             for (int i = 0; i < parameterMappings.size(); i++) {
104                 ParameterMapping parameterMapping = parameterMappings.get(i);
105                 if (parameterMapping.getMode() != ParameterMode.OUT) {
106                     Object value;
107                     String propertyName = parameterMapping.getProperty();
108                     PropertyTokenizer prop = new PropertyTokenizer(propertyName);
109                     if (parameterObject == null) {
110                         value = null;
111                     } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
112                         value = parameterObject;
113                     } else if (boundSql.hasAdditionalParameter(propertyName)) {
114                         value = boundSql.getAdditionalParameter(propertyName);
115                     } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
116                         value = boundSql.getAdditionalParameter(prop.getName());
117                         if (value != null) {
118                             value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
119                         }
120                     } else {
121                         value = metaObject == null ? null : metaObject.getValue(propertyName);
122                     }
123                     TypeHandler typeHandler = parameterMapping.getTypeHandler();
124                     if (typeHandler == null) {
125                         throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
126                     }
127                     typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
128                 }
129             }
130         }
131     }
132     
133     /**
134      * 根据数据库方言,生成特定的分页sql
135      * @param sql
136      * @param page
137      * @return
138      */
139     private String generatePageSql(String sql,Page page){
140         if(page!=null && dialect!=null && dialect.trim().length()>0){
141             StringBuffer pageSql = new StringBuffer();
142             if("mysql".equals(dialect)){
143                 pageSql.append(sql);
144                 pageSql.append(" limit "+page.getStart()+","+page.getPageShow());
145             }else if("oracle".equals(dialect)){
146                 pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
147                 pageSql.append(sql);
148                 pageSql.append(") as tmp_tb where ROWNUM<=");
149                 pageSql.append(page.getStart()+page.getPageShow());
150                 pageSql.append(") where row_id>");
151                 pageSql.append(page.getStart());
152             }
153             return pageSql.toString();
154         }else{
155             return sql;
156         }
157     }
158     
159     public Object plugin(Object arg0) {
160         // TODO Auto-generated method stub
161         return Plugin.wrap(arg0, this);
162     }
163 
164     public void setProperties(Properties p) {
165         dialect = p.getProperty("dialect");
166 //        if (dialect!=null && dialect.trim().length()>0) {
167 //            System.out.println("dialect property is not found!");
168 //        }
169         pageSqlId = p.getProperty("pageSqlId");
170 //        if (pageSqlId!=null && pageSqlId.trim().length()>0) {
171 //                System.out.println("pageSqlId property is not found!");
172 //        }
173     }
174     
175 }
PagePlugin.java

 

 1 package com.zhou.pageutil;
 2 
 3 import java.lang.reflect.Field;
 4 
 5 /**
 6  * @author Administrator
 7  *    反射工具
 8  */
 9 public class ReflectHelper {
10     
11     /**
12      * 获取obj对象fieldName的Field
13      * @param obj
14      * @param fieldName
15      * @return
16      */
17     public static Field getFieldByFieldName(Object obj, String fieldName) {
18         for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
19                 .getSuperclass()) {
20             try {
21                 return superClass.getDeclaredField(fieldName);
22             } catch (NoSuchFieldException e) {
23             }
24         }
25         return null;
26     }
27 
28     /**
29      * 获取obj对象fieldName的属性值
30      * @param obj
31      * @param fieldName
32      * @return
33      * @throws SecurityException
34      * @throws NoSuchFieldException
35      * @throws IllegalArgumentException
36      * @throws IllegalAccessException
37      */
38     public static Object getValueByFieldName(Object obj, String fieldName)
39             throws SecurityException, NoSuchFieldException,
40             IllegalArgumentException, IllegalAccessException {
41         Field field = getFieldByFieldName(obj, fieldName);
42         Object value = null;
43         if(field!=null){
44             if (field.isAccessible()) {
45                 value = field.get(obj);
46             } else {
47                 field.setAccessible(true);
48                 value = field.get(obj);
49                 field.setAccessible(false);
50             }
51         }
52         return value;
53     }
54 
55     /**
56      * 设置obj对象fieldName的属性值
57      * @param obj
58      * @param fieldName
59      * @param value
60      * @throws SecurityException
61      * @throws NoSuchFieldException
62      * @throws IllegalArgumentException
63      * @throws IllegalAccessException
64      */
65     public static void setValueByFieldName(Object obj, String fieldName,
66             Object value) throws SecurityException, NoSuchFieldException,
67             IllegalArgumentException, IllegalAccessException {
68         try{
69             Field field = obj.getClass().getDeclaredField(fieldName);
70             if (field.isAccessible()) {
71                 field.set(obj, value);
72             } else {
73                 field.setAccessible(true);
74                 field.set(obj, value);
75                 field.setAccessible(false);
76             }
77         }catch(Exception err){
78             //
79         }
80     }
81 }
ReflectHelper.java

 

 1 package com.zhou.pageutil;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.List;
 6 
 7 public class Page<E> implements java.io.Serializable{
 8     
 9     private int pageShow = 2; 
10     private int totalPage;
11     private int totalCount;
12     private int start;
13     private int nowPage;
14     private List<E> result = Collections.emptyList();
15     
16     public int getStart() {
17         start = (getNowPage()-1)*getPageShow();
18         if(start<0){
19             start = 0;
20         }
21         return start;
22     }
23     public void setStart(int start) {
24         this.start = start;
25     }
26     public int getPageShow() {
27         return pageShow;
28     }
29     public void setPageShow(int pageShow) {
30         this.pageShow = pageShow;
31     }
32     public int getTotalCount() {
33         return totalCount;
34     }
35     public void setTotalCount(int totalCount) {
36         this.totalCount = totalCount;
37     }
38     public List<E> getResult() {
39         return result;
40     }
41     public void setResult(List<E> result) {
42         this.result = result;
43     }
44     public void setTotalPage(int totalPage) {
45         this.totalPage = totalPage;
46     }
47     public void setNowPage(int nowPage) {
48         this.nowPage = nowPage;
49     }
50     public int getTotalPage() {
51         return  (int)Math.ceil(totalCount*1.0/pageShow);
52     }
53     public int getNowPage() {
54         if(nowPage<=0)
55             nowPage = 1;
56         if(nowPage>getTotalPage())
57             nowPage = getTotalPage();
58         return nowPage;
59     }
60     @Override
61     public String toString() {
62         return "Page [pageShow=" + pageShow + ", totalPage=" + getTotalPage()
63                 + ", totalCount=" + totalCount + ", nowPage=" + nowPage
64                 + ", result=" + result + "]";
65     }
66     
67     
68 }
Page.java

mapper,xml文件

 1 <?xml version="1.0" encoding="UTF-8" ?>    
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
 3 <mapper namespace="com.zhou.architecture1.customermgr.dao.CustomerDAO">  
 4     
 5      <insert id="create" parameterType="CM">
 6          insert into tbl_customer (customerId,pwd,showName,trueName,registerTime) 
 7           values(#{customerId},#{pwd},#{showName},#{trueName},#{registerTime})
 8      </insert>
 9      <update id="update" parameterType="CM">
10          update tbl_customer set customerId=#{customerId},pwd=#{pwd},
11              showName=#{showName},trueName=#{trueName},registerTime=#{registerTime} 
12                where uuid=#{uuid}
13      </update>
14      <delete id="delete" parameterType="int">
15          delete from tbl_customer where uuid=#{uuid}
16      </delete>
17      
18     <select id="getByUuid" parameterType="int" resultType="CM">  
19         select * from tbl_customer where uuid=#{uuid}
20     </select>  
21     <select id="getByConditionPage" parameterType="CQM" resultType="CM">  
22         select * from tbl_customer
23         <where>
24             <if test="uuid!=null &amp;&amp; uuid > 0">
25                 and uuid=#{uuid}
26             </if>  
27             <if test="customerId!=null &amp;&amp; customerId!=''">
28                 and customerId=#{customerId}
29             </if>
30             <if test="showName!=null &amp;&amp; showName!=''">
31                 and showName=#{showName}
32             </if>
33         </where>
34     </select> 
35 </mapper>
View Code

mapper接口

 1 package com.zhou.architecture1.common.dao;
 2 
 3 import java.util.List;
 4 
 5 public interface BaseDao<M, QM> {
 6 
 7     public void create(M m);
 8     public void update(M m);
 9     public void delete(int uuid);
10     
11     public M getByUuid(int uuid);
12     public List<M> getByConditionPage(QM qm);
13 }
BaseDao.java
 1 package com.zhou.architecture1.customermgr.dao;
 2 
 3 import org.springframework.stereotype.Repository;
 4 
 5 import com.zhou.architecture1.common.dao.BaseDao;
 6 import com.zhou.architecture1.customermgr.vo.CustomerModel;
 7 import com.zhou.architecture1.customermgr.vo.CustomerQueryModel;
 8 
 9 @Repository
10 public interface CustomerDAO extends BaseDao<CustomerModel, CustomerQueryModel>{
11 
12 }
CustomerDAO.java

 queryModel

 1 package com.zhou.architecture1.customermgr.vo;
 2 
 3 import com.zhou.pageutil.Page;
 4 
 5 public class CustomerQueryModel extends CustomerModel {
 6 
 7     private Page<CustomerQueryModel> page = new Page<CustomerQueryModel>();
 8 
 9     public Page<CustomerQueryModel> getPage() {
10         return page;
11     }
12 
13     public void setPage(Page<CustomerQueryModel> page) {
14         this.page = page;
15     }
16 }
CustomerQueryModel.java

测试

 1 package com.zhou;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 import org.springframework.stereotype.Service;
 9 
10 import com.zhou.architecture1.customermgr.dao.CustomerDAO;
11 import com.zhou.architecture1.customermgr.vo.CustomerModel;
12 import com.zhou.architecture1.customermgr.vo.CustomerQueryModel;
13 
14 @Service
15 public class Client {
16     
17     @Autowired
18     private CustomerDAO customerDAO;
19 
20     public static void main(String[] args) {
21         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
22         Client client = (Client)context.getBean("client");
23         
24         CustomerModel customerModel = new CustomerModel();
25         
26         customerModel.setCustomerId("zhou");
27         customerModel.setPwd("124");
28         customerModel.setShowName("老亮");
29         
30         //client.customerDAO.create(customerModel);
31         
32         CustomerQueryModel customerQueryModel = new CustomerQueryModel();
33         //customerQueryModel.setNowPage(2);
34         //customerQueryModel.setPageShow(4);
35         
36         customerQueryModel.getPage().setNowPage(2);
37         customerQueryModel.getPage().setPageShow(3);
38         
39         List<CustomerModel> list = client.customerDAO.getByConditionPage(customerQueryModel);
40         
41         System.out.println(list);
42         
43         
44     }
45     
46 }
View Code

 springmvc xml配置

 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:p="http://www.springframework.org/schema/p"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="
 7        http://www.springframework.org/schema/beans
 8        http://www.springframework.org/schema/beans/spring-beans.xsd
 9        http://www.springframework.org/schema/context
10        http://www.springframework.org/schema/context/spring-context.xsd
11        http://www.springframework.org/schema/mvc
12        http://www.springframework.org/schema/mvc/spring-mvc.xsd"
13     default-lazy-init="true">
14 
15     <!-- 开启controller注解支持 -->
16     <context:component-scan base-package="com.zhou"
17         use-default-filters="false">
18         <context:include-filter type="annotation"
19             expression="org.springframework.stereotype.Controller" />
20     </context:component-scan>
21 
22     <!-- 会自动注册了validator ConversionService -->
23     <mvc:annotation-driven>
24     </mvc:annotation-driven>
25 
26     <mvc:default-servlet-handler />
27     <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
28     
29     <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
30     <bean id="defaultViewResolver"
31         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
32         <property name="viewClass"    value="org.springframework.web.servlet.view.JstlView" />
33         <property name="contentType" value="text/html" />
34         <property name="prefix" value="/WEB-INF/jsp/" />
35         <property name="suffix" value=".jsp" />
36     </bean>
37 </beans>
springmvc xml

web,xml 配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0"
 3          xmlns="http://java.sun.com/xml/ns/javaee"
 4          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 6             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 7 
 8     <display-name>architecture1 web</display-name>
 9 
10     <!-- Spring配置文件开始  -->
11      <context-param>
12          <param-name>contextConfigLocation</param-name>
13          <param-value>
14              classpath:applicationContext.xml
15          </param-value>
16      </context-param>
17      <listener>
18          <listener-class>
19              org.springframework.web.context.ContextLoaderListener
20          </listener-class>
21      </listener>
22      <!-- Spring配置文件结束 -->
23 
24     <!-- 设置servlet编码开始 -->
25     <filter>
26         <filter-name>Set Character Encoding</filter-name>
27         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
28         <init-param>
29             <param-name>encoding</param-name>
30             <param-value>UTF-8</param-value>
31         </init-param>
32         <init-param>
33             <param-name>forceEncoding</param-name>
34             <param-value>true</param-value>
35         </init-param>
36     </filter>
37     <filter-mapping>
38         <filter-name>Set Character Encoding</filter-name>
39         <url-pattern>/*</url-pattern>
40     </filter-mapping>
41 
42     <servlet>
43         <servlet-name>springmvc</servlet-name>
44         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
45         <init-param>
46             <param-name>contextConfigLocation</param-name>
47             <param-value>classpath:spring-mvc.xml</param-value>
48         </init-param>
49         <load-on-startup>1</load-on-startup>
50     </servlet>
51     <servlet-mapping>
52         <servlet-name>springmvc</servlet-name>
53         <url-pattern>/</url-pattern>
54     </servlet-mapping>
55 </web-app>
web.xml

 

posted @ 2015-10-22 20:52  老亮侃码  阅读(288)  评论(0编辑  收藏  举报