StitchAttrUtil.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.iamberry.rst.utils;
  2. import com.iamberry.rst.core.page.PagedResult;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import java.lang.reflect.Field;
  5. import java.util.*;
  6. public class StitchAttrUtil {
  7. public final static String noProperty[] = {"serialVersionUID"};
  8. public static Set<String> propertySet = new HashSet<String>(Arrays.asList(noProperty));
  9. /**
  10. * 组装ModelAndView
  11. * @param object
  12. * @param modelAndView
  13. * @param url
  14. * @param pagedResult
  15. * @throws IllegalAccessException
  16. */
  17. public static void setModelAndView(Object object, ModelAndView modelAndView, String url, PagedResult<?> pagedResult) {
  18. StringBuilder sb = new StringBuilder(url);
  19. if(pagedResult.getTotal() != 0) {
  20. pagedResult.setPages((int) Math.ceil((double)pagedResult.getTotal()/pagedResult.getPageSize()));
  21. }
  22. sb.append("?pageSize=" + pagedResult.getPageSize());
  23. sb.append("&totalNum=" + pagedResult.getTotal() );
  24. StitchAttrUtil.setUrlByObj(sb,object);
  25. sb.append("&&pageNO=");
  26. Map<String, Object> map = StitchAttrUtil.getObjToMap(object);
  27. modelAndView.addAllObjects(map);
  28. modelAndView.addObject("page", pagedResult);
  29. modelAndView.addObject("url", sb.toString());
  30. return;
  31. }
  32. /**
  33. * 将obj 转为map,
  34. * 属性值为null的不会 put 到 Map 中
  35. * 属性名称在 noProperty 数组中的属性不会 put 到 Map 中
  36. * @param object
  37. * @return
  38. * @throws IllegalAccessException
  39. */
  40. public static Map<String, Object> getObjToMap(Object object) {
  41. Map<String, Object> map = new HashMap<>();
  42. Class<?> clazz = object.getClass();
  43. for (Field field : clazz.getDeclaredFields()) {
  44. field.setAccessible(true);
  45. String fieldName = field.getName();
  46. Object value = null;
  47. try {
  48. value = field.get(object);
  49. }catch (IllegalAccessException e){
  50. }
  51. if (value != null && !propertySet.contains(fieldName)) {
  52. map.put(fieldName, value);
  53. }
  54. }
  55. return map;
  56. }
  57. /**
  58. * 拼接url
  59. * @param sb
  60. * @param object
  61. * @throws IllegalAccessException
  62. */
  63. public static void setUrlByObj(StringBuilder sb,Object object){
  64. Class<?> clazz = object.getClass();
  65. for (Field field : clazz.getDeclaredFields()) {
  66. field.setAccessible(true);
  67. String fieldName = field.getName();
  68. Object value = null;
  69. try {
  70. value = field.get(object);
  71. }catch (IllegalAccessException e){
  72. }
  73. if (value != null && !propertySet.contains(fieldName)) {
  74. sb.append("&"+fieldName+ "=" + value.toString());
  75. }
  76. }
  77. }
  78. }