springmvc+Ibatis+Bootstrap自定义标签分页+登录模版

package com.org.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.org.dao.IUserDao;
import com.org.model.User;
import com.org.service.IUserService;

@Service 
@SuppressWarnings("all")
public class UserServiceImpl implements IUserService{
	/**
	 * 注入
	 * 	@Resource 和 @Autowrite是同等可以实现
	 */
	@Resource 
	private IUserDao userDao;
	
	public List<User> getUserList() {
		return userDao.getUserList();
	}

	@Override
	public List<User> getUserLists(Map<String, Object> map) {
		return userDao.getUserLists(map);
	}

	@Override
	public Integer getUserCount(Map<String, Object> map) {
		return userDao.getUserCount(map);
	}

	@Override
	public User getUserById(Integer primaryKeyId) {
		return userDao.getUserById(primaryKeyId);
	}

	@Override
	public void delUserById(Integer primaryKeyId) {
		  userDao.delUserById(primaryKeyId);
	}

	@Override
	public void addUser(User entity) {
		userDao.addUser(entity);
	}

	@Override
	public void editUser(User entity) {
		userDao.addUser(entity);
	}
	
}

 

package com.org.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.org.IbatisBaseDao;
import com.org.dao.IUserDao;
import com.org.model.User;

@Repository//@Component也可以实现
@SuppressWarnings("all")
public class UserDaoImpl extends IbatisBaseDao implements IUserDao {
	/***
	 * sqlMapClient和getSqlMapClientTemplate()是一样可以实现
	 */
	public List<User> getUserList() {
		try {
			// return sqlMapClient.queryForList("getUserList");
			return getSqlMapClientTemplate().queryForList("findUserList");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public List<User> getUserLists(Map<String, Object> map) {
		try {
			return sqlMapClient.queryForList("findUserLists", map);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public Integer getUserCount(Map<String, Object> map) {
		try {
			return (Integer) sqlMapClient.queryForObject("findUserCount", map);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	
	public User getUserById(Integer primaryKeyId) {
		try {
			sqlMapClient.queryForObject("findUserById", primaryKeyId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public void delUserById(Integer primaryKeyId) {
		try {
			sqlMapClient.delete("findDeleteUser", primaryKeyId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public void addUser(User entity) {
		try {
			sqlMapClient.insert("findInsertUser", entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public void editUser(User entity) {
		try {
			sqlMapClient.update("findUpdateUser", entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

package com.org.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.org.BaseController;
import com.org.model.User;
import com.org.service.IUserService;

/**
 * @Author:liangjilong
 * @Date:2014-2-25
 * @Version:1.0
 * @Description:
 */
@Controller
public class UserController extends BaseController {

	@Resource
	private IUserService userService;

	/***
	 * 方法一请求使用String
	 * 
	 * 请求@RequestMapping匹配的URL request
	 * 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/userList1.do")
	public String userList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		List<User> lists = userService.getUserList();
		if (lists != null) {
			request.setAttribute("userList", lists);
		}
		// userList指跳转到userList.jsp页面
		return "userList";
	}

	/**
	 * 方法二请求使用ModelAndView
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/userList2.do")
	public ModelAndView userList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		List<User> lists = userService.getUserList();
		if (lists != null) {
			request.setAttribute("userList", lists);
		}
		// userList指跳转到userList.jsp页面
		return new ModelAndView("userList");
	}

	/***
	 * 自定义标签实现分页
	 * 
	 * @param request
	 * @param response
	 * @param @ResponseBody ajax响应
	 * @param method={RequestMethod.POST,RequestMethod.GET}表单请求
	 * @param consumes="application/json; charset=UTF-8"请求格式是json
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value = "/pageList.do" ,method={RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody ModelAndView getUserInfo(Model model, @RequestParam(required = false) String username,
			@RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize)  {
		try {
			String userName = new String(username.getBytes("ISO-8859-1"),"UTF-8");//处理乱码
			
			Map<String, Object> map = new HashMap<String, Object>();
			username=(username==null)?"":username;
			map.put("username", username);//username必须要和ibatis配置的property=username一致
			Integer totalCount = this.userService.getUserCount(map);
			this.initPage(map, pageNum, pageSize, totalCount);
			List list = this.userService.getUserLists(map);
			this.initResult(model, list, map);
			
			return new ModelAndView("pagerList");
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return null;
	}
	 
	/**
	 * 添加用户
	 * @param type
	 * @param model
	 * @return
	 */
	@RequestMapping("/addUser.do")
	public ModelAndView addUser(@RequestParam String username, Model model) {
		User user = new User();
		user.setUsername(username);
		this.userService.addUser(user);
		return this.getUserInfo(model, null, null, null);
	}
	/***
	 * 删除用户
	 * @param id
	 * @param pageNum
	 * @param pageSize
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/delUser.do",method={RequestMethod.POST,RequestMethod.GET},consumes="application/json; charset=UTF-8")
	@ResponseBody
	public ModelAndView delUser(@RequestParam(required = true) Integer id, @RequestParam(required = false) Integer pageNum,
			@RequestParam(required = false) Integer pageSize, Model model, HttpServletRequest request,HttpServletResponse response) 
	{
		PrintWriter out=null;
		 
		JSONObject result=new JSONObject();
		try {
			out=response.getWriter();
		
			this.userService.delUserById(id);
			result.put("flag", true);
			
			out.write(result.toString());
		} catch (Exception e) {
			try {
				result.put("flag", false);
				out.write(result.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		}
		
		return null;
		//return this.getUserInfo(model, null, pageNum, pageSize);
	}

	/***
	 * 编辑用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/getUserById.do")
	public ModelAndView getUserById(@RequestParam(required = true) Integer id, Model model) {
		User u = this.userService.getUserById(id);
		model.addAttribute("user", u);
		return new ModelAndView("editUser");
	}
	
	/***
	 * 编辑用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/editUser.do")
	public ModelAndView editUser(@RequestParam(required = true) Integer id, @RequestParam String username,
			@RequestParam(required = false) Integer pageNum,
			@RequestParam(required = false) Integer pageSize, Model model) {
		User u = new User();
		u.setUsername(username);
		this.userService.editUser(u);
		return this.getUserInfo(model, null, pageNum, pageNum);
	}

}

 

package com.org;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;


/**
 * @author:liangjilong
 */
public class IbatisBaseDao extends SqlMapClientDaoSupport{

	/**
	 * spring注入此配置和整合hibernate是一致..
	 *  http://jilongliang.iteye.com/blog/2061557
	 */
	@Resource(name = "sqlMapClient")
	public SqlMapClient sqlMapClient;  
  
    @PostConstruct  
    public void initSqlMapClient() {  
        super.setSqlMapClient(sqlMapClient);  
    } 
}

 

package com.org.utils.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.org.utils.encode.CharacterEncode;

/***
 * 分页控件
 * springmvc+hibernate+Bootstrap自定义标签分页
 * http://jilongliang.iteye.com/blog/2062068
 */
public class Pager extends TagSupport {

	private static final long serialVersionUID = 1L;
	private String params;
	private Integer curPage;
	private Integer totalPage;
	private Integer pageSize =10; 
	private Integer totalCount = 0;
	private String formId;

	public void setCurPage(Integer curPage) {
		this.curPage = curPage;
	}

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

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}

	public Integer getTotalCount() {
		return totalCount;
	}

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

	/***
	 * javascript:void(0);是去掉#很有必要
	 */
	public int doStartTag() throws JspException {
		StringBuffer buffer=new StringBuffer();
		JspWriter out = pageContext.getOut();

		int pageNumber = 0;
		if (totalPage % pageSize == 0) {
			pageNumber = totalPage / pageSize;
		} else {
			pageNumber = (totalPage / pageSize) + 1;
		}
		if (curPage < 1) {
			curPage = 1;
		}

		try {
			if (pageNumber > 0) {
				buffer.append("<script type='text/javascript'>");//script-Start
				buffer.append("function go(pageNum)");
				buffer.append("{");//{start
				buffer.append("var f = document.getElementById('" + formId + "');");
				buffer.append("f.action = f.action + '?pageNum=' + pageNum + '&pageSize="+pageSize + "';");
				buffer.append("f.submit();" );
				buffer.append("}");//}end
				buffer.append("</script>");//script-end
				
				out.print(buffer.toString());

				out.append("<div class='page-number-strip' style='height:62px;'> ");//page-number-strip
				out.print("<ul class='pagination'>");//添加Bootstrap分页的样式pagination
				int start = 1;
				int end = totalPage;
				for (int i = 4; i >= 1; i--) {
					if ((curPage - i) >= 1) {
						start = curPage - i;
						break;
					}
				}
				for (int i = 4; i >= 1; i--) {
					if ((curPage + i) <= totalPage) {
						end = curPage + i;
						break;
					}
				}
				// 如果小于9则右侧补齐
				if (end - start + 1 <= 9) {
					Integer padLen = 9 - (end - start + 1);
					for (int i = padLen; i >= 1; i--) {
						if ((end + i) <= totalPage) {
							end = end + i;
							break;
						}
					}
				}

				// 如果还小于9左侧补齐
				if (end - start + 1 <= 9) {
					Integer padLen = 9 - (end - start + 1);
					for (int i = padLen; i >= 1; i--) {
						if ((start - i) >= 1) {
							start = start - i;
							break;
						}
					}
				}

				if (curPage > 1) {
					if (start > 1) {
						out.print("<li><a href='javascript:go(1)'>首页</a></li>");
					}
					out.print("<li><a href='javascript:go(" + (curPage - 1) + ")'>上一页</a></li>");
				}

				for (int i = start; i <= end; i++) {
					if (i == curPage) {
						out.print("<li class='active'><a href='javascript:void(0);'>" + i + "</a></li>");
					} else {
						out.print("<li><a href='javascript:go(" + i + ")'>" + i + "</a></li>");
					}
				}
				if (curPage < totalPage) {
					out.print("<li><a href='javascript:go(" + (curPage + 1) + ")'>下一页</a></li>");
					if (end < totalPage) {
						out.print("<li><a href='javascript:go(" + totalPage + ")'>尾页</a></li>");
					}
				}
				out.print("<li><a href='javascript:void(0)'>共" + totalPage + "页" + this.totalCount + "条</a></li>");
				out.print("</ul>");
				out.print("</div>");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return super.doStartTag();

	}

	/***
	 * 获取页面的参数
	 * @param 格式(parms="username=${user.username})
	 * @return
	 */
	public String getParms() {
		
		StringBuffer buffer=new StringBuffer();
		if(params!=null && params.length()>0){
			//分离参数 A=b
			String[] parmsArr=params.split("&");
			for(int i=0;i<parmsArr.length;i++){ 
				String parmstemp=parmsArr[i];
				String[] parmsEqArr=parmstemp.split("=");
				//分离参数 键 值 
				try {
					buffer.append(i > 0 ? "&" : "");
					buffer.append(parmsEqArr[0]).append("=");
					if(parmsEqArr.length>1){
						//ps.append(URLDecoder.decode(parmsEqArr[1],"UTF-8"));
						 buffer.append(CharacterEncode.URLEncoder(parmsEqArr[1]));
					}
				} catch (Exception e) {
					return "";
				}	
			}
		}
		
		return buffer.toString();
	}
	public static Integer getStartIndex(Integer pageNum, Integer pageSize) {
		Integer res = 0;
		if (pageNum > 0) {
			res = (pageNum - 1) * pageSize;
		}
		return res;
	}

	public String getParams() {
		return params;
	}

	public void setParams(String params) {
		this.params = params;
	}

}

 

<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="userSqlMap">
	<!--如果数据库表字段不一样必须使用 Id是给select引用
		如:数据库表的用户名字段是user_name如下配置..
		 <select>标签此时并不是resultClass="user" 而是resultMap="userMapId"
		<resultMap class="user" id="userMapId">
			<result property="username" column="user_name"/> 
		</resultMap>
	 -->
	<typeAlias alias="user" type="com.org.model.User" />
	
	<!-- 无分页查询 -->
	<select id="findUserList" resultClass="user">
		select * from user
	 </select>
	<!-- 分页查询 -->
	<select id="findUserLists" parameterClass="Map" resultClass="user" >
		SELECT 
			id,
			username,
			password,
			createDate,
			modifyDate,
			type
		FROM user
			WHERE 1=1
		<isNotEmpty prepend="and" property="username">
			username=#username#  
		</isNotEmpty>
			limit #startIndex#,#pageSize#
	</select>
	 <!-- 分页查询总数 -->
	<select id="findUserCount" parameterClass="Map" resultClass="Integer">
		SELECT COUNT(*) FROM user WHERE 1=1
		<isNotNull prepend="and" property="username">
			username=#username#  
		</isNotNull>
	</select>
	
	<!-- 按id查询 -->
	<select id="findUserById" parameterClass="String" resultClass="user" >
		SELECT * from user where id=#id#;
	</select>
	<!-- 更新 -->
	<update id="findUpdateUser" parameterClass="user">
		  update user  set Id=#id#
		<isNotNull prepend="," property="password">password=#password#</isNotNull>
		<isNotNull prepend="," property="username">username=#username#</isNotNull>
		  where Id=#id# 
	</update>
	
	<!-- 添加 -->
	 <insert id="findInsertUser" parameterClass="user">
    	  INSERT INTO user
    	 (
    	  	id,
			username,
			password,
			createDate,
			modifyDate,
			type
    	  )
    	  values(
    	  	#id#,
    	  	#username#,
    	  	#password#,
    	  	#createDate#,
    	  	#modifyDate#,
    	  	#type#
    	  );
	  </insert>
	  
	  <!-- 删除 -->
	  <delete id="findDeleteUser" parameterClass="String">
	  		delete from user where id=#id#
	  </delete>
</sqlMap>

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="/morinda-tags" prefix="m"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>${title }</title>
	<jsp:include page="common/include.jsp"></jsp:include>
	
	<script type="text/javascript">
	
		$(function(){
	 
			$("#deleteUser").click(function(){
				
				
				  //$("#modal-title-content").html("删除提示!");
				  //$("#modal-body-content").html("删除之前,谨慎操作,以免恢复不回来!");
				  //$('#deleteUser').on('show.bs.modal', function (e) { });
			});
			
		});
		
		function deleteUser(id){
			$("#modal-title-content").html("删除提示!");
			$("#modal-body-content").html("删除之前,谨慎操作,以免恢复不回来!");
			$.ajax({
				   type: "POST",
				   url: '<%=basePath%>'+"delUser.do",
				   contentType:"application/json; charset=utf-8",
				   dataType:"json",
				   data: "id="+ id +"&pageNum=${param.pageNum}&pageSize=${param.pageSize}",
				   success: function(responseText){
					   var flag=responseText.flag;
					   if(flag==true){
						   alert("操作成功!");
					   }else{
						   alert("删除失败..!");
					   }
				   }
			});
		}
		
		
	</script>
  </head>
  
  <body style="border:1px solid #ccc;">
  
	 <form action="<%=basePath%>pageList.do" method="post" name="search" id="pageFormId">
			<!-- panel-success浅绿色 -->
			<div class="panel panel-info">
				<div class="panel-heading" id="divSearchTitle">
					<span class="glyphicon glyphicon-search"></span>搜索条件
					<span id="divSlide" class="glyphicon glyphicon-chevron-up" style="float: right;"></span>
				</div>
				<div class="panel-body" id="divSearch">
					<table class="Morinda-table">
						<tr class="Morinda-row">
							<td class="Morinda-label-td"> 用户名:
							</td>
							<td class="Morinda-field-td">
							 	<input type="text" name="username" size="15" class="Morinda-text" value="${username}"
							 	 maxlength="20" placeholder="请输入用户名"/>
							</td>
							<td colspan="2" style="text-align: center">
								<input type="submit" value="查询" class="btn btn-info" id="btnSearch">
								<input type="reset" value="清空" class="btn btn-info" id="btnClear">
							</td>
						</tr>
					</table>
				</div>
			</div>
		</form>
		
		<!-- panel-default 
			详细请参考..http://v3.bootcss.com/components/#panels
		 -->
		<div class="panel panel-success">
     		<div class="panel-heading">
   				<button class="btn btn-info"  id="btnDel">删除</button>
   				<button class="btn btn-info"  id="btnUpdate">修改</button>
   				<button class="btn btn-info"  id="btnAdd">添加</button>
    		</div>	
    		
     		<div class="panel-body" id="table-container" style="padding:0px;">
		    	<table class="table table-bordered table-striped">
				  <tr >
				    <th>编号</th>
				    <th>用户</th>
				    <th>创建时间</th>
				    <th>修改时间</th>
				    <th>操作</th>
				  </tr>
				  
				  <c:forEach var="user" items="${list}" varStatus="st">
				  	<tr>
				   		<td>${st.count}</td>
				   		<td>${user.username }</td>
				   	  	<td>${user.createDate} </td>
				   	  	<td>${user.modifyDate} </td>
				   		<td align="center">
							<span>
								<!-- data-target="#shwodialogModal"指向这个div data-toggle="modal"-->
								<a href="javascript:void(0);" onclick="deleteUser('${user.id}');" id="deleteUser" 
									data-toggle="modal" data-target="#shwodialogModal">
									删除
								</a>
							</span>
							<span><a href="javascript:void(0);" onclick="updateUser('${user.id}');">修改</a></span>
				    	</td>
				  </tr>
				</c:forEach>
			</table>
          	<m:pager pageSize="${pageSize}" totalPage="${totalPage}" totalCount="${totalCount}"
          		  	 curPage="${pageNum}" formId="pageFormId"  />
    	</div>
 	  </div>  
 	  
	
	<div class="modal fade" id="shwodialogModal" tabindex="-1" role="dialog" 
		aria-labelledby="modal-title-content" aria-hidden="true" style="display: none;">
	  <div class="modal-dialog">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
	        <h4 class="modal-title" id="modal-title-content"></h4>
	      </div>
	      <div class="modal-body" id="modal-body-content"></div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
	        <button type="button" class="btn btn-primary">确认</button>
	      </div>
	    </div>
	  </div>
	 </div>
 
  </body>
</html>

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	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:oscache="http://www.springmodules.org/schema/oscache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 	 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
	 	 http://www.springframework.org/schema/context
	 	 http://www.springframework.org/schema/context/spring-context-3.1.xsd 
	 	 http://www.springframework.org/schema/aop 
	 	 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
	 	 http://www.springframework.org/schema/tx 
	 	 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
	 	 http://www.springmodules.org/schema/oscache 
	 	 http://www.springmodules.org/schema/cache/springmodules-oscache.xsd
	 	 http://www.springframework.org/schema/mvc
	 	 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<!--
		 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 
		 mvc:annotation-driven
	--> 
	<mvc:annotation-driven/>
	<!-- 扫描包 -->
	<context:annotation-config/>  
	<context:component-scan base-package="com.org.*" />
	
	
	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<!-- 匹配jsp文件下面的所有.jsp的页面 -->
		<property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" /> 
	</bean>
	 <!-- 
	 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/" p:suffix=".jsp" />-->
	
	<!-- 配置jdbc -->
	<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>
	<!-- 配置數據源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 连接池启动时的初始值 -->
        <property name="initialSize" value="1"/>  
        <property name="maxActive" value="500"/>    
        <property name="maxIdle" value="2"/>        
        <property name="minIdle" value="1"/> 
	</bean>
		
	 <!-- 定义Ibatis配置
	 	org.springframework.orm.ibatis.SqlMapClientFactoryBean
	 	com.org.utils.ibatis.SqlMapClientFactory重写处理读取ibatis
	 	方便读取config
	  -->
   <bean id="sqlMapClient" class="com.org.utils.ibatis.SqlMapClientFactory">
       <property name="configLocation">
           <value>classpath:ibatis-Base.xml</value>
       </property>
       <property name="dataSource">
       		<ref bean="dataSource"/> 
       </property>
    </bean>
   <!-- 配置sqlMapClientTemplate模板 -->
	<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
		<property name="sqlMapClient" ref="sqlMapClient"/>
	</bean>
	<!-- 配置 transactionManager事物管理-->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	
	<!-- Spring AOP config配置切点 -->  
	<aop:config>
		<aop:pointcut expression="execution(* com.org.service.*.*(..))" id="bussinessService" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService"/>
	</aop:config>

	<!-- 配置那个类那个方法用到事务处理 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	 
	 
<!-- 这个映射配置主要是用来进行静态资源的访问 -->
 <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> 
 <mvc:resources mapping="/resource/**" location="/resource/" />  
 <mvc:resources mapping="/jsp/**" location="/jsp/" /> 
 
</beans>

 

package com.org;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;

/**
 *@DEMO:dress
 *@Java:T.java
 *@Date:2015-1-9下午5:03:13
 *@Author:liangjilong
 *@Email:[email protected]
 *@Weibo:http://weibo.com/jilongliang
 *@Version:1.0
 *@Description:IbatisDao的封装类
 */
@SuppressWarnings("all")
public class BaseIbatisDao extends SqlMapClientDaoSupport{
	
	private Logger log4j = Logger.getLogger(BaseIbatisDao.class);
	/**
	 * @Autowired和@Resource一样的可以注入
	 * 
	 */
	@Resource(name = "sqlMapClient")
    public SqlMapClient sqlMapClient;  
  
    @PostConstruct  
    public void initSqlMapClient() {  
        super.setSqlMapClient(sqlMapClient);  
    } 
    
    /************************--------------*新增----------------********************/

	/**
	 * 根据条件查询对象集合
	 * 
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @param paramObj
	 *            参数对象
	 * @return
	 */
	
	public <T> List<T> loadList(String sqlid, Object paramObj) {
		return (List<T>) getSqlMapClientTemplate()
				.queryForList(sqlid, paramObj);
	}

	/**
	 * 根据条件查询对象所有数据
	 * 
	 * @param <T>
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @return
	 */
	
	public <T> List<T> loadList(String sqlid) {
		return (List<T>) getSqlMapClientTemplate().queryForList(sqlid);
	}

	/**
	 * 根据ID查询ENTITY 对象
	 * 
	 * @param <T>
	 * @param sqlid对应IBATIS
	 *            xml SQL_ID
	 * @return <T> 实体对象
	 */
	
	public <T> T loadObject(String sqlid) {
		return (T) getSqlMapClientTemplate().queryForObject(sqlid);
	}

	/**
	 * 根据ID查询ENTITY 对象
	 * 
	 * @param <T>
	 * @param sqlid对应IBATIS
	 *            xml SQL_ID
	 * @param id
	 *            实体ID
	 * @return <T> 实体对象
	 */
	
	public <T> T loadObject(String sqlid, String id) {
		return (T) getSqlMapClientTemplate().queryForObject(sqlid, id);
	}

	/**
	 * 根据ID查询ENTITY 对象
	 * 
	 * @param <T>
	 * @param sqlid对应IBATIS
	 *            xml SQL_ID
	 * @param id
	 *            实体ID
	 * @return <T> 实体对象
	 */
	
	public <T> T loadObject(String sqlId, Long id) {
		return (T) getSqlMapClientTemplate().queryForObject(sqlId, id);
	}

	/**
	 * 根据条件查询对象
	 * 
	 * @param <T>
	 * @param sqlid对应IBATIS
	 *            xml SQL_ID
	 * @param paramObj
	 *            参数
	 * @return <T> 实体对象
	 */
	
	public <T> T loadObject(String sqlId, Object paramObj) {
		return (T) getSqlMapClientTemplate().queryForObject(sqlId, paramObj);
	}

	/**
	 * 保存对象
	 * 
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @param entity
	 *            保存的对象
	 */
	public void save(String sqlid, Object entity) {
		getSqlMapClientTemplate().insert(sqlid, entity);
	}

	/**
	 * 保存对象
	 * 
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @param entity
	 *            保存的对象
	 */
	public void save(String sqlid, Map<String, Object> entity) {
		getSqlMapClientTemplate().insert(sqlid, entity);
	}

	/**
	 * 更新对象
	 * 
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @param entity
	 *            修改对象
	 */
	public void update(String sqlId, Map<String, Object> entity) {
		getSqlMapClientTemplate().update(sqlId, entity);
	}

	/**
	 * 更新对象
	 * 
	 * @param sqlid
	 *            对应IBATIS xml SQL_ID
	 * @param entity
	 *            修改对象
	 */
	public void update(String sqlId, Object entity) {
		getSqlMapClientTemplate().update(sqlId, entity);
	}

	/**
	 * 删除指定的对象
	 * 
	 * @param sqlId
	 * @param object
	 *            需要删除的对象
	 */
	public void delete(String sqlId, Object object) {
		getSqlMapClientTemplate().delete(sqlId, object);
	}

	/**
	 * 查询数据总条数
	 * 
	 * @param sqlid
	 * @param object
	 * @return
	 */
	public Long loadRecordCountObject(String sqlid, Object object) {
		log4j.info("sqlid====" + sqlid);
		return (Long) getSqlMapClientTemplate().queryForObject(sqlid, object);
	}

	/**
	 * 查询数据总条数
	 * 
	 * @param sqlid
	 * @param object
	 * @return 返回Int
	 */
	public Integer loadRecordCount(String sqlid, Object object) {
		log4j.info("sqlid====" + sqlid);
		return (Integer) getSqlMapClientTemplate() .queryForObject(sqlid, object);
	}

	/**
	 * @Description: 返回表中ID最大值加一
	 * @param:sqlMapId Ibatis配置的ID
	 * @param tabName 表名
	 * @return:
	 * @returnType: Long
	 * @throws
	 */
	public Long findNextId(String sqlMapId,String tabName) {
		Long id = 0l;
		String seqName = tabName.substring(3) + "_S";
		id = (Long) getSqlMapClientTemplate().queryForObject(sqlMapId, seqName);
		if (id == null || id.equals(0l)){
			id=null;
		}
		return id;
	}
	/**
	 * 
	 * @param:sqlMapId Ibatis配置的ID
	 * @return
	 */
	public Date findOracleSysDate(String sqlMapId) {
		return (Date) getSqlMapClientTemplate().queryForObject(sqlMapId, null);
	}
}

 

 
springmvc+Ibatis+Bootstrap自定义标签分页+登录模版_第1张图片
 
springmvc+Ibatis+Bootstrap自定义标签分页+登录模版_第2张图片
 
springmvc+Ibatis+Bootstrap自定义标签分页+登录模版_第3张图片
 
springmvc+Ibatis+Bootstrap自定义标签分页+登录模版_第4张图片
 源代码

你可能感兴趣的:(springMVC,ibatis)