一、Info.java文件内容
package com.winphone.common;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Info")
public class Info {
private String state;
private String code;
private Object info;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getInfo() {
return info;
}
public void setInfo(Object info) {
this.info = info;
}
}
二、PagePlugin.java文件内容:
package com.winphone.common;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import javax.xml.bind.PropertyException;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import com.winphone.entity.Page;
import com.winphone.utils.ReflectHelper;
import com.winphone.utils.Tools;
@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PagePlugin implements Interceptor {
private static String dialect = ""; //数据库方言
private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)
public Object intercept(Invocation ivk) throws Throwable {
// TODO Auto-generated method stub
if(ivk.getTarget() instanceof RoutingStatementHandler){
RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL
BoundSql boundSql = delegate.getBoundSql();
Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
if(parameterObject==null){
throw new NullPointerException("parameterObject尚未实例化!");
}else{
Connection connection = (Connection) ivk.getArgs()[0];
String sql = boundSql.getSql();
String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
setParameters(countStmt,mappedStatement,countBS,parameterObject);
ResultSet rs = countStmt.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
countStmt.close();
//System.out.println(count);
Page page = null;
if(parameterObject instanceof Page){ //参数就是Page实体
page = (Page) parameterObject;
page.setEntityOrField(true); //见com.flf.entity.Page.entityOrField 注释
page.setTotalResult(count);
}else{ //参数为某个实体,该实体拥有Page属性
Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
if(pageField!=null){
page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
if(page==null)
page = new Page();
page.setEntityOrField(false); //见com.flf.entity.Page.entityOrField 注释
page.setTotalResult(count);
ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象
}else{
throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");
}
}
String pageSql = generatePageSql(sql,page);
ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.
}
}
}
return ivk.proceed();
}
/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
* @param ps
* @param mappedStatement
* @param boundSql
* @param parameterObject
* @throws SQLException
*/
private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = mappedStatement.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (propertyName.startsWith("__frch_")&& boundSql.hasAdditionalParameter(prop.getName())) {
value = boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
}
} else {
value = metaObject == null ? null : metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
}
}
}
}
/**
* 根据数据库方言,生成特定的分页sql
* @param sql
* @param page
* @return
*/
private String generatePageSql(String sql,Page page){
if(page!=null && Tools.notEmpty(dialect)){
StringBuffer pageSql = new StringBuffer();
if("mysql".equals(dialect)){
pageSql.append(sql);
pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());
}else if("oracle".equals(dialect)){
pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
pageSql.append(sql);
pageSql.append(") as tmp_tb where ROWNUM<=");
pageSql.append(page.getCurrentResult()+page.getShowCount());
pageSql.append(") where row_id>");
pageSql.append(page.getCurrentResult());
}
return pageSql.toString();
}else{
return sql;
}
}
public Object plugin(Object arg0) {
// TODO Auto-generated method stub
return Plugin.wrap(arg0, this);
}
public void setProperties(Properties p) {
dialect = p.getProperty("dialect");
if (Tools.isEmpty(dialect)) {
try {
throw new PropertyException("dialect property is not found!");
} catch (PropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pageSqlId = p.getProperty("pageSqlId");
if (Tools.isEmpty(pageSqlId)) {
try {
throw new PropertyException("pageSqlId property is not found!");
} catch (PropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
三、HelloController.java文件内容:
package com.winphone.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.winphone.entity.LoginUser;
import com.winphone.service.LoginUserService;
@Controller
public class HelloController {
@Autowired
private LoginUserService loginUserService;
@RequestMapping(value="/Hello")
public String HelloWorld(Model model){
LoginUser loginUser = new LoginUser();
loginUser.setUserName("admin");
List<LoginUser> list = loginUserService.listLoginUsers(loginUser);
model.addAttribute("message",list.get(0).getUserName());
return "HelloWorld";
}
}
四、LoginUser.java文件内容:
/**
*
*/
package com.winphone.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* 实体: 登录用户表
* @author
* @version
*/
@XmlRootElement(name = "LoginUser")
public class LoginUser {
private String onlineStatus;//用户在线状态 00-不在线 01-在线
private String pwErrorNumber;//密码错误次数
private String userType;//登录类型类型
private String userName;//用户名
private String loginUserId;//用户ID
private String password;//密码
private String lastLoginTime;//上次登录时间
private String loginUserStatus;//登录用户状态
private List<String> loginUserIdList;//用户id集合
private List<String> roleIdList;//角色id集合
private Page page;//分页
private String newPassword;//新密码
private String confirmPassword;//确认新密码
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getLoginUserStatus() {
return loginUserStatus;
}
public void setLoginUserStatus(String loginUserStatus) {
this.loginUserStatus = loginUserStatus;
}
public List<String> getRoleIdList() {
return roleIdList;
}
public void setRoleIdList(List<String> roleIdList) {
this.roleIdList = roleIdList;
}
public List<String> getLoginUserIdList() {
return loginUserIdList;
}
public void setLoginUserIdList(List<String> loginUserIdList) {
this.loginUserIdList = loginUserIdList;
}
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public String getOnlineStatus(){
return this.onlineStatus;
}
public void setOnlineStatus(String onlineStatus){
this.onlineStatus = onlineStatus;
}
public String getPwErrorNumber(){
return this.pwErrorNumber;
}
public void setPwErrorNumber(String pwErrorNumber){
this.pwErrorNumber = pwErrorNumber;
}
public String getUserType(){
return this.userType;
}
public void setUserType(String userType){
this.userType = userType;
}
public String getUserName(){
return this.userName;
}
public void setUserName(String userName){
this.userName = userName;
}
public String getLoginUserId(){
return this.loginUserId;
}
public void setLoginUserId(String loginUserId){
this.loginUserId = loginUserId;
}
public String getPassword(){
return this.password;
}
public void setPassword(String password){
this.password = password;
}
public String getLastLoginTime(){
return this.lastLoginTime;
}
public void setLastLoginTime(String lastLoginTime){
this.lastLoginTime = lastLoginTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((onlineStatus == null) ? 0 : onlineStatus.hashCode());
result = prime * result + ((pwErrorNumber == null) ? 0 : pwErrorNumber.hashCode());
result = prime * result + ((userType == null) ? 0 : userType.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
result = prime * result + ((loginUserId == null) ? 0 : loginUserId.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((lastLoginTime == null) ? 0 : lastLoginTime.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final LoginUser other = (LoginUser) obj;
if (onlineStatus == null) {
if (other.onlineStatus != null)
return false;
} else if (!onlineStatus.equals(other.onlineStatus))
return false;
if (pwErrorNumber == null) {
if (other.pwErrorNumber != null)
return false;
} else if (!pwErrorNumber.equals(other.pwErrorNumber))
return false;
if (userType == null) {
if (other.userType != null)
return false;
} else if (!userType.equals(other.userType))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
if (loginUserId == null) {
if (other.loginUserId != null)
return false;
} else if (!loginUserId.equals(other.loginUserId))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (lastLoginTime == null) {
if (other.lastLoginTime != null)
return false;
} else if (!lastLoginTime.equals(other.lastLoginTime))
return false;
return true;
}
public String toString(){
return super.toString();
}
}
五、Page.java文件内容:
package com.winphone.entity;
public class Page {
private int showCount = 10; //每页显示记录数
private int totalPage; //总页数
private int totalResult; //总记录数
private int currentPage; //当前页
private int currentResult; //当前记录起始索引
private boolean entityOrField; //true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性
private String pageStr; //最终页面显示的底部翻页导航,详细见:getPageStr();
public int getTotalPage() {
if(totalResult%showCount==0)
totalPage = totalResult/showCount;
else
totalPage = totalResult/showCount+1;
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotalResult() {
return totalResult;
}
public void setTotalResult(int totalResult) {
this.totalResult = totalResult;
}
public int getCurrentPage() {
if(currentPage<=0)
currentPage = 1;
if(currentPage>getTotalPage())
currentPage = getTotalPage();
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public String getPageStr() {
StringBuffer sb = new StringBuffer();
if(totalResult>0){
sb.append(" <ul>\n");
if(currentPage==1){
sb.append(" <li class=\"pageinfo\">首页</li>\n");
sb.append(" <li class=\"pageinfo\">上页</li>\n");
}else{
sb.append(" <li><a href=\"#@\" οnclick=\"nextPage(1)\">首页</a></li>\n");
sb.append(" <li><a href=\"#@\" οnclick=\"nextPage("+(currentPage-1)+")\">上页</a></li>\n");
}
int showTag = 3; //分页标签显示数量
int startTag = 1;
if(currentPage>showTag){
startTag = currentPage-1;
}
int endTag = startTag+showTag-1;
for(int i=startTag; i<=totalPage && i<=endTag; i++){
if(currentPage==i)
sb.append("<li class=\"current\">"+i+"</li>\n");
else
sb.append(" <li><a href=\"#@\" οnclick=\"nextPage("+i+")\">"+i+"</a></li>\n");
}
if(currentPage==totalPage){
sb.append(" <li class=\"pageinfo\">下页</li>\n");
sb.append(" <li class=\"pageinfo\">尾页</li>\n");
}else{
sb.append(" <li><a href=\"#@\" οnclick=\"nextPage("+(currentPage+1)+")\">下页</a></li>\n");
sb.append(" <li><a href=\"#@\" οnclick=\"nextPage("+totalPage+")\">尾页</a></li>\n");
}
sb.append(" <li class=\"pageinfo\">第"+currentPage+"页</li>\n");
sb.append(" <li class=\"pageinfo\">共"+totalPage+"页</li>\n");
sb.append("</ul>\n");
sb.append("<script type=\"text/javascript\">\n");
sb.append("function nextPage(page){");
sb.append(" if(true && document.forms[0]){\n");
sb.append(" var url = document.forms[0].getAttribute(\"action\");\n");
sb.append(" if(url.indexOf('?')>-1){url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
sb.append(" else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
sb.append(" document.forms[0].action = url+page;\n");
sb.append(" document.forms[0].submit();\n");
sb.append(" }else{\n");
sb.append(" var url = document.location+'';\n");
sb.append(" if(url.indexOf('?')>-1){\n");
sb.append(" if(url.indexOf('currentPage')>-1){\n");
sb.append(" var reg = /currentPage=\\d*/g;\n");
sb.append(" url = url.replace(reg,'currentPage=');\n");
sb.append(" }else{\n");
sb.append(" url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";\n");
sb.append(" }\n");
sb.append(" }else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
sb.append(" document.location = url + page;\n");
sb.append(" }\n");
sb.append("}\n");
sb.append("</script>\n");
}
pageStr = sb.toString();
return pageStr;
}
public void setPageStr(String pageStr) {
this.pageStr = pageStr;
}
public int getShowCount() {
return showCount;
}
public void setShowCount(int showCount) {
this.showCount = showCount;
}
public int getCurrentResult() {
currentResult = (getCurrentPage()-1)*getShowCount();
if(currentResult<0)
currentResult = 0;
return currentResult;
}
public void setCurrentResult(int currentResult) {
this.currentResult = currentResult;
}
public boolean isEntityOrField() {
return entityOrField;
}
public void setEntityOrField(boolean entityOrField) {
this.entityOrField = entityOrField;
}
}
六、PageRestful.java文件内容:
package com.winphone.entity;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* 分页
* @author maogaofei
* @date 2016年8月30日 上午9:39:58
*/
@XmlRootElement(name = "PageRestful")
public class PageRestful {
private Page page;//分页
private List<LoginUser> loginUsers;//登录用户
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
public List<LoginUser> getLoginUsers() {
return loginUsers;
}
public void setLoginUsers(List<LoginUser> loginUsers) {
this.loginUsers = loginUsers;
}
}
七、LoginUserMapper.java 文件内容:
/**
* 代码声明
*/
package com.winphone.mapper;
import java.util.List;
import com.winphone.entity.LoginUser;
public interface LoginUserMapper {
/**
* 根据条件插入对象字段
*/
int insertSelective(LoginUser loginUser);
/**
* 根据主键删除
*/
int deleteByPrimaryKey(String loginUserId);
/**
* 根据条件修改对象属性
*/
int updateByPrimaryKeySelective(LoginUser loginUser);
/**
* 根据主键查询
*/
LoginUser selectByPrimaryKey(String loginUserId);
/**
* 根据条件查询列表
*/
List<LoginUser> listLoginUsers(LoginUser loginUser);
/**
* 根据条件分页查询列表
*/
List<LoginUser> listPageLoginUser(LoginUser loginUser);
}
八、LoginUserServiceImpl.java文件内容:
/**
* 代码声明
*/
package com.winphone.service.impl;
import com.winphone.entity.PageRestful;
import java.util.List;
import com.winphone.entity.LoginUser;
import com.winphone.mapper.LoginUserMapper;
import com.winphone.service.LoginUserService;
public class LoginUserServiceImpl implements LoginUserService {
private LoginUserMapper loginUserMapper;
public LoginUserMapper getLoginUserMapper() {
return loginUserMapper;
}
public void setLoginUserMapper(
LoginUserMapper loginUserMapper) {
this.loginUserMapper = loginUserMapper;
}
@Override
public int insertLoginUser(LoginUser loginUser) {
return loginUserMapper.insertSelective(loginUser);
}
@Override
public int deleteLoginUser(String loginUserId) {
return loginUserMapper.deleteByPrimaryKey(loginUserId);
}
@Override
public int updateLoginUser(LoginUser loginUser) {
return loginUserMapper.updateByPrimaryKeySelective(loginUser);
}
@Override
public List<LoginUser> listLoginUsers(LoginUser loginUser) {
List<LoginUser> loginUserList = loginUserMapper.listLoginUsers(loginUser);
return loginUserList;
}
@Override
public PageRestful listPageLoginUser(LoginUser loginUser) {
PageRestful pageRestful=new PageRestful();
List<LoginUser> loginUsers = loginUserMapper.listPageLoginUser(loginUser);
loginUsers.add(0,null);
pageRestful.setLoginUsers(loginUsers);
pageRestful.setPage(loginUser.getPage());
return pageRestful;
}
@Override
public LoginUser selectByPrimaryKey(String loginUserId) {
return loginUserMapper.selectByPrimaryKey(loginUserId);
}
}
九、LoginUserService.java文件内容:
/**
* 代码声明
*/
package com.winphone.service;
import java.util.List;
import com.winphone.entity.PageRestful;
import com.winphone.entity.LoginUser;
public interface LoginUserService{
/**
* 新增
*/
int insertLoginUser(LoginUser loginUser);
/**
* 根据ID删除数据
*/
int deleteLoginUser(String loginUserId);
/**
* 修改
*/
int updateLoginUser(LoginUser loginUser);
/**
* 根据条件查询列表
*/
List<LoginUser> listLoginUsers(LoginUser loginUser);
/**
* 根据条件分页查询列表
*/
PageRestful listPageLoginUser(LoginUser loginUser);
/**
* 根据ID获取登录用户
* @author maogaofei
* @date 2016年9月9日 下午3:57:31
* @param loginUserId
* @return
*/
LoginUser selectByPrimaryKey(String loginUserId);
}
十、DateUtil.java文件内容:
package com.winphone.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 日期公共方法
* @author maogaofei
* @date 2016年9月1日 下午3:09:32
*/
public class DateUtil {
private static SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
/**
* 得到本月的最后一天
*
* @return
*/
public String getMonthLastDay(String month) {
String[] str=month.split("-");
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,Integer.parseInt(str[0]));
c.set(Calendar.MONTH, Integer.parseInt(str[1])-1);
c.set(Calendar.MONTH, c.get(Calendar.MONTH)+1);
c.set(Calendar.DAY_OF_MONTH, 1);
return dateFormat.format(c.getTime());
}
/**
* 查询当前时间,返回时间类型
*
* @return
*/
public static Date currentDate() {
long dateLong = System.currentTimeMillis();
Date date = new Date(dateLong);
return date;
}
public static String getToday(){
String time = "";
time = getToday("yyyy-MM-dd");
return time;
}
public static String getToday(String format){
return getDateStr(Calendar.getInstance().getTime(), format);
}
public static String getDateStr(Date date, String format){
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
public static void main(String[] args) {
System.out.println(DateUtil.getToday("yyyy-MM-dd HH:mm:ss"));
}
}
十一、ReflectHelper.java文件内容:
package com.winphone.utils;
import java.lang.reflect.Field;
/**
* @author Administrator
* 反射工具
*/
public class ReflectHelper {
/**
* 获取obj对象fieldName的Field
* @param obj
* @param fieldName
* @return
*/
public static Field getFieldByFieldName(Object obj, String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
}
return null;
}
/**
* 获取obj对象fieldName的属性值
* @param obj
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object getValueByFieldName(Object obj, String fieldName)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
Object value = null;
if(field!=null){
if (field.isAccessible()) {
value = field.get(obj);
} else {
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
}
}
return value;
}
/**
* 设置obj对象fieldName的属性值
* @param obj
* @param fieldName
* @param value
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setValueByFieldName(Object obj, String fieldName,
Object value) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(fieldName);
if (field.isAccessible()) {
field.set(obj, value);
} else {
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
}
}
十二、Tools.java文件内容:
package com.winphone.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.winphone.common.Info;
public class Tools {
/**
* 检测字符串是否不为空(null,"","null")
* @param s
* @return 不为空则返回true,否则返回false
*/
public static boolean notEmpty(String s){
return s!=null && !"".equals(s) && !"null".equals(s);
}
/**
* 检测字符串是否为空(null,"","null")
* @param s
* @return 为空则返回true,不否则返回false
*/
public static boolean isEmpty(String s){
return s==null || "".equals(s) || "null".equals(s);
}
/**
* 字符串转换为字符串数组
* @param str 字符串
* @param splitRegex 分隔符
* @return
*/
public static String[] str2StrArray(String str,String splitRegex){
if(isEmpty(str)){
return null;
}
return str.split(splitRegex);
}
/**
* 用默认的分隔符(,)将字符串转换为字符串数组
* @param str 字符串
* @return
*/
public static String[] str2StrArray(String str){
return str2StrArray(str,",\\s*");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
* @param date
* @return yyyy-MM-dd HH:mm:ss
*/
public static String date2Str(Date date){
return date2Str(date,"yyyy-MM-dd HH:mm:ss");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期
* @param date
* @return
*/
public static Date str2Date(String date){
if(notEmpty(date)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Date();
}else{
return null;
}
}
/**
* 按照参数format的格式,日期转字符串
* @param date
* @param format
* @return
*/
public static String date2Str(Date date,String format){
if(date!=null){
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}else{
return "";
}
}
/**
* 返回调用接口的信息
* @param obj
* @param rsult
* @return
*/
public static Info msg(Object obj ,boolean rsult){
if(rsult){
Info info = new Info();
info.setInfo(obj);
info.setState("success");
return info;
}else{
Info info = new Info();
info.setInfo(obj);
info.setState("false");
return info;
}
}
}