记录一次使用Ajax进行分页和MyBatis的学习...

2018-08-17 09:40:56来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

记录一次使用Ajax进行分页和MyBatis的学习...
 
第一次写博客,写得不算好,敬请见谅.
 
1.配置Mybatis.xml
2.配置log4j.properties
3.实体类
4.PageBean类的编写,用于分页使用
5.配置FlowerMapper.xml
6.编写FlowerMapper接口
7.编写过滤器,过滤编码格式;
8.编码格式的xml配置;
9.测试类
10.分页查询,FlowerService接口编写
11.FlowerServiceImpl接口实现类编写
12.FlowerServlet编写
13.导入Jquery文件,重新命名过,使用的3.X版本
14.后端代码编写完成,最后是页面代码编写.
15.页面效果展示
 
 
目录结构:
            搭建环境:导入mybatis的相关jar包,使用gson进行json字符串转换.使用了mysql数据库,导入了mysql驱动包
            
1.配置Mybatis.xml
 
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!-- 开启LOG4J支持 -->
 7     <settings>
 8         <setting name="logImpl" value="LOG4J" />
 9     </settings>
10     <!-- 别名设置 -->
11     <typeAliases>
12         <!-- 设置之后,类名即别名 -->
13         <package name="cn.realmid.pojo" />
14     </typeAliases>
15     <!-- 数据库环境设置 -->
16     <environments default="mysql">
17         <!-- 具体的数据库环境设置 -->
18         <environment id="mysql">
19             <!-- 事务管理设置 -->
20 
21             <transactionManager type="JDBC"></transactionManager>
22             <!-- 数据源设置 -->
23             <dataSource type="POOLED">
24                 <property name="driver" value="com.mysql.jdbc.Driver" />
25                 <property name="url" value="jdbc:mysql://localhost:3306/flower" />
26                 <property name="username" value="root" />
27                 <property name="password" value="assass" />
28             </dataSource>
29         </environment>
30     </environments>
31     <!-- mappers设置 -->
32     <mappers>
33         <!-- mybatis的动态sql设置 -->
34         <package name="cn.realmid.mapper" />
35     </mappers>
36 </configuration>  
37   
View Code

 

2.配置log4j.properties
 
 1 log4j.logger.cn.realmid.mapper=DEBUG, CONSOLE,LOGFILE
 2 
 3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
 4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
 5 log4j.appender.CONSOLE.layout.ConversionPattern=- %l-%d{yyy MMM dd HH:mm:ss}-%m%n
 6 
 7 log4j.appender.LOGFILE=org.apache.log4j.FileAppender
 8 log4j.appender.LOGFILE.File=D:/axis.log
 9 log4j.appender.LOGFILE.Append=true
10 log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
11 log4j.appender.LOGFILE.layout.ConversionPattern=- %l-%d{yyy MMM dd HH:mm:ss}-%m%n
View Code

 

3.实体类
 
 1 package cn.realmid.pojo;
 2 
 3 public class Flower {
 4     private Integer id;
 5     private String name;
 6     private Double price;
 7     private String production;
 8     public Integer getId() {
 9         return id;
10     }
11     public void setId(Integer id) {
12         this.id = id;
13     }
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     public Double getPrice() {
21         return price;
22     }
23     public void setPrice(Double price) {
24         this.price = price;
25     }
26     public String getProduction() {
27         return production;
28     }
29     public void setProduction(String production) {
30         this.production = production;
31     }
32     @Override
33     public int hashCode() {
34         final int prime = 31;
35         int result = 1;
36         result = prime * result + ((id == null) ? 0 : id.hashCode());
37         result = prime * result + ((name == null) ? 0 : name.hashCode());
38         result = prime * result + ((price == null) ? 0 : price.hashCode());
39         result = prime * result + ((production == null) ? 0 : production.hashCode());
40         return result;
41     }
42     @Override
43     public boolean equals(Object obj) {
44         if (this == obj)
45             return true;
46         if (obj == null)
47             return false;
48         if (getClass() != obj.getClass())
49             return false;
50         Flower other = (Flower) obj;
51         if (id == null) {
52             if (other.id != null)
53                 return false;
54         } else if (!id.equals(other.id))
55             return false;
56         if (name == null) {
57             if (other.name != null)
58                 return false;
59         } else if (!name.equals(other.name))
60             return false;
61         if (price == null) {
62             if (other.price != null)
63                 return false;
64         } else if (!price.equals(other.price))
65             return false;
66         if (production == null) {
67             if (other.production != null)
68                 return false;
69         } else if (!production.equals(other.production))
70             return false;
71         return true;
72     }
73     @Override
74     public String toString() {
75         return "Flower [id=" + id + ", name=" + name + ", price=" + price + ", production=" + production + "]";
76     }
77     public Flower(Integer id, String name, Double price, String production) {
78         super();
79         this.id = id;
80         this.name = name;
81         this.price = price;
82         this.production = production;
83     }
84     public Flower() {
85         super();
86         // TODO Auto-generated constructor stub
87     }
88     
89 }
View Code

 

 

4.PageBean类的编写,用于分页使用
 
  1 package cn.realmid.pojo;
  2 
  3 import java.util.Arrays;
  4 import java.util.List;
  5 
  6 /**
  7  * 分页的三个基本属性
  8  * 1.每页几条记录size  可以有默认值5
  9  * 2.当前页号  index    可以有默认值1
 10  * 3.记录总数totalCount:不可能有默认值,需要查询数据库获取真正的记录总数
 11  * 
 12  * 4.一共多少页 :totalPageCount=totalCount/size+1
 13  *         5  30  31 32 33 34 35
 14  * 5.上一页    index-1  当前页1,上一页1
 15  * 6.下一页   index+1  当前页是最后一页  下一页:还是最后一页
 16  * 
 17  * 扩展
 18  * 分页Bean还可以放要查询的数据  protected List<T> list;
 19  * 分页Bean还可以放页码列表     [1]  2  3  4  5   private int[] numbers;
 20  * 
 21  * @author Administrator
 22  *
 23  * @param <T>
 24  */
 25 public class PageBean {
 26     private int size;//每页显示记录     //ok
 27     private int index;// 当前页号       ok       
 28     private int totalPageCount;// 总页数     ok
 29     private int totalCount;// 记录总数    //ok             2
 30     
 31     
 32     private int[] numbers;//展示页数集合 
 33     protected List<Flower> list;//要显示到页面的数据集   
 34 
 35     /**
 36      * 得到开始记录
 37      * @return
 38      * 
 39      */
 40     public int getStartRow() {
 41 
 42         return (index - 1) * size;
 43     }
 44 
 45     /**
 46      * 得到结束记录
 47      * @return
 48      */
 49     public int getEndRow() {
 50         
 51         return index * size;
 52     }
 53 
 54     /**
 55      * @return Returns the size.
 56      */
 57     public int getSize() {        
 58         return size;
 59     }
 60 
 61     /**
 62      * @param size
 63      * The size to set.
 64      */
 65     public void setSize(int size) {
 66         if (size > 0) {
 67             this.size = size;
 68         }
 69     }
 70     /**
 71      * @return Returns the currentPageNo.
 72      */
 73     public int getIndex() {
 74         if (totalPageCount == 0) {
 75             
 76             return 0;
 77         }
 78         
 79         return index;
 80     }
 81 
 82     /**
 83      * @param currentPageNo
 84      * The currentPageNo to set.
 85      */
 86     public void setIndex(int index) {
 87     
 88         if (index > 0) {
 89             
 90             this.index = index;
 91         }
 92     }
 93 
 94     /**
 95      * @return Returns the totalCount.
 96      */
 97     public int getTotalCount() {
 98         return totalCount;
 99     }
100 
101     /**
102      * @param totalCount
103      *  The totalCount to set.
104      */
105     public void setTotalCount(int totalCount) {
106         if (totalCount >= 0) {
107             this.totalCount = totalCount;
108             setTotalPageCountByRs();//根据总记录数计算总页??
109         }
110     }
111 
112     
113     public int getTotalPageCount() {
114         return this.totalPageCount;
115     }
116 
117     /**
118      * 根据总记录数计算总页??
119      * 5   
120      * 20    4
121      * 23    5
122      */
123     private void setTotalPageCountByRs() {
124         if (this.size > 0 && this.totalCount > 0 && this.totalCount % this.size == 0) {
125             this.totalPageCount = this.totalCount / this.size;
126         } else if (this.size > 0 && this.totalCount > 0 && this.totalCount % this.size > 0) {
127             this.totalPageCount = (this.totalCount / this.size) + 1;
128         } else {
129             this.totalPageCount = 0;
130         }
131         setNumbers(totalPageCount);//获取展示页数集合
132     }
133 
134     public int[] getNumbers() {
135         return numbers;
136     }
137     
138     /**
139      * 设置显示页数集合
140      * 
141      * 默认显示10个页码
142      * 41  42  43  44    [45 ]   46  47  48  49  50
143      * 
144      * 
145      *  1 2  3 [4]  5 6 7 8  9  10
146      *  
147      *  41  42  43  44    45    46  47  [48]  49  50
148      * @param totalPageCount
149      */
150     public void setNumbers(int totalPageCount) {
151         if(totalPageCount>0){
152             //!.当前数组的长度
153             int[] numbers = new int[totalPageCount>10?10:totalPageCount];//页面要显示的页数集合
154             int k =0;
155             //
156             //1.数组长度<10   1 2 3 4 ....   7
157             //2.数组长度>=10
158             //     当前页<=6  1 2 3 4    10
159             //     当前页>=总页数-5           ......12 13 14 15  
160             //     其他                                5  6  7 8   9 当前页(10)  10  11 12  13
161             for(int i = 0;i < totalPageCount;i++){
162                 //保证当前页为集合的中??
163                 if((i>=index- (numbers.length/2+1) || i >= totalPageCount-numbers.length) && k<numbers.length){
164                     numbers[k] = i+1;
165                     k++;
166                 }else if(k>=numbers.length){
167                     break;
168                 }                
169             }
170             
171             this.numbers = numbers;
172         }
173         
174     }
175     
176     public void setNumbers(int[] numbers) {
177         this.numbers = numbers;
178     }
179 
180     public List<Flower> getList() {
181         return list;
182     }
183 
184     public void setList(List<Flower> list) {
185         this.list = list;
186     }
187 
188     @Override
189     public String toString() {
190         return "PageBean [size=" + size + ", index=" + index + ", totalPageCount=" + totalPageCount + ", totalCount="
191                 + totalCount + ", numbers=" + Arrays.toString(numbers) + ", list=" + list + "]";
192     }
193     
194     
195 }
View Code

 

 

5.配置FlowerMapper.xml
 
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <!DOCTYPE mapper
  3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5 <mapper namespace="cn.realmid.mapper.FlowerMapper">
  6     
  7     <!-- 查询所有花卉信息 -->
  8     <select id="selF" resultType="flower">
  9         select * from flower
 10     </select>
 11     
 12     <!-- 通过id查询花卉信息 -->
 13     <select id="selFById" resultType="flower">
 14         select * from flower where
 15         id=#{id}
 16     </select>
 17     
 18     <!-- 通过名字和产地查询花卉信息     传基本数据类型-->
 19     <select id="selFByNamePro" resultType="flower">
 20         select * from flower where
 21         name=#{name} and production=#{production}
 22     </select>
 23     
 24     <!-- 传引用数据类型 -->
 25     <select id="selFByNamePro2" resultType="flower">
 26         select * from flower
 27         where name=#{flower.name} and production=#{flower.production}
 28     </select>
 29 
 30     <!-- 插入花卉信息 -->
 31     <insert id="insF">
 32         insert into flower
 33         values(default,#{flower.name},#{flower.price},#{flower.production})
 34     </insert>
 35     
 36     <!-- 更新花卉信息 -->
 37     <update id="upF">
 38         update flower set name=#{name} where id=#{id}
 39     </update>
 40     
 41     <!-- 删除花卉信息 -->
 42     <delete id="delF">
 43         delete from flower where id=#{id}
 44     </delete>
 45 
 46     <!-- **********动态拼接*********** -->
 47     <!-- if标签 -->
 48     <select id="selFByNameProIf" resultType="flower">
 49         select * from flower where 1=1
 50         <if test="name != '' and name != null">
 51             and name=#{name}
 52         </if>
 53         <if test="production != '' and production != null">
 54             and production=#{production}
 55         </if>
 56     </select>
 57     <!-- where标签和if标签结合使用 where标签,去掉第一个and,也就是去掉最近一个and -->
 58     <select id="selFByNameProWhere" resultType="flower">
 59         select * from flower
 60         <where>
 61             <if test="name != '' and name != null">
 62                 and name=#{name}
 63             </if>
 64             <if test="production != '' and production != null">
 65                 and production=#{production}
 66             </if>
 67         </where>
 68     </select>
 69 
 70     <!-- choose标签;第一个条件成立后面的条件就不再判断,类似于java的if-else多条件判断 -->
 71     <select id="selFByNameProChoose" resultType="flower">
 72         select * from flower
 73         <where>
 74             <choose>
 75                 <when test="name != '' and name != null">
 76                     and name=#{name}
 77                 </when>
 78                 <when test="production != '' and production != null">
 79                     and production=#{production}
 80                 </when>
 81                 <otherwise>
 82                     and name='紫玫瑰'
 83                 </otherwise>
 84             </choose>
 85         </where>
 86     </select>
 87 
 88     <!-- set标签:修改时用 -->
 89     <update id="upSet">
 90         update flower
 91         <set>
 92             id=#{id},
 93             <if test="name != '' and name != null">
 94                 name=#{name},
 95             </if>
 96             <if test="production != '' and production != null">
 97                 production=#{production},
 98             </if>
 99         </set>
100         where id=#{id}
101     </update>
102 
103     <!-- trim标签:可以动态设置... -->
104     <update id="upTrim">
105         update flower
106         <trim prefix="set" suffixOverrides=",">
107             id=#{id},
108             <if test="name != '' and name != null">
109                 name=#{name},
110             </if>
111             <if test="production != '' and production != null">
112                 production=#{production},
113             </if>
114         </trim>
115         where id=#{id}
116     </update>
117     <!-- foreach标签:主要和IN关键字搭配使用 ;可以用于批量删除 -->
118     <select id="selFForEach" resultType="flower">
119         select * from flower where id IN
120         <foreach collection="list" open="(" separator="," close=")"
121             item="i">
122             #{i}
123         </foreach>
124     </select>
125 
126     <!-- 分页查询 -->
127     <!-- bind标签 -->
128     <select id="selFPageing" resultType="flower">
129         select <include refid="real"/> from flower
130         <where>
131             <if test="name != '' and name != null">
132                 <bind name="name" value="'%'+name+'%'" />
133                 and name like #{name}
134             </if>
135             <if test="production != '' and production != null">
136                 <bind name="pro" value="'%'+production+'%'" />
137                 and production like #{pro}
138             </if>
139         </where>
140         limit #{index},#{size}
141     </select>
142     <!-- 查询信息条数 -->
143     <select id="selFCount" resultType="int">
144         SELECT count(*) FROM flower
145         <where>
146             <if test="name != '' and name != null">
147                 <bind name="name" value="'%'+name+'%'" />
148                 and name like #{name}
149             </if>
150             <if test="production != '' and production != null">
151                 <bind name="pro" value="'%'+production+'%'" />
152                 and production like #{pro}
153             </if>
154         </where>
155     </select>
156     <!-- sql标签
157             可以设置查询表的那些字段
158         include标签
159             动态引入sql标签设置的查询字段
160         在进行数据查询时,不能使用*查询所有,但是对于查询字段较多的,可以达到复用性,这样比较方便,维护升级比较方便,
161      -->
162     <sql id="real">
163         id,name,price,production
164     </sql>
165 </mapper>
166   
167   
View Code

 

6.编写FlowerMapper接口
 
  1 package cn.realmid.mapper;
  2 
  3 import java.util.List;
  4 
  5 import org.apache.ibatis.annotations.Param;
  6 
  7 import cn.realmid.pojo.Flower;
  8 
  9 public interface FlowerMapper {
 10     /**
 11      * 查询所有花卉信息
 12      * 
 13      * @return
 14      */
 15     List<Flower> selF();
 16 
 17     /**
 18      * 通过id查询花卉信息
 19      * 
 20      * @param id
 21      * @return
 22      */
 23     Flower selFById(@Param("id") Integer id);
 24 
 25     /**
 26      * 通过名字和产地查询花卉信息
 27      * 
 28      * @param name
 29      * @param production
 30      * @return
 31      */
 32     List<Flower> selFByNamePro(@Param("name") String name, @Param("production") String production);
 33 
 34     /**
 35      * 通过名字和产地查询花卉信息
 36      * 
 37      * @param flower
 38      * @return
 39      */
 40     List<Flower> selFByNamePro2(@Param("flower") Flower flower);
 41 
 42     /**
 43      * 插入一条花卉信息
 44      * 
 45      * @param flower
 46      * @return
 47      */
 48     Integer insF(@Param("flower") Flower flower);
 49 
 50     /**
 51      * 修改花卉信息
 52      * 
 53      * @param name
 54      * @param id
 55      * @return
 56      */
 57     Integer upF(@Param("name") String name, @Param("id") Integer id);
 58 
 59     /**
 60      * 通过id删除花卉信息
 61      * 
 62      * @param id
 63      * @return
 64      */
 65     Integer delF(@Param("id") Integer id);
 66     /* ****************动态拼接**************** */
 67 
 68     /**
 69      * 通过名字和产地查询花卉信息--if
 70      * 
 71      * @param name
 72      * @param production
 73      * @return
 74      */
 75     List<Flower> selFByNameProIf(@Param("name") String name, @Param("production") String production);
 76 
 77     /**
 78      * 通过名字和产地查询花卉信息--where
 79      * 
 80      * @param name
 81      * @param production
 82      * @return
 83      */
 84     List<Flower> selFByNameProWhere(@Param("name") String name, @Param("production") String production);
 85     /**
 86      * 通过名字和产地查询花卉信息--choose
 87      * 
 88      * @param name
 89      * @param production
 90      * @return
 91      */
 92     List<Flower> selFByNameProChoose(@Param("name") String name, @Param("production") String production);
 93     /**
 94      * 修改花卉信息--set
 95      * 
 96      * @param name
 97      * @param production
 98      * @return
 99      */
100     Integer upSet(@Param("name") String name, @Param("production") String production,@Param("id")Integer id);
101     /**
102      * 修改花卉信息--trim
103      * 
104      * @param name
105      * @param production
106      * @return
107      */
108     Integer upTrim(@Param("name") String name, @Param("production") String production,@Param("id")Integer id);
109     /**
110      * 传入list集合,查询id再此集合内的花卉信息--foreach
111      * @param list
112      * @return
113      */
114     List<Flower> selFForEach(@Param("list")List<Integer> list);
115     /**
116      * 分页查询
117      * @param name
118      * @param production
119      * @param index
120      * @param size
121      * @return
122      */
123     List<Flower> selFPageing(@Param("name")String name,@Param("production")String production,@Param("index")Integer index,@Param("size")Integer size);
124     /**
125      * 查询flower数据总条数
126      * @return
127      */
128     Integer selFCount(@Param("name")String name,@Param("production")String production);
129 }
View Code

 

7.编写过滤器,过滤编码格式;
 
 1 package cn.realmid.filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 
12 public class FilterEncoding implements Filter {
13     private String charset = "UTF-8";//默认使用utf-8
14     @Override
15     public void destroy() {
16 
17     }
18 
19     @Override
20     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
21             throws IOException, ServletException {
22             request.setCharacterEncoding(this.charset);
23             response.setCharacterEncoding(this.charset);
24             chain.doFilter(request, response);//允许通行
25     }
26 
27     @Override
28     public void init(FilterConfig filterConfig) throws ServletException {
29         if (filterConfig.getInitParameter("charset") != null) { //读取web.xml里面初始化参数,不为空执行
30             this.charset = filterConfig.getInitParameter("charset"); //使用web.xml里面初始化参数的编码格式
31         }
32     }
33 
34 }
View Code

 

8.编码格式的xml配置;
 
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 4     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 5     id="WebApp_ID" version="3.1">
 6     
 7     <display-name>Flower</display-name>
 8     
 9     <filter>
10         <filter-name>EncodingFilter</filter-name>
11         <filter-class>cn.realmid.filter.FilterEncoding</filter-class>
12         <init-param>
13             <param-name>charset</param-name>
14             <param-value>UTF-8</param-value>
15         </init-param>
16     </filter>
17     <filter-mapping>
18         <filter-name>EncodingFilter</filter-name>
19         <url-pattern>/*</url-pattern>
20     </filter-mapping>
21     
22     
23     <welcome-file-list>
24         <welcome-file>index.html</welcome-file>
25         <welcome-file>index.htm</welcome-file>
26         <welcome-file>index.jsp</welcome-file>
27         <welcome-file>default.html</welcome-file>
28         <welcome-file>default.htm</welcome-file>
29         <welcome-file>default.jsp</welcome-file>
30     </welcome-file-list>
31 </web-app>
View Code

 

9.测试类
 
 1 package cn.realmid.test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.io.Resources;
 9 import org.apache.ibatis.session.SqlSession;
10 import org.apache.ibatis.session.SqlSessionFactory;
11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
12 
13 import cn.realmid.mapper.FlowerMapper;
14 import cn.realmid.pojo.Flower;
15 
16 public class TestDemo {
17 
18     public static void main(String[] args) throws IOException {
19     
20         //获取SqlSession对象
21         InputStream is = Resources.getResourceAsStream("mybatis.xml");
22         SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
23         SqlSession ss = factory.openSession();
24         
25         //通过动态代理生成FlowerMapper接口的实现类对象
26         FlowerMapper mapper = ss.getMapper(FlowerMapper.class);
27         
28         /*//查询
29         List<Flower> selF = mapper.selF();
30         System.out.println(selF);
31         
32         Flower selFById = mapper.selFById(1);
33         System.out.println(selFById);
34         
35         List<Flower> selFByNamePro = mapper.selFByNamePro("白玫瑰", "中国");
36         System.out.println(selFByNamePro);
37         
38         List<Flower> selFByNamePro2 = mapper.selFByNamePro2(new Flower(10, "白玫瑰", 18.88, "中国"));
39         System.out.println(selFByNamePro2);
40         
41         //增删改
42         Integer insF = mapper.insF(new Flower(10, "紫玫瑰", 18.88, "中国"));
43         ss.commit();
44         System.out.println(insF);
45         
46         Integer upF = mapper.upF("蓝玫瑰", 6);
47         ss.commit();
48         System.out.println(upF);
49         
50         Integer delF = mapper.delF(11);
51         ss.commit();
52         System.out.println(delF);
53         */
54         
55         /*List<Flower> selFByNameProIf = mapper.selFByNameProIf("白玫瑰", "中国");
56         System.out.println(selFByNameProIf);
57         
58         List<Flower> selFByNameProWhere = mapper.selFByNameProWhere("白玫瑰", "中国");
59         System.out.println(selFByNameProWhere);
60         
61         List<Flower> selFByNameProChoose = mapper.selFByNameProChoose("", "");
62         System.out.println(selFByNameProChoose);
63         
64         Integer upSet = mapper.upSet("白玫瑰", "中国",17);
65         System.out.println(upSet);
66         
67         Integer upTrim = mapper.upTrim("白玫瑰", "中国",18);
68         System.out.println(upTrim);
69         
70         ArrayList<Integer> list = new ArrayList<Integer>();
71         list.add(1);
72         list.add(2);
73         list.add(3);
74         List<Flower> selFForEach = mapper.selFForEach(list);
75         System.out.println(selFForEach);*/
76         
77         List<Flower> selFPageing = mapper.selFPageing("玫瑰", "中国", 1, 10);
78         System.out.println(selFPageing);
79         
80     }
81 }
View Code

 

10.分页查询,FlowerService接口编写
 1 package cn.realmid.service;
 2 
 3 
 4 import org.apache.ibatis.annotations.Param;
 5 
 6 import cn.realmid.pojo.PageBean;
 7 
 8 public interface FlowerService {
 9     /**
10      * 分页查询
11      * @param name
12      * @param production
13      * @param index
14      * @param size
15      * @return
16      */
17     PageBean getFlowerInfoService(@Param("name")String name,@Param("production")String production,@Param("index")Integer index,@Param("size")Integer size);
18 
19 }
View Code

 

11.FlowerServiceImpl接口实现类编写
 1 package cn.realmid.service.impl;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.List;
 6 
 7 import org.apache.ibatis.io.Resources;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactory;
10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
11 
12 import cn.realmid.mapper.FlowerMapper;
13 import cn.realmid.pojo.Flower;
14 import cn.realmid.pojo.PageBean;
15 import cn.realmid.service.FlowerService;
16 
17 public class FlowerServiceImpl implements FlowerService {
18 
19     @Override
20     public PageBean getFlowerInfoService(String name, String production, Integer index, Integer size) {
21         SqlSession ss = null;
22         List<Flower> list = null;
23         PageBean page = null;
24         try {
25             //获取SqlSession对象
26             InputStream is = Resources.getResourceAsStream("mybatis.xml");
27             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
28             ss = factory.openSession();
29             
30             //获取FlowerMapper接口实例化对象
31             FlowerMapper mapper = ss.getMapper(FlowerMapper.class);
32             
33             //查询数据
34             list = mapper.selFPageing(name, production, (index-1)*size, size);
35             //查询数据总条数
36             Integer totalCount = mapper.selFCount(name, production);
37             
38             //System.out.println("-----------------------------"+list);
39             
40             page = new PageBean();
41             page.setSize(size);
42             page.setIndex(index);
43             page.setTotalCount(totalCount);
44             page.setList(list);
45             
46         } catch (IOException e) {
47             e.printStackTrace();
48         } finally {
49             if (null != ss) {
50                 ss.close();
51             }
52         }
53 
54         return page;
55     }
56 
57 }
View Code
12.FlowerServlet编写
 
 1 package cn.realmid.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.google.gson.Gson;
12 
13 import cn.realmid.pojo.PageBean;
14 import cn.realmid.service.FlowerService;
15 import cn.realmid.service.impl.FlowerServiceImpl;
16 
17 @WebServlet({ "/FlowerServlet", "/fs" })
18 public class FlowerServlet extends HttpServlet {
19     private static final long serialVersionUID = 1L;
20        
21     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
22         //获取前台发送过来的数据
23         String name = request.getParameter("name");
24         String production = request.getParameter("production");
25         Integer index = Integer.valueOf(request.getParameter("index"));
26         Integer size = Integer.valueOf(request.getParameter("size"));
27         
28         //System.out.println("  name--->"+name+"  production--->"+production+"   index--->"+index+"   size--->"+size);
29         //调用业务层处理数据
30         FlowerService service = new FlowerServiceImpl();
31         PageBean page = service.getFlowerInfoService(name, production, index, size);
32         //System.out.println(page);
33         //返回json数据
34         response.getWriter().write(new Gson().toJson(page));
35         
36     }
37 
38 }
View Code

 

13.导入Jquery文件,重新命名过,使用的3.X版本
 
14.后端代码编写完成,最后是页面代码编写.
 
  1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2 <%
  3     String path = request.getContextPath();
  4     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
  5             + path + "/";
  6 %>
  7 
  8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9 <html>
 10 <head>
 11 <base href="<%=basePath%>">
 12 
 13 <title>My JSP 'index.jsp' starting page</title>
 14 <meta http-equiv="pragma" content="no-cache">
 15 <meta http-equiv="cache-control" content="no-cache">
 16 <meta http-equiv="expires" content="0">
 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 18 <meta http-equiv="description" content="This is my page">
 19 <!--
 20     <link rel="stylesheet" type="text/css" href="styles.css">
 21     -->
 22     <!-- 导入Jquery文件 -->
 23 <script type="text/javascript" src="js/js.js"></script>
 24 <script type="text/javascript">
 25     $(function() {
 26         var index = 1; /* 下标 */
 27         var size = 5; /* 每页显示的数据条数 */
 28         var totalPageCount; /* 总页数 */
 29         var totalCount; /* 数据总条数  */
 30         var numbers; /* 页数集合 */
 31         
 32         var len=5;/* 选择每页显示的数据--以多少为跨度 */
 33         
 34         var na = $("#name").val();/* 全局变量,name花卉名字 */
 35         var pro = $("#production").val();/* 全局变量,pro产地 */
 36 
 37         /* 点击up进行上一页查询 */
 38         $("#up").click(function() {
 39             if (index > 1) {/* 当所处页数index大于1时,可以点击上一页 */
 40                 getData(na, pro, index - 1, size);
 41             } else {
 42                 console.log("已经是第一页了")
 43             }
 44         })
 45         /* 点击next进行下一页查询 */
 46         $("#next").click(function() {
 47             if (index < totalPageCount) {/* 当所处页数index小于最大页数totalPageCount时,可以点击下一页 */
 48                 getData(na, pro, index + 1, size);
 49             } else {
 50                 console.log("已经是最后一页了")
 51             }
 52         })
 53         /* 点击 查询  进行模糊查询 */
 54         $("#but").click(function() {
 55             na = $("#name").val();/* 获取花卉名字,并将其赋值给全局变量na */
 56             pro = $("#production").val();/* 获取花卉产地并将其赋值的给全局变量pro */
 57             index=1;
 58             getData(na, pro, index, size);
 59 
 60         })
 61         /* 当每页显示条数发生改变时 */
 62         $("#pageSize").change(function() {
 63             size = $("#pageSize").val();/* 获取值pageSize的值并将值赋值给全局变量size */
 64             index=1;/* 当页面显示条数发生改变时,从第一页开始展示数据 */
 65             getData(na, pro, index, size);
 66         })
 67         
 68         /* 点击下标,显示对应数据 */
 69         $("#index").on('click','a',function(){/* 为a标签动态绑定事件 */
 70             index = $(this).attr("data");/* 获取链接里面的页码 */
 71             getData(na, pro, index, size)
 72         })
 73         
 74         /* 得到所有参数 */
 75         getData(na, pro, index, size);
 76         
 77         function getData(na, pro, indexs, size) {
 78             $.post("fs", {
 79                 name : na,
 80                 production : pro,
 81                 index : indexs,
 82                 size : size
 83             }, function(data) {
 84                 eval("var res=" + data);
 85                 index = indexs;
 86                 /* 将取得的数据存入js对象里面 */
 87                 size = res.size;
 88                 index = res.index;
 89                 totalPageCount = res.totalPageCount;
 90                 totalCount = res.totalCount;
 91                 numbers = res.numbers;
 92 
 93                 /* console.log("--------------------------------------------------");
 94                 console.log("  ----size-->" + size +
 95                     " ---- index-->" + index +
 96                     " ---- totalPageCount-->" + totalPageCount +
 97                     " ---- totalCount-->" + totalCount +
 98                     " ---- numbers-->" + numbers);*/
 99                     
100                 var tb = $("#tb");/* 展示查询回来的数据 */
101                 tb.empty();
102                 for (var i = 0; i < res.list.length; i++) {
103                     tb.append(
104                         "<tr>" +
105                         "<td>" + res.list[i].name + "</td>" +
106                         "<td>" + res.list[i].price + "</td>" +
107                         "<td>" + res.list[i].production + "</td>" +
108                         "</tr>"
109                     );
110                 }
111                 
112                 /* 进行每页显示数据条数显示 */
113                 var leng=Math.ceil(totalCount/len);/* 20/5 表示每页显示以5为一个跨度 */
114                 var sizs = $("#pageSize");
115                 sizs.empty();
116                 for (var i = 1; i <= leng; i++) {
117                     if(size == i*len){
118                         sizs.append(/* 表示页面选择的每页显示数据条数  */
119                             "<option value='" + i * len + "' selected='selected'>" + i * len + "</option>"
120                         );
121                     }else{
122                         sizs.append(
123                             "<option value='" + i * len + "'>" + i * len + "</option>"
124                         );
125                     }
126                 }
127         
128                 /* 进行下标数据显示 */
129                  var indexs = $("#index");
130                 indexs.empty();
131                 for (var i = 1; i <= totalPageCount; i++) {
132                     if(i == index){
133                         indexs.append(
134                          '&nbsp;&nbsp;[<a href="javascript:void(0)" id="res" data="'+i+'">'+i+'</a>]&nbsp;&nbsp;'
135                          );
136                     }else{
137                         indexs.append(
138                          '&nbsp;&nbsp;<a href="javascript:void(0)" id="res" data="'+i+'">'+i+'</a>&nbsp;&nbsp;'
139                      );
140                     }
141                 } 
142                 
143                 var pages = $("#pageCount");
144                 pages.empty();
145                 pages.append("<span>总页数:[" + totalPageCount + "];数据总条数:[" + totalCount + "]</span>");
146             });
147         }
148     
149     })
150     
151 </script>
152 </head>
153 
154 <body>
155     <h3>花卉信息查询</h3>
156     花卉的名字 :
157     <input type="text" name="name" id="name" value="" /> 花卉的产地 :
158     <input type="text" name="production" id="production" value="" />
159     <input type="button" name="but" id="but" value="查询" />
160     <hr />
161     <table border="1px" cellpadding="10px" cellspacing="0px">
162         <thead>
163             <tr>
164                 <td>花名</td>
165                 <td>价格</td>
166                 <td>产地</td>
167             </tr>
168         </thead>
169         <tbody id="tb">
170         </tbody>
171     </table>
172     <a href="javascript:void(0)" id="up">上一页</a>&nbsp;&nbsp;
173     <span id="index"> 
174     
175     </span>
176     <a href="javascript:void(0)" id="next">下一页</a> &nbsp;&nbsp;
177     <hr />
178     每页显示的数据:
179     <select id="pageSize">
180 
181     </select>182     <hr />
183     <span id="pageCount"></span>
184 </body>
185 </html>
View Code

 

15.页面效果展示
 
 
 
 
 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:十年阿里顶级架构师教你怎么使用Java来搭建微服务

下一篇:直接调用线程的run方法是否可以启动线程?