2018-09-13 16:23:45 dongyang1124 阅读数 420

前台表格插件多种样,以前用过datatable以及gridtable,这次想要尝试一个新的,就选择了bootstrap table,主要是界面定了想要用bootstrap设计界面,所以就选择了这个,bootstrap table 官网为http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/,里面对表格各种问题都有详细描述。好了,不多说了,下面来详细说明bootstrap table编写的步骤。
1、引入文件

<!-- 引入bootstrap css文件 -->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!-- 引入bootstrap table css文件 -->
<link href="../css/bootstrap-table.css" rel="stylesheet">
<!-- 引入jquery文件 -->
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/bootstrap-table.js"></script>
<!-- 引入中文语言包 -->
<script src="../js/bootstrap-table-locale-all.js"></script>

从网上下载这些文件,然后放到指定文件夹下面
2、bootstrap table js 为了以后方便应用,我把js提取出来放到单独js里面,然后传参,只要传过去的参数符合要求,就可以在界面上展示改表格。

/**
 * bootstrap分页方法
 */
var TableInitSearch = function() {
    var oTableInit = new Object();
    //oTableInit.bootstrapTable('destroy');  
    // 初始化Table
    oTableInit.Init = function(id, url,columns,searchArgs) {
        //---先销毁表格 ---
        $(id).bootstrapTable('destroy');  
        $(id).bootstrapTable({
            url : url, // 请求后台的URL(*)
             method: 'post',
             contentType: "application/x-www-form-urlencoded",
             //【查询设置】
             /* queryParamsType的默认值为 'limit' ,在默认情况下 传给服务端的参数为:offset,limit,sort
                               设置为 ''  在这种情况下传给服务器的参数为:pageSize,pageNumber */
             queryParamsType:'', 
             striped : false, // 是否显示行间隔色
             cache : false, // 是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
             toolbar : '#toolbar', // 工具按钮用哪个容器
             queryParams: function queryParams(params) {  
               var param = {  
                   pageNumber: params.pageNumber,    //后台接收的时候为pageNumber
                   pageSize: params.pageSize //后台接收的时候为pageSize
               }; 
               for(var key in searchArgs){
                   param[key]=searchArgs[key]//此处查询时向后台传递的参数
               }  
               return param;                   
             }, 
             //【其它设置】
             locale:'zh-CN',//中文支持
             pagination: true,//是否开启分页(*)
             sortOrder : "asc", // 排序方式
             pageNumber:1,//初始化加载第一页,默认第一页
             pageSize: 10,//每页的记录行数(*)
             pageList: [ 10, 25, 50, 100 ], // 可供选择的每页的行数(*)
             sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
             search : false, // 是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
             strictSearch : true,
             minimumCountColumns : 2, // 最少允许的列数
             clickToSelect : true, // 是否启用点击选中行
             showRefresh:false,//刷新按钮
             //【样式设置】
              height: 500,//table的高度
             cardView : false, // 是否显示详细视图
             detailView : false, // 是否显示父子表
            columns : columns,
        });

    };
    return oTableInit;
};

从上图可以看出需要传递三个参数,id ,传到后台的url,以及column。
3、jsp界面

<table id="table"></table>
<script>
var id = "#table";
var  url = "${pageContext.request.contextPath}/user/userlist";
var  columns = [
                {
                    field : 'id',
                    title : '用户编号',
                    align : 'center',
                    valign : 'middle'
                },
                {
                    field : 'name',
                    title : '姓名',
                    align : 'center',
                    valign : 'middle'
                },
                {
                    field : 'age',
                    title : '年龄',
                    align : 'center',
                    valign : 'middle'
                }];
//1.初始化Table
var oTable = new TableInitSearch();
var searchArgs = {
        id:null,
        name:null
}
//界面初始化
$(function() {
            oTable.Init(id, url, columns, searchArgs);
        });
function toSearch() {
var name= $("input[name='name']").val();//获得input框输入的name值
var id= $("input[name='id']").val();//获得input框输入的id值
    searchArgs = {
        id: id,
        name: name
    }
    oTable.Init(id, url, columns, searchArgs);                          
} 
</script>

4、后台 conctroller

@RequestMapping("/userlist")
@ResponseBody 
//ajax调用
public Map<String, Object> getUsers(Integer pageSize,
        Integer pageNumber,String name,String id) {
    Map<String, Object> result = new HashMap<String, Object>();
    List<User> userlist = ........//此处为后台调用获取用户的方法
    result.put("total", total);//获取列表总数量
    result.put("rows", userlist);/获取用户数list
}

果然是不写不知道,一写就真的了解别人真的不是没写,有些东西真的是下意识的忽略。

2016-04-28 22:51:32 u010915032 阅读数 3567

一..分页思路

有两张分页的方式:1.查询所有数据,在前段分页。2.根据页面返回值查询相应数据。方式一明显当数据量太大时,对数据库和服务器造成压力过大,而且比较浪费带宽。

二.实现思路

页面所需参数:总页面数,当前页码,需要显示的数值。可以讲前两个分装到一个Page类中,数值放入map中传给前端页面

初始化bootstrap-paginator 

ajax请求获取json对象,动态生成html元素

三.主要代码

相应页面html代码,需引入bootstrap样式

<div class="row">
	<table class="table table-striped">
		<thead>
			<tr>
				<th>菜品名称</th>
				<th>菜品类型</th>
				<th>菜品描述</th>
				<th>菜品价格</th>
				<th>..</th>
			</tr>
		</thead>
		<tbody id="example">
			<c:forEach items="${list}" var="food" varStatus="status">
				<tr>
					<td>${food.foodName}</td>
					<td>${food.foodTypeId}</td>
					<td>${food.description}</td>
					<td>${food.priceSelling}</td>
					<td><a href="rest/food/getInfo?id=${ food.id}">详情</a></td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
</div>

<div align="center">
	<div id="page"></div>
</div>
相应js代码,需引入相关js文件(jquery, bootstrap,bootstrap-paginator)

<script type='text/javascript'>
					//根据第一次传递进来的值初始化分页插件
					var options = {
						currentPage: ${page.pageNow},
						totalPages: ${page.totalPageCount},
						numberOfPages:5,
						itemTexts: function (type, page, current) {
				              switch (type) {
				                case "first":
				                  return "首页";
				                case "prev":
				                  return "上一页";
				                case "next":
				                  return "下一页";
				                case "last":
				                  return "末页";
				                case "page":
				                  return page;
				              }
				            },
				      //事件响应
					 onPageClicked: function (event, originalEvent, type, page) {
						 	//异步访问数据
				            $.ajax({
				              url: "<%=basePath%>rest/food/queryByCriteria?pn="+page,
				              type: "post",
				              date: "",
				              success: function (data1) {
				            	  $("#example").empty();
				            	  page = data1.page;
				               	  list = data1.list;
				               	 if (list != null) {
				                	$.each( list, function(index, food){  
				                		var html = '<tr>'+//
	              						   '<td>'+food.id+'<td/>'+//
	              						   '<td>'+food.foodName+'<td/>'+//
	              						   '<td>'+food.foodTypeId+'<td/>'+//
	              						   '<td>'+food.description+'<td/>'+//
	              						   '<td>'+food.priceSelling+'<td/>'+//
	              						   '<td><a href="rest/food/getInfo?id='+food.id+'">详情</a></td>'+//
	              						   '</tr>';
											$("#example").append(html);	
				                		});
				                	}else{
				                		$("example").append('没有找到相应数据');
				                	}
				                }
				            });
				          }
					}
					//初始化分页插件
					$('#page').bootstrapPaginator(options);
				</script>
    后台相关代码

Page.class

import java.io.Serializable;

/**
 * 分页
 */
public class Page implements Serializable {

	private static final long serialVersionUID = -3198048449643774660L;

	private int pageNow = 1; // 当前页数

	private int pageSize = 5; // 每页显示记录的条数

	private int totalCount; // 总的记录条数

	private int totalPageCount; // 总的页数

	@SuppressWarnings("unused")
	private int startPos; // 开始位置,从0开始

	@SuppressWarnings("unused")
	private boolean hasFirst;// 是否有首页

	@SuppressWarnings("unused")
	private boolean hasPre;// 是否有前一页

	@SuppressWarnings("unused")
	private boolean hasNext;// 是否有下一页

	@SuppressWarnings("unused")
	private boolean hasLast;// 是否有最后一页

	/**
	 * 通过构造函数 传入 总记录数 和 当前页
	 * 
	 * @param totalCount
	 * @param pageNow
	 */
	public Page(int totalCount, int pageNow) {
		this.totalCount = totalCount;
		this.pageNow = pageNow;
	}

	/**
	 * 取得总页数,总页数=总记录数/总页数
	 * 
	 * @return
	 */
	public int getTotalPageCount() {
		totalPageCount = getTotalCount() / getPageSize();
		return (totalCount % pageSize == 0) ? totalPageCount : totalPageCount + 1;
	}

	public void setTotalPageCount(int totalPageCount) {
		this.totalPageCount = totalPageCount;
	}

	public int getPageNow() {
		return pageNow;
	}

	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	/**
	 * 取得选择记录的初始位置
	 * 
	 * @return
	 */
	public int getStartPos() {
		return (pageNow - 1) * pageSize;
	}

	public void setStartPos(int startPos) {
		this.startPos = startPos;
	}

	/**
	 * 是否是第一页
	 * 
	 * @return
	 */
	public boolean isHasFirst() {
		return (pageNow == 1) ? false : true;
	}

	public void setHasFirst(boolean hasFirst) {
		this.hasFirst = hasFirst;
	}

	/**
	 * 是否有首页
	 * 
	 * @return
	 */
	public boolean isHasPre() {
		// 如果有首页就有前一页,因为有首页就不是第一页
		return isHasFirst() ? true : false;
	}

	public void setHasPre(boolean hasPre) {
		this.hasPre = hasPre;
	}

	/**
	 * 是否有下一页
	 * 
	 * @return
	 */
	public boolean isHasNext() {
		// 如果有尾页就有下一页,因为有尾页表明不是最后一页
		return isHasLast() ? true : false;
	}

	public void setHasNext(boolean hasNext) {
		this.hasNext = hasNext;
	}

	/**
	 * 是否有尾页
	 * 
	 * @return
	 */
	public boolean isHasLast() {
		// 如果不是最后一页就有尾页
		return (pageNow == getTotalCount()) ? false : true;
	}

	public void setHasLast(boolean hasLast) {
		this.hasLast = hasLast;
	}

}
FoodController相关方法

//第一次点击链接
@RequestMapping(value = "/query", method = RequestMethod.GET)
public String query(HttpServletRequest request, Map<String, Object> map) {
	FoodExample example = new FoodExample();
	List<Food> listSize = foodService.selectFoodByExample(example);
	// 默认为pageNow = 1
	Page page = new Page(listSize.size(), 1);
	List<Food> list = foodService.selectFoodByExampleAndPage(example, 1, page.getPageSize());
	map.put("page", page);
	map.put("list", list);
	return "foodAction/list";
}

//获取json对象
@RequestMapping(value = "/queryByCriteria", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> queryByFoodPrice(HttpServletRequest request) {
	Map<String, Object> map = new HashMap<String, Object>();
	FoodExample example = new FoodExample();
	FoodExample.Criteria criteria = example.createCriteria();
	String pageNow = request.getParameter("pn");
	int pn = 1;
	if (pageNow != "" & pageNow != null) {
		pn = new Integer(pageNow);
	}
	List<Food> listSize = foodService.selectFoodByExample(example);
	Page page = new Page(listSize.size(), pn);
	List<Food> list = foodService.selectFoodByExampleAndPage(example, pn, page.getPageSize());
	map.put("page", page);
	map.put("list", list);
	return map;
}

四.总结

以上就是结合spring mvc ajax bootstrap-paginator  分页实现过程,其中初始化 bootstrap-paginator  的时候可能会出现分页插件不是水平摆放问题,具体解决方法需要将bootstrap-paginator.js里的listContainer = $("<ul></ul>"),改成listContainer = $("<ul class='pagination'></ul>")。注意spring mvc的配置能正确返回json数据


------------------------------------------------------------------------------------------2017/04/16 更新-------------------------------------------------------------------------------------------------------------------

项目源码

2018-12-13 18:30:25 linsongbin1 阅读数 3127

概述


有时候我们是需要将bootstrap.yml文件的外置的,也即是说,在spring boot应用启动后,不直接使用jar包里面的bootstrap.yml文件,而是读取某个目录下的bootstrap.yml文件,然后进行覆盖。注意在spring boot 2.0之前的版本,得使用如下参数:

spring.config.location

完整配置如下:

nohup java $JAVA_OPTS -jar xxxx.jar --spring.config.location=/data/sc_config/bootstrap.yml

而如果是spring boot 2.0以及以后的版本,可以使用:

spring.cloud.bootstrap.location

完整配置如下:

nohup java $JAVA_OPTS -jar xxxx.jar --spring.cloud.bootstrap.location=/data/sc_config/bootstrap.yml
2016-03-06 14:44:13 linuu 阅读数 7169

准备环境:JDK1.7+MAVEN+Eclipse

1) 打开Eclipse 点击Window-->Preferences-->Maven--->User Settings 配置一下你的Maven配置文件setting.xml


2)新建Maven项目

记得勾选红色方框中的钩,点击Next,出现如下:

将packaging中的jar修改成pom,如上图所示,Group Id为你的基本包名,可以任意命名,点击Finish,完成后出现

打开study-pom中的pom.xml,添加如下基本依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.lyncc</groupId>
	<artifactId>study-pom</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<properties>
		<spring.version>4.0.1.RELEASE</spring.version>
		<mybatis.version>3.2.4</mybatis.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.0.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.11</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.4</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.2-GA</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.28</version>
		</dependency>

		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
	</dependencies>

</project>
3)新建Maven模块Maven Module

选择Maven Module然后点击Next,如下


Module Name输入study-intf(该maven模块是接口模块),然后点击Browse

选择study-pom然后点击ok,回到上个窗口,点击Next,出现:

选择如上图红色框框选中的quickstart,点击NEXT:

点击Finish,如下图:

4)再次新建maven模块,模块名为study-service(service模块),新建方法与上述步骤3中一致,只是在Moudle Name修改为study-service,建立好如下图所示:


5)新建maven-moudle,模块名为study-web

点击Next


选择webapp,点击Next:

点击Finish:

分别打开study-intf,service,web模块中的pom.xml文件,将有黄色下划线的去掉,否则项目会有warning警告),例外,依次修改study-intf,service,web的默认依赖的jdk版本,分别右击项目模块,然后依次修改为


然后依次修改pom的依赖

study-intf下的pom.xml如下:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-intf</artifactId>
  <name>study-intf</name>
  <url>http://maven.apache.org</url>
 
</project>
study-service下的pom.xml如下:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-service</artifactId>
  <name>study-service</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.lyncc</groupId>
      <artifactId>study-intf</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>
study-web下的pom.xml需要添加web的依赖

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.lyncc</groupId>
    <artifactId>study-pom</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>study-web</artifactId>
  <packaging>war</packaging>
  <name>study-web Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<spring.version>4.0.1.RELEASE</spring.version>
	</properties>
  <dependencies>
   <dependency>
      <groupId>org.lyncc</groupId>
      <artifactId>study-service</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.11</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-core-asl</artifactId>
		<version>1.9.11</version>
	</dependency>
	<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
  </dependencies>
  <build>
    <finalName>study-web</finalName>
  </build>
</project>

6)修改study-web下的web.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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>study-web</display-name>

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

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:spring-mybatis.xml,classpath*:spring.xml</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.xml</param-value>
	</context-param>

	<context-param>
		<param-name>rootLevel</param-name>
		<param-value>DEBUG</param-value>
	</context-param>

	<context-param>
		<param-name>loggingLevel</param-name>
		<param-value>INFO</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:spring-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>
选择study-web,新建spring.xml,spring-servlet.xml,log4j.xml

spring.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:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="org.study">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
</beans>
spring-servlet.xml

<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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
       
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    
     <context:component-scan base-package="org.study.lyncc.web.controller" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
    </context:component-scan>  
    
    <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/"/>
    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"/>


    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean> 
    
</beans>
log4j.xml

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">  
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">  
  <!-- [控制台STDOUT] -->  
  <appender name="console" class="org.apache.log4j.ConsoleAppender">  
     <param name="encoding" value="GBK" />  
     <param name="target" value="System.out" />  
     <layout class="org.apache.log4j.PatternLayout">  
       <param name="ConversionPattern" value="%-5p %c{2} - %m%n" />  
     </layout>  
  </appender>  
  
  <!-- [公共Appender] -->  
  <appender name="DEFAULT-APPENDER" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/common-default.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
    <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [错误日志APPENDER] -->  
   <appender name="ERROR-APPENDER" class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/common-error.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="threshold" value="error" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
        <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [组件日志APPENDER] -->  
   <appender name="COMPONENT-APPENDER"  
class="org.apache.log4j.DailyRollingFileAppender">  
     <param name="File" value="${webapp.root}/logs/logistics-component.log" />  
     <param name="Append" value="true" />  
     <param name="encoding" value="GBK" />  
     <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />  
     <layout class="org.apache.log4j.PatternLayout">  
    <param name="ConversionPattern" value="%d %-5p %c{2} - %m%n" />  
     </layout>  
   </appender>  
  
   <!-- [组件日志] -->  
   <logger name="LOGISTICS-COMPONENT">  
      <level value="${loggingLevel}" />  
      <appender-ref ref="COMPONENT-APPENDER" />  
      <appender-ref ref="ERROR-APPENDER" />  
   </logger>  
  
   <!-- Root Logger -->  
   <root>  
       <level value="${rootLevel}"></level>  
       <appender-ref ref="DEFAULT-APPENDER" />  
       <appender-ref ref="ERROR-APPENDER" />  
       <appender-ref ref="console" /> 
       <appender-ref ref="COMPONENT-APPENDER" /> 
   </root>  
</log4j:configuration>  

7)在study-intf的src/main/resources(可能需要自己新建)添加jdbc.properties,,mybatis-config.xml,spring-mybatis.xml文件

jdbc.properites

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration 
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
         <typeAlias alias="User" type="org.study.intf.lyncc.entity.User"/> 
    </typeAliases>
    <mappers>
    </mappers>
</configuration>
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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
 
 
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc_driverClassName}" />
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
    </bean>
    
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
     
    <!-- mybatis文件配置,扫描所有mapper文件 -->
      <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:mybatis-config.xml"
          p:mapperLocations="classpath:mapper/*.xml"/> 
       
   <!-- spring与mybatis整合配置,扫描所有dao -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="org.study.intf.lyncc.mapper"
        p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
  
</beans>
数据库建表语句:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `mail` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;

INSERT INTO `user` VALUES ('1', '曾子墨', '123456', '25', 'zimo@163.com');
INSERT INTO `user` VALUES ('2', '吴神', '234456', '24', 'shentong@alibaba.com');
INSERT INTO `user` VALUES ('3', '张岩', '654321', '23', 'zhangyan@qq.com');
INSERT INTO `user` VALUES ('4', '武松', '12wsas', '45', 'wusong@qq.com');
INSERT INTO `user` VALUES ('5', '孙悟空', 'qwert', '5000', 'wukong@163.com');
INSERT INTO `user` VALUES ('6', '孙燕姿', 'yanzi', '29', 'lvguang@meili.com');
INSERT INTO `user` VALUES ('7', '京东', 'JD', '15', 'jd@jd.com');
INSERT INTO `user` VALUES ('8', '淘宝', 'taobao', '19', 'mayun@taobao.com');
INSERT INTO `user` VALUES ('9', '蘑菇街', 'mogujie', '6', 'mogujie@mg.com');
INSERT INTO `user` VALUES ('10', '当当', 'dangdang', '11', 'dangdang@wuxi.com');
INSERT INTO `user` VALUES ('11', 'facebook', 'facebook', '12', 'facebook@fb.com');

好了,到此为止所有的准备工作都好了,接下来就是写代码了

UserController.java

package org.study.lyncc.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.study.intf.lyncc.entity.User;
import org.study.service.UserService;


@Controller
@RequestMapping(value="/user")
public class UserController {
	

	@Resource
	private UserService userService;
	
	@ResponseBody
	@RequestMapping(value="test")
	public List<User> getAllList(){
		List<User> users = userService.getAllUser();
		return users;
	}
	
	
	@RequestMapping(value="list")
	public String list(){
		return "list";
	}
	
	@ResponseBody
	@RequestMapping("/page")
	public Map<String, Object> page(@RequestParam Map<String, Object> requestMap){
		
		int limit = Integer.valueOf("" + requestMap.get("limit"));
		int offset = Integer.valueOf("" + requestMap.get("offset"));
		List<User> users = userService.findByPage(limit,offset);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("status", "success");
		resultMap.put("total", userService.findCount());
		resultMap.put("rows", users);
		
		return resultMap;
	}
	
	
}

UserService.java

package org.study.service;

import java.util.List;

import org.study.intf.lyncc.entity.User;

public interface UserService {

	List<User> getAllUser();

	List<User> findByPage(int limit, int offset);

	Integer findCount();

}

UserSerivceImpl.java

package org.study.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.study.intf.lyncc.entity.User;
import org.study.intf.lyncc.mapper.UserMapper;
import org.study.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;

	public List<User> getAllUser() {
		return userMapper.findAllUser();
	}

	public List<User> findByPage(int limit, int offset) {
		return userMapper.findByPage(limit,offset);
	}

	public Integer findCount() {
		return userMapper.countAll();
	}

}

UserMapper.java

package org.study.intf.lyncc.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.study.intf.lyncc.entity.User;


public interface UserMapper{

	List<User> findAllUser();

	List<User> findByPage(@Param("limit")Integer limit,@Param("offset")Integer offset);

	Integer countAll();
	
 
}
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="org.study.intf.lyncc.mapper.UserMapper">

 	<resultMap type="User" id="userInfo">
	     <id property="id" column="id"/>
		 <result property="username" column="username"/>
		 <result property="mail" column="mail"/>
		 <result property="age" column="age"/>
		 <result property="password" column="password"/>
	</resultMap>
	
	<select id="findAllUser" resultMap="userInfo">
	  select * from user
	</select>
	
	<select id="findByPage" resultMap="userInfo">
	     select * from user limit #{offset},#{limit}
	</select>
	
	<select id="countAll" resultType="Integer">
	  select count(*) from user
	</select>
	 
</mapper>
User.java

package org.study.intf.lyncc.entity;

import java.io.Serializable;

 
public class User implements Serializable {
	
	
	private static final long serialVersionUID = 1L;
	
	private Integer id;  
	
    private String username;  
    
    private String password;  
    
    private int age;
    
    private String mail;

    public User() {
    	
    }


    public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	 
}
list.html

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
<link rel="stylesheet" href="${ctx}/resources/bootstrap-table.min.css">
<script type="text/javascript" src="${ctx}/resources/jquery-1.11.1.min.js"/></script>
<script type="text/javascript" src="${ctx}/resources/bootstrap-table.min.js"></script>
<link rel="stylesheet" href="${ctx}/resources/bootstrap.min.css">
<script type="text/javascript" src="${ctx}/resources/bootstrap.min.js"></script>
</head>
<body >
	<div class="page-container">
	  <div style="height:500px">
	   <table class="table table-bordered table-striped" id="usertable">
	   </table>
	   </div>
	</div>
</body>
<script type="text/javascript">
$(function(){
	 $("#usertable").bootstrapTable({
		 method:'get',
		 url:"${ctx}/user/page",
		 cache: false, 
		 striped: true,
		 pagination: true,
		 pageList: [10,20,50],
		 pageSize:10,
		 pageNumber:1,
		 queryParams: function(params){
		 		paramsReturn = {
					limit: params.limit,
					offset: params.offset,
				};
			 	return paramsReturn;
		 },
		 sidePagination:'server',
		 contentType: "application/x-www-form-urlencoded",
		 showColumns: true, 
		 showRefresh: true,  
		 smartDisplay:true,
		 columns: [
          {  
				field: 'id',  
				title: '编号',  
				align: 'center',  
				width: '60',  
				valign: 'middle',	
          },
          {  
        	  	field: 'username', 
          	    title: '名称',  
				align: 'center',  
				width: '60',  
				valign: 'middle', 
          },
          {  
				field: 'age',  
				title: '年龄',  
				align: 'center',  
				width: '40',  
				valign: 'middle',
          },
          {   
        	  	field: 'password',
          		title: '密码',  
				align: 'center',  
				width: '120',  
				valign: 'middle',
          },
          {
        	    field: 'mail',
				title: '邮箱',  
				align: 'center',  
				width: '40',  
				valign: 'middle', 
          },
          {
				title: '用户操作',  
				align: 'center',  
				width: '240',  
				valign: 'middle', 
				formatter: function(value,row,index){
	        		 var str = "";
	            	 if(row.type == 0)
	            		 str += '<button class="btn btn-secondary btn-xs"><i class="fa fa-edit"></i><span>查看</span></button>';
	            	 else
	            		 str += '<button class="btn btn-warning btn-xs"><i class="fa fa-edit"></i><span >编辑</span></button>';
	            	 return str;
   			}
          },
	     ]
	 });
});
</script>
</html>
就做了简单的分页功能,效果图如下:


好了,到此为止,基本代码已经贴出了,bootstrap的包在附件中,这边就不贴出了,源码下载地址是(下载后用jdk1.7编译):

http://download.csdn.net/detail/linuu/9454826

如果有问题,请指出~









2015-08-14 10:37:35 a410498563 阅读数 32

结合springmvc bootstrap 的代码快速构建

主要实现思路:服务端通过构建通用的增删改查服务 + 前端的jquery插件实现 配置及开发 所见即所得 功能。

目前版本还不够完善,正在开发中。

线上截图吧



 

1、支持自动创建bootstrap风格的树,适合在手机上进行操作。

2、支持form datagrid的联合保存、修改等功能

3、支持单表字段的翻译功能

 

 源码和数据库文件请见附件下载

 

没有更多推荐了,返回首页