zoukankan      html  css  js  c++  java
  • 【ssm】极简的极省力的开发方式——针对简单型EasyUI的增删改查的后台管理

    需要具备技能点:

    ssm框架搭建,mybatis generator的熟练使用

    1.控制器:

    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.公司名字.service.IActivityService;
    
    @Controller
    @RequestMapping("manage/act")
    public class ActivityController extends BaseClass {
    
    	@Autowired
    	private IActivityService actService;
    
    	@RequestMapping("index/{name}")
    	public String index(@PathVariable(value = "name") String name, HttpServletRequest req, HttpServletResponse res) {
    		return "act/" + name + "/index";
    	}
    
    	@RequestMapping("list/{name}")
    	@ResponseBody
    	public EasyUIResult<?> list(@PathVariable(value = "name") String name, HttpServletRequest req,
    			PageParam pageParam) {
    		try {
    			Object example = actService.createExampleByName(name, req);
    			return actService.list(example, pageParam);
    		} catch (Exception e) {
    			logger.error(e.getMessage());
    		}
    		return null;
    	}
    
    	@ResponseBody
    	@RequestMapping("save/{name}")
    	public Map<Object, Object> update(@PathVariable(value = "name") String name, HttpServletRequest req,
    			HttpServletResponse res) {
    		Map<Object, Object> resultMap = new HashMap<>();
    		try {
    			Object obj = actService.getBean(name, req);
    			obj = actService.saveOrUpdate(obj);
    			resultMap.put("data", obj);
    			resultMap.put("status", true);
    			resultMap.put("msg", "保存成功");
    		} catch (Exception e) {
    			resultMap.put("status", false);
    			resultMap.put("msg", "保存失败");
    			logger.error(e.getMessage());
    		}
    		return resultMap;
    	}
    
    	@ResponseBody
    	@RequestMapping("del/{name}")
    	public Map<Object, Object> del(@PathVariable(value = "name") String name,
    			@RequestParam(value = "ids", required = true) Integer[] ids, HttpServletRequest req,
    			HttpServletResponse res) {
    		Map<Object, Object> resultMap = new HashMap<>();
    		try {
    			Object success = actService.del(name, ids);
    			resultMap.put("data", success);
    			resultMap.put("status", true);
    			resultMap.put("msg", "刪除成功!");
    		} catch (Exception e) {
    			resultMap.put("status", false);
    			resultMap.put("msg", "刪除失败!");
    			logger.error(e.getMessage());
    		}
    		return resultMap;
    	}
    
    	@ResponseBody
    	@RequestMapping("export/{name}")
    	public void export(@PathVariable(value = "name") String name, HttpServletRequest req, HttpServletResponse res) {
    		
    	}
    }
    

      2.BaseClass

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class BaseClass {
    	protected Logger logger = LoggerFactory.getLogger(getClass());
    }
    

      3.Service实现

      1 package com.*.service.impl;
      2 
      3 import java.io.File;
      4 import java.io.FileOutputStream;
      5 import java.lang.reflect.Method;
      6 import java.sql.Timestamp;
      7 import java.text.SimpleDateFormat;
      8 import java.util.ArrayList;
      9 import java.util.Date;
     10 import java.util.HashMap;
     11 import java.util.List;
     12 import java.util.Map;
     13 import java.util.Map.Entry;
     14 import java.util.UUID;
     15 import java.util.concurrent.ConcurrentHashMap;
     16 
     17 import javax.servlet.http.HttpServletRequest;
     18 
     19 import org.apache.commons.lang3.StringUtils;
     20 import org.springframework.beans.factory.annotation.Autowired;
     21 import org.springframework.beans.factory.annotation.Value;
     22 import org.springframework.stereotype.Service;
     23 import org.springframework.transaction.annotation.Propagation;
     24 import org.springframework.transaction.annotation.Transactional;
     25 import org.springframework.web.bind.ServletRequestDataBinder;
     26 import org.springframework.web.multipart.MultipartFile;
     27 import org.springframework.web.multipart.MultipartHttpServletRequest;
     28 
     29 import com.*.dao.SuperDaoImpl;
     30 import com.*.pojo.ActInfo;
     31 import com.*.pojo.ActInfoExample;
     32 import com.*.pojo.ActResource;
     33 import com.*.pojo.ActResourceExample;
     34 import com.*.pojo.ActResourceIndex;
     35 import com.*.pojo.ActResourceIndexExample;
     36 import com.*.pojo.ActTactics;
     37 import com.*.pojo.ActTacticsExample;
     38 import com.*.pojo.BaseClass;
     39 import com.*.pojo.Limit;
     40 import com.*.pojo.vo.EasyUIResult;
     41 import com.*.pojo.vo.PageParam;
     42 import com.*.service.IActivityService;
     43 
     44 @Service(value = "actService")
     45 public class ActivityServiceImpl extends BaseClass implements IActivityService {
     46     // adv.resource.img.URL=/webapp/upload/files/home/act_resource/
     47     // adv.resource.img.url.pre=http://127.0.0.1:32812/files/home/act_resource/
     48     public static final SimpleDateFormat DATE_FORMAT_LONG = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     49     public static final SimpleDateFormat DATE_FORMAT_SHORT = new SimpleDateFormat("yyyy-MM-dd");
     50     
     51     
     52     @Value(value = "${adv.resource.img.URL}")
     53     private String savePath;
     54     @Value(value = "${adv.resource.img.url.pre}")
     55     private String imgPrefix;
     56     @Value(value = "${adv.resource.img.url.pre}")
     57     private String exportInfoTacticsSQL;
     58 
     59     private static final String INFO_KEY = "actInfo";
     60     private static final String RESOURCE_KEY = "actResource";
     61     private static final String RESOURCE_INDEX_KEY = "actResourceIndex";
     62     private static final String TACTICS_KEY = "actTactics";
     63 
     64     private static final Map<String, Class<?>> BEAN_NAME_MAP = new ConcurrentHashMap<>();
     65 
     66     static {
     67         BEAN_NAME_MAP.put(RESOURCE_KEY, ActResource.class);
     68         BEAN_NAME_MAP.put(TACTICS_KEY, ActTactics.class);
     69         BEAN_NAME_MAP.put(INFO_KEY, ActInfo.class);
     70         BEAN_NAME_MAP.put(RESOURCE_INDEX_KEY, ActResourceIndex.class);
     71     }
     72 
     73     @Autowired
     74     private SuperDaoImpl superDao;
     75 
     76     @Transactional(propagation = Propagation.REQUIRED)
     77     public Object saveOrUpdate(Object obj) {
     78         try {
     79             if (obj == null) {
     80                 logger.warn("the obj can not be null !");
     81                 return null;
     82             }
     83 
     84             Method method = obj.getClass().getDeclaredMethod("getId");
     85             Object id = method.invoke(obj);
     86             boolean success = false;
     87             if (id == null) {
     88                 Method setCreateTimeMethod = null;
     89                 if (obj.getClass().getMethod("setCreateTime", String.class) != null) {
     90                     setCreateTimeMethod = obj.getClass().getMethod("setCreateTime", String.class);
     91                     setCreateTimeMethod.invoke(obj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));// setCreateTime(
     92                                                                                                                     // );
     93                 }
     94                 
     95                 if (obj instanceof ActResourceIndex) {
     96                     ActResourceIndex idx=(ActResourceIndex) obj;
     97                     idx.setUniqueCode(UUID.randomUUID().toString().replaceAll("-", ""));
     98                 }
     99                 
    100                 success = superDao.insertSelective(obj) > 0;
    101             } else {
    102                 success = superDao.updateByPrimaryKeySelective(obj) > 0;
    103             }
    104             if (success) {
    105                 return obj;
    106             } else {
    107                 return false;
    108             }
    109         } catch (Exception e) {
    110             logger.warn(e.getMessage());
    111         }
    112         return false;
    113     }
    114 
    115     @Transactional(propagation = Propagation.REQUIRED)
    116     public Object del(String name, Integer[] ids) {
    117         try {
    118             if (name == null) {
    119                 return false;
    120             }
    121 
    122             Class<?> clazz = BEAN_NAME_MAP.get(name);
    123             boolean[] flags = new boolean[ids.length];
    124             for (int i = 0; i < ids.length; i++) {
    125                 flags[i] = superDao.deleteByPrimaryKey(ids[i], clazz) > 0;
    126             }
    127 
    128             return flags;
    129         } catch (Exception e) {
    130             logger.error(e.getMessage());
    131         }
    132         return false;
    133     }
    134 
    135     /**
    136      * 搜索
    137      */
    138     @SuppressWarnings({ "unchecked", "rawtypes" })
    139     public EasyUIResult<?> list(Object example, PageParam page) {
    140 
    141         EasyUIResult<?> rs = new EasyUIResult<>();
    142 
    143         int count = superDao.countByExample(example);
    144         rs.setTotal(count);
    145 
    146         setLimit(example, page);
    147         setOrder(example, page);
    148         List lst = superDao.selectByExample(example);
    149         rs.setRows(lst);
    150         return rs;
    151     }
    152 
    153     /**
    154      * 自动封装bean,摘自:https://zhidao.baidu.com/question/198956630.html
    155      * 
    156      * @param name
    157      * @param req
    158      * @return
    159      */
    160     public Object getBean(String name, HttpServletRequest req) {
    161         try {
    162             if (StringUtils.isNotBlank(name)) {
    163                 Class<?> clazz = BEAN_NAME_MAP.get(name);
    164 
    165                 if (clazz == null) {
    166                     logger.warn("没有找到要封装的实体类!");
    167                     return null;
    168                 }
    169                 Object bean = clazz.newInstance();
    170                 ServletRequestDataBinder binder = new ServletRequestDataBinder(bean);
    171                 binder.bind(req);
    172 
    173                 List<UploadResult> rs = uploadImg(req);
    174 
    175                 if (rs != null && rs.size() > 0) {
    176                     if (rs.get(0).isSuccess()) {
    177                         setImgPath(bean, rs.get(0).getPrefix());
    178                     }
    179                 }
    180                 return bean;
    181             }
    182         } catch (Exception e) {
    183             logger.error(e.getMessage());
    184         }
    185         return null;
    186     }
    187 
    188     /**
    189      * 创建搜索对象
    190      */
    191     public Object createExampleByName(String name, HttpServletRequest req) {
    192         try {
    193             if (name.equals(RESOURCE_KEY)) {
    194                 return createResourceExample(req);
    195             } else if (name.equals(INFO_KEY)) {
    196                 return createInfoExample(req);
    197             } else if (name.equals(TACTICS_KEY)) {
    198                 return createTacticsExample(req);
    199             }else if(name.equals(RESOURCE_INDEX_KEY)){
    200                 return createResourceIndexExample(req);
    201             }
    202         } catch (Exception e) {
    203             logger.error(e.getMessage());
    204         }
    205         return null;
    206     }
    207 
    208     private Object createResourceIndexExample(HttpServletRequest req) {
    209         Object obj = getBean(RESOURCE_INDEX_KEY, req);
    210 
    211         if (obj != null && obj instanceof ActResourceIndex) {
    212             ActResourceIndex bean = (ActResourceIndex) obj;
    213             ActResourceIndexExample example = new ActResourceIndexExample();
    214             com.*.pojo.ActResourceIndexExample.Criteria c = example.createCriteria();
    215             if (bean.getId()!=null) {
    216                 c.andIdEqualTo(bean.getId());
    217             }
    218             
    219             if (StringUtils.isNotBlank(bean.getName())) {
    220                 c.andNameLike("%"+bean.getName()+"%");
    221             }
    222             
    223             if (StringUtils.isNotBlank(bean.getUniqueCode())) {
    224                 c.andUniqueCodeLike("%"+bean.getUniqueCode()+"%");
    225             }
    226             
    227             if (StringUtils.isNotBlank(bean.getDescription())) {
    228                 c.andDescriptionLike("%"+bean.getUniqueCode()+"%");
    229             }
    230             
    231             if (StringUtils.isNotBlank(bean.getCreateTime())) {
    232                 c.andCreateTimeGreaterThanOrEqualTo(bean.getCreateTime()+" 00:00:00");
    233                 c.andCreateTimeLessThanOrEqualTo(bean.getCreateTime()+" 23:59:59");
    234             }
    235             return example;
    236         }
    237         return null;
    238     }
    239 
    240     private Object createTacticsExample(HttpServletRequest req) {
    241         Object bean = getBean(TACTICS_KEY, req);
    242 
    243         if (bean != null && bean instanceof ActTactics) {
    244             ActTactics tactics = (ActTactics) bean;
    245             ActTacticsExample example = new ActTacticsExample();
    246             com.*.pojo.ActTacticsExample.Criteria c = example.createCriteria();
    247 
    248             if (tactics.getId() != null) {
    249                 c.andIdEqualTo(tactics.getId());
    250             }
    251 
    252             if (StringUtils.isNotBlank(tactics.getActCode())) {
    253                 c.andActCodeEqualTo(tactics.getActCode());
    254             }
    255 
    256             if (StringUtils.isNotBlank(tactics.getName())) {
    257                 c.andNameLike("%" + tactics.getName() + "%");
    258             }
    259 
    260             if (StringUtils.isNotBlank(tactics.getCreateTime())) {
    261                 String value1 = tactics.getCreateTime() + " 00:00:00";
    262                 String value2 = tactics.getCreateTime() + " 23:59:59";
    263                 c.andCreateTimeBetween(value1, value2);
    264             }
    265 
    266             if (StringUtils.isNotBlank(tactics.getXcode())) {
    267                 c.andXcodeLike("%" + tactics.getName() + "%");
    268             }
    269 
    270             if (StringUtils.isNotBlank(tactics.getNeedCondition())) {
    271                 c.andNeedConditionLike("%" + tactics.getName() + "%");
    272             }
    273 
    274             if (StringUtils.isNotBlank(tactics.getSendResource())) {
    275                 c.andSendResourceLike("%" + tactics.getSendResource() + "%");
    276             }
    277             return example;
    278         }
    279 
    280         return null;
    281     }
    282 
    283     private Object createInfoExample(HttpServletRequest req) {
    284         Object bean = getBean(INFO_KEY, req);
    285 
    286         if (bean != null && bean instanceof ActInfo) {
    287 
    288             ActInfo info = (ActInfo) bean;
    289             ActInfoExample example = new ActInfoExample();
    290             com.*.pojo.ActInfoExample.Criteria c = example.createCriteria();
    291 
    292             if (info.getActivityId() != null) {
    293                 c.andActivityIdEqualTo(info.getActivityId());
    294             }
    295 
    296             if (StringUtils.isNotBlank(info.getActivityName())) {
    297                 c.andActivityNameLike("%" + info.getActivityName() + "%");
    298             }
    299 
    300             if (StringUtils.isNotBlank(info.getCityCode())) {
    301                 if (!info.getCityCode().equals("0")) {
    302                     c.andCityCodeLike("%" + info.getCityCode() + "%");
    303                 }
    304             }
    305 
    306             if (StringUtils.isNotBlank(info.getStartTime())) {
    307                 c.andStartTimeGreaterThanOrEqualTo(info.getStartTime());
    308             }
    309 
    310             if (StringUtils.isNotBlank(info.getEndTime())) {
    311                 c.andEndTimeLessThanOrEqualTo(info.getEndTime());
    312             }
    313 
    314             if (StringUtils.isNotBlank(info.getCreateTime())) {
    315                 String value1 = info.getCreateTime() + " 00:00:00";
    316                 String value2 = info.getCreateTime() + " 23:59:59";
    317                 c.andCreateTimeLessThanOrEqualTo(value2);
    318                 c.andCreateTimeGreaterThanOrEqualTo(value1);
    319             }
    320             return example;
    321         }
    322 
    323         return null;
    324     }
    325 
    326     private Object createResourceExample(HttpServletRequest req) {
    327         Object bean = getBean(RESOURCE_KEY, req);
    328 
    329         if (bean != null && bean instanceof ActResource) {
    330 
    331             ActResource resource = (ActResource) bean;
    332             ActResourceExample example = new ActResourceExample();
    333             com.*.pojo.ActResourceExample.Criteria c = example.createCriteria();
    334 
    335             if (resource.getId() != null) {
    336                 c.andIdEqualTo(resource.getId());
    337             }
    338 
    339             if (StringUtils.isNotBlank(resource.getActCode())) {
    340                 c.andActCodeEqualTo(resource.getActCode());
    341             }
    342 
    343             if (StringUtils.isNotBlank(resource.getSize())) {
    344                 c.andSizeLike("%" + resource.getSize() + "%");
    345             }
    346             return example;
    347         }
    348         return null;
    349     }
    350 
    351     public Object getExportResult(String name, HttpServletRequest req) {
    352         try {
    353             if (name.equals("actInfoTactics")) {
    354                 superDao.selectExportData(null, getExportDate().get(""),getExportDate().get(""));
    355             }
    356         } catch (Exception e) {
    357             e.printStackTrace();
    358         }
    359         return null;
    360     }
    361 
    362     public  Map<String, Object> getExportDate() {
    363         Map<String, Object> map = new HashMap<>();
    364         try {
    365             Date nowDate = new Date();
    366             String nowZeroTime = DATE_FORMAT_SHORT.format(nowDate);
    367             //后续如果需要改导出时间只需改动下面的3
    368             nowDate = DATE_FORMAT_LONG.parse(nowZeroTime + " 03:00:00");
    369             Date yestoday = new Timestamp(nowDate.getTime() - 3600 * 1000 * 24);
    370             String endTime = DATE_FORMAT_LONG.format(nowDate);
    371             String startTime = DATE_FORMAT_LONG.format(yestoday);
    372             
    373             map.put("startTimeStr", startTime);
    374             map.put("endTimeStr", endTime);
    375             map.put("startTime", yestoday);
    376             map.put("endTime", nowDate);
    377         } catch (Exception e) {
    378             e.printStackTrace();
    379         }
    380         return map;
    381     }
    382 
    383     private void setImgPath(Object obj, String path) {
    384         if (obj == null) {
    385             return;
    386         }
    387         Method[] mds = obj.getClass().getDeclaredMethods();
    388         for (Method method : mds) {
    389             if (method.getName().startsWith("setImg")) {
    390                 try {
    391                     method.invoke(obj, path);
    392                 } catch (Exception e) {
    393                     e.printStackTrace();
    394                 }
    395             }
    396         }
    397     }
    398 
    399     private List<UploadResult> uploadImg(HttpServletRequest request) {
    400         List<UploadResult> rs = new ArrayList<>();
    401         try {
    402             if (request instanceof MultipartHttpServletRequest) {
    403                 File file = new File(savePath);
    404                 if (!file.exists()) {
    405                     file.mkdirs();
    406                 }
    407                 int tmp = 0;
    408                 String originalName = "";
    409                 FileOutputStream fos = null;
    410                 MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    411                 Map<String, MultipartFile> fileMap = req.getFileMap();
    412                 for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
    413                     originalName = entry.getValue().getOriginalFilename();
    414                     tmp = originalName.lastIndexOf(".");
    415                     if (tmp == -1) {
    416                         continue;
    417                     }
    418 
    419                     file = new File(savePath + System.currentTimeMillis() + originalName.substring(tmp));
    420                     fos = new FileOutputStream(file);
    421                     fos.write(entry.getValue().getBytes());
    422                     rs.add(new UploadResult(imgPrefix + file.getName(), true));
    423                 }
    424                 if (fos != null)
    425                     fos.close();
    426             }
    427         } catch (Exception e) {
    428             e.printStackTrace();
    429         }
    430         return rs;
    431     }
    432 
    433     private void setLimit(Object example, PageParam page) {
    434         try {
    435             if (example==null) {
    436                 return;
    437             }
    438             Method method = example.getClass().getDeclaredMethod("setLimit", Limit.class);
    439             if (method==null) {
    440                 return;
    441             }
    442             method.invoke(example, new Limit((page.getPage() - 1) * page.getRows(), page.getRows()));
    443         } catch (Exception e) {
    444             e.printStackTrace();
    445         }
    446     }
    447 
    448     private void setOrder(Object example, PageParam page) {
    449         try {
    450             String orderByClause = "";
    451             if (StringUtils.isNotBlank(page.getOrder()) && StringUtils.isNoneBlank(page.getSort())) {
    452                 orderByClause = (convertOrderFiled(page.getSort()) + " " + page.getOrder());
    453 
    454             } else {
    455                 orderByClause = " create_time desc";
    456             }
    457             // setOrderByClause
    458             
    459             if (example==null) {
    460                 return;
    461             }
    462             Method method = example.getClass().getDeclaredMethod("setOrderByClause", String.class);
    463 
    464             if (method==null) {
    465                 return;
    466             }
    467             method.invoke(example, orderByClause);
    468         } catch (Exception e) {
    469             e.printStackTrace();
    470         }
    471     }
    472 
    473     private String convertOrderFiled(String str) {
    474         char[] ch = str.toCharArray();
    475         int index = -1;
    476         for (int i = 0; i < ch.length; i++) {
    477 
    478             if ('A' <= ch[i] && ch[i] <= 'Z') {
    479                 index = i;
    480                 break;
    481             }
    482         }
    483         if (index != -1) {
    484             str = str.substring(0, index) + "_" + ((char) (str.charAt(index) + 32)) + str.substring(index + 1);
    485         }
    486         return str;
    487     }
    488 
    489     public class UploadResult {
    490         public UploadResult() {
    491         }
    492 
    493         public UploadResult(String prefix, boolean success) {
    494             setPrefix(prefix);
    495             setSuccess(success);
    496         }
    497 
    498         private String url;
    499         private boolean success;
    500 
    501         public String getPrefix() {
    502             return url;
    503         }
    504 
    505         public void setPrefix(String prefix) {
    506             this.url = prefix;
    507         }
    508 
    509         public boolean isSuccess() {
    510             return success;
    511         }
    512 
    513         public void setSuccess(boolean success) {
    514             this.success = success;
    515         }
    516 
    517     }
    518 }
    View Code

    4.SuperDaoImpl

      1 package com.*.dao;
      2 
      3 import java.lang.reflect.Method;
      4 import java.util.Arrays;
      5 import java.util.List;
      6 import java.util.Map;
      7 import java.util.concurrent.ConcurrentHashMap;
      8 
      9 import org.apache.commons.lang3.StringUtils;
     10 import org.apache.ibatis.annotations.Param;
     11 import org.springframework.beans.BeansException;
     12 import org.springframework.context.ApplicationContext;
     13 import org.springframework.context.ApplicationContextAware;
     14 import org.springframework.jdbc.core.JdbcTemplate;
     15 import org.springframework.stereotype.Repository;
     16 
     17 import com.*.pojo.BaseClass;
     18 
     19 /**
     20  * mapper proxy,结合pageHelper+MyBatisGenerator简直所向无敌
     21  * 后期将加入redis缓存功能,结合nginx转发组成高并发后端
     22  * 
     23  * @author Administrator
     24  *
     25  */
     26 
     27 @Repository("superDao")
     28 public class SuperDaoImpl extends BaseClass implements ApplicationContextAware {
     29 
     30     /**************************************
     31      * 代理方法名 start
     32      ***************************************/
     33     public static final String COUNT_BY_EXAMPLE_METHOD_NAME = "countByExample";
     34     public static final String DELETE_BY_EXAMPLE_METHOD_NAME = "deleteByExample";
     35     public static final String DELETE_BY_PRIMARY_KEY_METHOD_NAME = "deleteByPrimaryKey";
     36     public static final String INSERT_METHOD_NAME = "insert";
     37     public static final String INSERT_SELECTIVE_METHOD_NAME = "insertSelective";
     38     public static final String SELECT_BY_EXAMPLE_METHOD_NAME = "selectByExample";
     39     public static final String SELECT_BY_PRIMARY_KEY_METHOD_NAME = "selectByPrimaryKey";
     40     public static final String UPDATE_BY_EXAMPLE_SELECTIVE_METHOD_NAME = "updateByExampleSelective";
     41     public static final String UPDATE_BY_EXAMPLE_METHOD_NAME = "updateByExample";
     42     public static final String UPDATE_BY_PRIMARYKEY_SELECTIVE_METHOD_NAME = "updateByPrimaryKeySelective";
     43     public static final String UPDATE_BY_PRIMARYKEY_METHOD_NAME = "updateByPrimaryKey";
     44     /**************************************
     45      * 代理方法名 end
     46      ***************************************/
     47 
     48     /**
     49      * mapper所在包的前缀
     50      */
     51     private String mapperPackagePrifix="com.*.mapper.";
     52     private static final Map<Object, Object> CACHE_MAP = new ConcurrentHashMap<>();
     53     /**
     54      * application 实例
     55      */
     56     private ApplicationContext ctx;
     57 
     58     public void setMapperPackagePrifix(String name) {
     59         this.mapperPackagePrifix = name;
     60     }
     61 
     62     /**
     63      * 根据一个对象查找Mapper,对象要么是实体类,要么是example
     64      * 
     65      * @param obj
     66      * @return
     67      */
     68     public Object findMapper(Object obj) {
     69         try {
     70             if (obj == null) {
     71                 logger.warn("the param obj instance can not be null !");
     72                 return null;
     73             }
     74             Class<?> clazz = obj.getClass();
     75 
     76             if (CACHE_MAP.get(clazz) != null) {
     77                 return CACHE_MAP.get(clazz);
     78             }
     79 
     80             String name = clazz.getSimpleName();
     81             String mapperClassName = "";
     82 
     83             if (name.endsWith("Example")) {
     84                 int index = name.indexOf("Example");
     85                 mapperClassName = mapperPackagePrifix + name.substring(0, index) + "Mapper";
     86             } else {
     87                 mapperClassName = mapperPackagePrifix + name + "Mapper";
     88             }
     89             logger.debug("mapper class name is :" + mapperClassName);
     90 
     91             Class<?> mapperClazz = Class.forName(mapperClassName);
     92             logger.debug("mapper is found :" + mapperClazz);
     93 
     94             CACHE_MAP.put(clazz, ctx.getBean(mapperClazz));
     95             return CACHE_MAP.get(clazz);
     96         } catch (Exception e) {
     97             logger.error("find mapper failed : " + e.getMessage());
     98         }
     99         return null;
    100     }
    101 
    102     /**
    103      * 查找方法
    104      * 
    105      * @param obj
    106      * @return
    107      */
    108     public Method findMethod(Object mapper, String methodName, Object... parameters) {
    109         try {
    110             if (mapper == null) {
    111                 logger.warn("the mapper can not be null ! ");
    112             }
    113             Class<?> clazz = mapper.getClass();
    114             Class<?>[] clazzArray = new Class[parameters.length];
    115             for (int i = 0; i < parameters.length; i++) {
    116                 if (parameters[i] == null) {
    117                     continue;
    118                 }
    119                 clazzArray[i] = parameters[i].getClass();
    120             }
    121             logger.debug("the clazz array is " + Arrays.toString(clazzArray));
    122             return clazz.getDeclaredMethod(methodName, clazzArray);
    123         } catch (Exception e) {
    124             logger.error(" find method : " + methodName + " is error," + e.getMessage());
    125         }
    126         return null;
    127     }
    128 
    129     /**
    130      * 查询数量
    131      * 
    132      * @param example
    133      * @return
    134      */
    135     public int countByExample(Object example) {
    136         try {
    137             if (example == null) {
    138                 logger.warn("countByExample failed,the example can not be null !");
    139                 return -1;
    140             }
    141 
    142             Object mapper = findMapper(example);
    143             logger.debug("mapper instance found for " + mapper.getClass());
    144 
    145             Method method = findMethod(mapper, COUNT_BY_EXAMPLE_METHOD_NAME, example);
    146             logger.debug("mapper instance found for " + mapper.getClass());
    147 
    148             return Integer.valueOf(method.invoke(mapper, example).toString());
    149         } catch (Exception e) {
    150             logger.error("countByExample failed, " + e.getMessage());
    151             e.printStackTrace();
    152         }
    153         return -1;
    154     }
    155 
    156     /**
    157      * 代理方法
    158      * 
    159      * @param example
    160      * @return
    161      */
    162     public int deleteByExample(Object example) {
    163         try {
    164             if (example == null) {
    165                 logger.warn("deleteByExample failed,the example can not be null !");
    166                 return -1;
    167             }
    168 
    169             Object mapper = findMapper(example);
    170             logger.debug("mapper instance found for " + mapper.getClass());
    171 
    172             Method method = findMethod(mapper, DELETE_BY_EXAMPLE_METHOD_NAME, example);
    173             logger.debug("mapper instance found for " + mapper.getClass());
    174 
    175             return (int) method.invoke(mapper, example);
    176         } catch (Exception e) {
    177             logger.error("deleteByExample failed, " + e.getMessage());
    178         }
    179         return -1;
    180     }
    181 
    182     /**
    183      * 代理方法
    184      * 
    185      * @param id
    186      * @param beanClazz
    187      * @return
    188      */
    189     public int deleteByPrimaryKey(Object id, Class<?> beanClazz) {
    190         String mapperClassName = "";
    191         try {
    192             if (id == null) {
    193                 logger.warn("deleteByPrimaryKey failed,the id can not be null !");
    194                 return -1;
    195             }
    196 
    197             if (beanClazz == null) {
    198                 logger.warn("deleteByPrimaryKey failed,the beanClazz can not be null !");
    199                 return -1;
    200             }
    201 
    202             mapperClassName = mapperPackagePrifix + beanClazz.getSimpleName() + "Mapper";
    203             Class<?> clazz = Class.forName(mapperClassName);
    204             logger.debug("Mapper class  found for " + mapperClassName);
    205 
    206             Object mapper =findMapper(beanClazz.newInstance());
    207             logger.debug("mapper instance found for " + mapper.getClass());
    208 
    209             Method method = clazz.getMethod(DELETE_BY_PRIMARY_KEY_METHOD_NAME, id.getClass());
    210             logger.debug("mapper instance found for " + mapper.getClass());
    211 
    212             return (int) method.invoke(mapper, id);
    213         } catch (Exception e) {
    214             logger.error("deleteByPrimaryKey failed, " + e.getMessage());
    215             e.printStackTrace();
    216         }
    217         return -1;
    218     }
    219 
    220     /**
    221      * 代理方法
    222      * 
    223      * @param record
    224      * @return
    225      */
    226     public int insert(Object record) {
    227         try {
    228             if (record == null) {
    229                 logger.warn("insert faild,the object can not be null !");
    230                 return -1;
    231             }
    232 
    233             Object mapper = findMapper(record);
    234             logger.debug("mapper instance found for " + mapper.getClass());
    235 
    236             Method insertMethod = findMethod(mapper, INSERT_METHOD_NAME, record);
    237             logger.debug("method  found in " + mapper.getClass());
    238 
    239             if (insertMethod == null) {
    240                 logger.warn("insert faild,the method dose not exits !");
    241                 return -1;
    242             }
    243 
    244             Object value = insertMethod.invoke(mapper, record);
    245             logger.info("insert success,the return value is: " + value);
    246             return (int) value;
    247         } catch (Exception e) {
    248             logger.error("insert faild," + e.getMessage());
    249         }
    250         return -1;
    251     }
    252 
    253     /**
    254      * 代理方法
    255      * 
    256      * @param record
    257      * @return
    258      */
    259     public int insertSelective(Object record) {
    260 
    261         try {
    262             if (record == null) {
    263                 logger.warn("insertSelective faild,the object can not be null !");
    264                 return -1;
    265             }
    266 
    267             Object mapper = findMapper(record);
    268             logger.debug("mapper instance found for " + mapper.getClass());
    269 
    270             Method insertMethod = findMethod(mapper, INSERT_SELECTIVE_METHOD_NAME, record);
    271             logger.debug("method  found in " + mapper.getClass());
    272 
    273             if (insertMethod == null) {
    274                 logger.warn("insertSelective faild,the method dose not exits !");
    275                 return -1;
    276             }
    277 
    278             Object value = insertMethod.invoke(mapper, record);
    279             logger.info("insertSelective success,the return value is: " + value);
    280             return (int) value;
    281         } catch (Exception e) {
    282             e.printStackTrace();
    283             logger.error("insertSelective faild," + e.getMessage());
    284         }
    285         return -1;
    286     }
    287 
    288     /**
    289      * 代理方法
    290      * 
    291      * @param example
    292      * @return
    293      */
    294     public List<?> selectByExample(Object example) {
    295         try {
    296             if (example == null) {
    297                 logger.warn("selectByExample failed,the example can not be null !");
    298                 return null;
    299             }
    300 
    301             Object mapper = findMapper(example);
    302             logger.debug("mapper instance found for " + mapper.getClass());
    303 
    304             Method method = findMethod(mapper, SELECT_BY_EXAMPLE_METHOD_NAME, example);
    305             logger.debug("mapper instance found for " + mapper.getClass());
    306 
    307             return (List<?>) method.invoke(mapper, example);
    308         } catch (Exception e) {
    309             logger.error("deleteByExample failed, " + e.getMessage());
    310             e.printStackTrace();
    311         }
    312         return null;
    313     }
    314 
    315     /**
    316      * 代理方法,代理原selectByPrimaryKey方法,由于原方法只需要主键,此处无法只需要一个主键,故加入一个Type
    317      * 
    318      * @param id
    319      * @param clazz
    320      * @return
    321      */
    322     @SuppressWarnings("unchecked")
    323     public <T> T selectByPrimaryKey(Object id, Class<T> clazz) {
    324         String mapperClassName = "";
    325         try {
    326             if (id == null) {
    327                 logger.warn("selectByPrimaryKey failed,the id can not be null !");
    328                 return null;
    329             }
    330 
    331             if (clazz == null) {
    332                 logger.warn("selectByPrimaryKey failed,the param clazz can not be null !");
    333                 return null;
    334             }
    335             mapperClassName = mapperPackagePrifix + clazz.getSimpleName() + "Mapper";
    336             Class<?> clazzMapper = Class.forName(mapperClassName);
    337             logger.debug("Mapper class  found for " + mapperClassName);
    338 
    339             Object mapper = ctx.getBean(clazzMapper);
    340             logger.debug("mapper instance found for " + mapper.getClass());
    341 
    342             Method method = clazzMapper.getMethod(SELECT_BY_PRIMARY_KEY_METHOD_NAME, id.getClass());
    343             logger.debug("mapper instance found for " + mapper.getClass());
    344 
    345             return (T) method.invoke(mapper, id);
    346         } catch (Exception e) {
    347             logger.error("selectByPrimaryKey failed, " + e.getMessage());
    348         }
    349         return null;
    350     }
    351 
    352     /**
    353      * 代理方法
    354      * 
    355      * @param record
    356      * @param example
    357      * @return
    358      */
    359     public int updateByExampleSelective(@Param("record") Object record, @Param("example") Object example) {
    360 
    361         try {
    362             if (record == null) {
    363                 logger.warn("updateByExampleSelective faild,the object can not be null !");
    364                 return -1;
    365             }
    366 
    367             Object mapper = findMapper(record);
    368             logger.debug("mapper instance found for " + mapper.getClass());
    369 
    370             Method updateByExampleSelectiveMethod = findMethod(mapper, UPDATE_BY_EXAMPLE_SELECTIVE_METHOD_NAME, record,
    371                     example);
    372             logger.debug("method  found in " + mapper.getClass());
    373 
    374             if (updateByExampleSelectiveMethod == null) {
    375                 logger.warn("updateByExampleSelectiveMethod faild,the method dose not exits !");
    376                 return -1;
    377             }
    378 
    379             Object value = updateByExampleSelectiveMethod.invoke(mapper, record, example);
    380             logger.debug("updateByExampleSelective success,the return value is: " + value);
    381             return (int) value;
    382         } catch (Exception e) {
    383             logger.error("updateByExampleSelective faild," + e.getMessage());
    384         }
    385         return -1;
    386     }
    387 
    388     /**
    389      * 代理方法
    390      * 
    391      * @param record
    392      * @param example
    393      * @return
    394      */
    395     public int updateByExample(@Param("record") Object record, @Param("example") Object example) {
    396 
    397         try {
    398             if (record == null) {
    399                 logger.warn("updateByExample faild,the record can not be null !");
    400                 return -1;
    401             }
    402             if (example == null) {
    403                 logger.warn("updateByExample faild,the example can not be null !");
    404                 return -1;
    405             }
    406 
    407             Object mapper = findMapper(record);
    408             logger.debug("mapper instance found for " + mapper.getClass());
    409 
    410             Method updateByExampleSelectiveMethod = findMethod(mapper, UPDATE_BY_EXAMPLE_METHOD_NAME, record, example);
    411             logger.debug("method  found in " + mapper.getClass());
    412 
    413             if (updateByExampleSelectiveMethod == null) {
    414                 logger.warn("updateByExample faild,the method dose not exits !");
    415                 return -1;
    416             }
    417 
    418             Object value = updateByExampleSelectiveMethod.invoke(mapper, record, example);
    419             logger.debug("updateByExample success,the return value is: " + value);
    420             return (int) value;
    421         } catch (Exception e) {
    422             logger.error("updateByExample faild," + e.getMessage());
    423         }
    424         return -1;
    425     }
    426 
    427     /**
    428      * 代理方法
    429      * 
    430      * @param record
    431      * @return
    432      */
    433     public int updateByPrimaryKeySelective(Object record) {
    434 
    435         try {
    436             if (record == null) {
    437                 logger.warn("updateByPrimaryKeySelective faild,the object can not be null !");
    438                 return -1;
    439             }
    440 
    441             Object mapper = findMapper(record);
    442             logger.debug("mapper instance found for " + mapper.getClass());
    443 
    444             Method updateByExampleSelectiveMethod = findMethod(mapper, UPDATE_BY_PRIMARYKEY_SELECTIVE_METHOD_NAME,
    445                     record);
    446             logger.debug("method  found in " + mapper.getClass());
    447 
    448             if (updateByExampleSelectiveMethod == null) {
    449                 logger.warn("updateByExampleSelectiveMethod faild,the method dose not exits !");
    450                 return -1;
    451             }
    452 
    453             Object value = updateByExampleSelectiveMethod.invoke(mapper, record);
    454             logger.info("updateByExampleSelectiveMethod success,the return value is: " + value);
    455             return (int) value;
    456         } catch (Exception e) {
    457             logger.error("updateByExampleSelectiveMethod faild," + e.getMessage());
    458         }
    459         return -1;
    460     }
    461 
    462     /**
    463      * 代理方法
    464      * 
    465      * @param record
    466      * @return
    467      */
    468     public int updateByPrimaryKey(Object record) {
    469 
    470         try {
    471             if (record == null) {
    472                 logger.warn("updateByPrimaryKey faild,the object can not be null !");
    473                 return -1;
    474             }
    475 
    476             Object mapper = findMapper(record);
    477             logger.debug("mapper instance found for " + mapper.getClass());
    478 
    479             Method updateByExampleSelectiveMethod = findMethod(mapper, UPDATE_BY_PRIMARYKEY_METHOD_NAME, record);
    480             logger.debug("method  found in " + mapper.getClass());
    481 
    482             if (updateByExampleSelectiveMethod == null) {
    483                 logger.warn("updateByPrimaryKey faild,the method dose not exits !");
    484                 return -1;
    485             }
    486 
    487             Object value = updateByExampleSelectiveMethod.invoke(mapper, record);
    488             logger.info("updateByPrimaryKey success,the return value is: " + value);
    489             return (int) value;
    490         } catch (Exception e) {
    491             logger.error("updateByPrimaryKey faild," + e.getMessage());
    492         }
    493         return -1;
    494     }
    495 
    496     public List<Map<String,Object>> selectExportData(String sql,Object...param){
    497         if (StringUtils.isNotBlank(sql)) {
    498             return null;
    499         }
    500         JdbcTemplate template = ctx.getBean(org.springframework.jdbc.core.JdbcTemplate.class);
    501         try {
    502             return template.queryForList(sql, param);
    503         } catch (Exception e) {
    504             e.printStackTrace();
    505         }
    506         return null;
    507     }
    508     
    509     @Override
    510     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    511         ctx = applicationContext;
    512     }
    513 
    514 }
    View Code

    5.EasyUiResult

     1 package com.*.pojo.vo;
     2 
     3 import java.io.Serializable;
     4 import java.util.ArrayList;
     5 import java.util.List;
     6 
     7 /**
     8  * 返回最终结果的包装类
     9  */
    10 public class EasyUIResult<T> implements Serializable {
    11 
    12     /**
    13      * 默认构造函数
    14      */
    15     public EasyUIResult() {
    16 
    17     }
    18 
    19     /**
    20      * 构造函数
    21      *
    22      * @param total
    23      * @param rows
    24      */
    25     public EasyUIResult(long total, List<T> rows) {
    26         this.total = total;
    27         this.rows = rows;
    28     }
    29 
    30     /**
    31      * 总共多少条记录
    32      */
    33     private long total;
    34     /**
    35      * 当前页的记录
    36      */
    37     private List<T> rows;
    38 
    39 
    40     public long getTotal() {
    41         return total;
    42     }
    43 
    44     public void setTotal(long total) {
    45         this.total = total;
    46     }
    47 
    48     public List<T> getRows() {
    49         return rows;
    50     }
    51 
    52     public void setRows(List<T> rows) {
    53         if (rows == null) {
    54             rows = new ArrayList<T>();
    55         }
    56         this.rows = rows;
    57     }
    58 }
    View Code

    6.spring-mvc.xml

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <beans xmlns="http://www.springframework.org/schema/beans"
      3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      4        xmlns:context="http://www.springframework.org/schema/context"
      5        xmlns:mvc="http://www.springframework.org/schema/mvc"
      6        xsi:schemaLocation="http://www.springframework.org/schema/beans
      7                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      8                            http://www.springframework.org/schema/context
      9                            http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     10 
     11 
     12     <mvc:annotation-driven/>
     13     <!--扫描Controller-->
     14     <context:component-scan base-package="com.*.uomp.base.action">
     15         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     16     </context:component-scan>
     17     <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
     18         <property name="converters">
     19             <set>
     20                 <!-- 此处可以定义多种转换类型 -->
     21                 <bean class="com.xwtec.converter.DateConverter"/>
     22             </set>
     23         </property>
     24     </bean>
     25     <context:component-scan base-package="com.xwtec.web.controller"/>
     26     <!--定义注解驱动-->
     27     <mvc:annotation-driven conversion-service="conversionService">
     28         <!--enableMatrixVariables="true">-->
     29         <mvc:message-converters register-defaults="true">
     30             <!-- StringHttpMessageConverter编码为UTF-8,防止乱码 -->
     31             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
     32                 <constructor-arg value="UTF-8"/>
     33                 <property name="supportedMediaTypes">
     34                     <list>
     35                         <bean class="org.springframework.http.MediaType">
     36                             <constructor-arg index="0" value="text"/>
     37                             <constructor-arg index="1" value="html"/>
     38                             <constructor-arg index="2" value="UTF-8"/>
     39                         </bean>
     40                         <bean class="org.springframework.http.MediaType">
     41                             <constructor-arg index="0" value="*"/>
     42                             <constructor-arg index="1" value="*"/>
     43                             <constructor-arg index="2" value="UTF-8"/>
     44                         </bean>
     45                     </list>
     46                 </property>
     47             </bean>
     48 
     49             <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
     50             <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"
     51                   id="fastJsonHttpMessageConverter">
     52                 <property name="supportedMediaTypes">
     53                     <list>
     54                         <value>text/html;charset=UTF-8</value>
     55                         <value>text/json;charset=UTF-8</value>
     56                         <value>application/json;charset=UTF-8</value>
     57                     </list>
     58                 </property>
     59                 <!--序列化选项-->
     60                 <property name="fastJsonConfig">
     61                     <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
     62                         <property name="serializerFeatures">
     63                             <list>
     64                                 <!-- 输出key时是否使用双引号 -->
     65                                 <value>QuoteFieldNames</value>
     66                                 <!-- 是否输出值为null的字段 -->
     67                                 <value>WriteMapNullValue</value>
     68                                 <!-- 数值字段如果为null,输出为0,而非null -->
     69                                 <value>WriteNullNumberAsZero</value>
     70                                 <!-- List字段如果为null,输出为[],而非null -->
     71                                 <value>WriteNullListAsEmpty</value>
     72                                 <!-- 字符类型字段如果为null,输出为"",而非null -->
     73                                 <value>WriteNullStringAsEmpty</value>
     74                                 <!-- Boolean字段如果为null,输出为false,而非null -->
     75                                 <value>WriteNullBooleanAsFalse</value>
     76                                 <!-- null String不输出  -->
     77                                 <value>WriteNullStringAsEmpty</value>
     78                                 <!-- null String也要输出  -->
     79                                 <value>WriteMapNullValue</value>
     80                                 <!-- Date的日期转换器 -->
     81                                 <value>WriteDateUseDateFormat</value>
     82                             </list>
     83                         </property>
     84                     </bean>
     85                 </property>
     86             </bean>
     87         </mvc:message-converters>
     88     </mvc:annotation-driven>
     89     <!--定义视图解析器-->
     90     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     91         <property name="prefix" value="/WEB-INF/views/"/>
     92         <property name="suffix" value=".jsp"/>
     93     </bean>
     94     <!--图片上传解析-->
     95     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     96         <!--设置最大的文件大小-->
     97         <property name="maxUploadSize" value="52428800"/>
     98         <!--编码-->
     99         <property name="defaultEncoding" value="UTF-8"/>
    100     </bean>
    101 
    102     <!--配置拦截器-->
    103     <mvc:interceptors>
    104         <mvc:interceptor>
    105             <!--拦截所有main路径以及子路径-->
    106             <mvc:mapping path="/manage/**"/>
    107             <bean class="com.xwtec.web.handerinterceptor.UserLoginHandlerInterceptor"/>
    108         </mvc:interceptor>
    109     </mvc:interceptors>
    110 </beans>
    View Code

    7.easui示例页面

      1 <!DOCTYPE HTML>
      2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
      3 <%@ page language="java" pageEncoding="UTF-8" isELIgnored="false"%>
      4 <html>
      5 <head>
      6 <title>活动信息管理</title>
      7 <jsp:include page="/taglibs.jsp"></jsp:include>
      8  <script>
      9         var contextPath = '${pageContext.request.contextPath}';
     10         var base_url=contextPath+'/rest/manage/act/list/actInfo';
     11         var citymap={};
     12         citymap['A']='郑州';
     13         citymap['B']='开封';
     14         citymap['C']='洛阳';
     15         citymap['D']='平顶山';
     16         citymap['E']='安阳';
     17         citymap['F']='鹤壁';
     18         citymap['G']='新乡';
     19         citymap['H']='焦作';
     20         citymap['J']='濮阳';
     21         citymap['K']='许昌';
     22         citymap['L']='漯河';
     23         citymap['M']='三门峡';
     24         citymap['N']='商丘';
     25         citymap['O']='周口';
     26         citymap['P']='驻马店';
     27         citymap['Q']='南阳';
     28         citymap['R']='信阳';
     29         citymap['U']='济源';
     30         
     31         $(document).on('click','#showCity',function (e){
     32             var tmp=$(e.target).attr('value');
     33             layer.open({
     34                 type: 1,
     35                 shadeClose:true,
     36                 skin: 'layui-layer-rim', //加上边框
     37                 area: ['420px', '240px'], //宽高
     38                 content:tmp
     39               });
     40         })
     41        
     42         function loadData(query_url){
     43             $('#data_grid').datagrid({
     44                 title: '已上线活动列表',
     45                 fitColumns: true,//不指定高度或宽度,则自适应
     46                 nowrap: true,
     47                 striped: true,//设置为true将交替显示行背景
     48                 autoRowHeight: true,
     49                 collapsible: true,
     50                 method: 'get',
     51                 url:query_url,//一个用以从远程站点请求数据的超链接地址
     52                 sortName: 'createTime',//默认排序列名
     53                 sortOrder: 'desc',//默认字段排序方式
     54                 remoteSort: true,//是否通过远程服务器对数据排序
     55                 singleSelect: false,//设置为true将只允许选择一行
     56                 idField: 'id',//表明该列是一个唯一列
     57                 columns: [
     58                     [
     59                         {field: 'ck', checkbox: true},
     60                         {field: 'id', hidden: true},
     61                         {field: 'activityId',40, title: '活动id', align: 'center', halign: 'center', sortable: true},
     62                         {field: 'activityName', 80,title: '活动名称', align: 'center', halign: 'center', sortable: true},
     63                         {field: 'startTime', 60, title: '开始时间', align: 'center', halign: 'center', sortable: true},
     64                         {field: 'endTime',  60,title: '结束时间', align: 'center', halign: 'center', sortable: true},
     65                         {field: 'createTime', 60, title: '上线时间', align: 'center', halign: 'center', sortable: true},
     66                         {
     67                             field: 'cityCode',  130,title: '地市', align: 'center', halign: 'center', sortable: true,formatter: function (value, row, index) {
     68                                 if (!isNullOrUndefined(value)) {
     69                                     if(value.indexOf('0')>-1){return "全省";}
     70                                     else{
     71                                         var arr=value.split(',');
     72                                         var tmp='';
     73                                         
     74                                         for(var t in arr){
     75                                             if(!citymap[arr[t]])
     76                                                 continue;
     77                                             tmp+=citymap[arr[t]]
     78                                             if(t!=arr.length-1)
     79                                                 tmp+=',';
     80                                         }
     81                                         if(arr.length>8){return '<span id="showCity" value="'+tmp+'">地市过多,点击查看<span>'};
     82                                         return tmp;
     83                                     }
     84                                 }
     85                                 return value;
     86                             }
     87                         }
     88                     ]
     89                 ],
     90                 pagination: true,//设置true将在数据表格底部显示分页工具栏
     91                 rownumbers: true,//设置为true将显示行数
     92                 pageSize: 10,//分页大小
     93                 pageList: [10, 50, 100],//每页的个数
     94                 toolbar: '#jform_contactListtb',//工具栏、菜单栏
     95                 onLoadSuccess: function (data) {
     96                     $('#data_grid').datagrid('clearSelections');
     97                     $('#activityName').combobox({
     98                          valueField : 'id',  
     99                          textField : 'activityName',  
    100                          editable : true,  
    101                          required : true,  
    102                          mode : 'local',  
    103                          data: data.rows  
    104                     });
    105                 }
    106             });
    107         }
    108         $(function () {
    109             loadData(base_url);
    110         });
    111 
    112 
    113         /**
    114          * 查询
    115          */
    116         function query() {
    117                 
    118                 var name=$('#activityName').combobox('getText');
    119                 console.log(name);
    120                 var city=$('#cityCode').val();
    121                 console.log(city);
    122                 var time= $('#createTime').datebox('getValue');
    123                 console.log(time);
    124                 var queryUrl=base_url+'?query=true';
    125                 
    126                 if(name&&name!=''){
    127                     queryUrl+='&activityName='+name.trim();
    128                 }
    129                 if(city&&city!=''){
    130                     queryUrl+='&cityCode='+city.trim();        
    131                 }
    132                 if(time&&time!=''){
    133                     queryUrl+='&createTime='+time.trim();
    134                 }
    135                 loadData(queryUrl);
    136         }
    137 
    138 
    139         /**
    140          * 删除
    141          */
    142         function del() {
    143             var selRows = $('#data_grid').datagrid('getChecked');
    144             if (selRows.length <= 0) {
    145                 layer.msg('请至少选择一行进行操作', {time: 1000});
    146                 return;
    147             }
    148             layer.confirm('确定要进行删除吗?', {
    149                 btn: ['确定', '取消'] //按钮
    150             }, function () {
    151                 var ids = [];
    152                 $.each(selRows, function (i, v) {
    153                     ids.push(v.id);
    154                 });
    155                 $.post(contextPath+'/rest/manage/act/del/actInfo?ids=' + ids.toString(), function (data) {
    156                     layer.msg(data.msg, {time: 2000});
    157                     $('#data_grid').datagrid('load');
    158                     $('#data_grid').datagrid('clearSelections');
    159                 }, 'json');
    160             });
    161 
    162         }
    163 
    164 
    165         /**
    166          * 用户弹窗
    167          */
    168         function oper(oper) {
    169             if ('add' == oper) {
    170                 $('#form_tag').dialog('setTitle', '新增活动');
    171                 $('#addTag_form').form('clear');
    172                 $('#saveBtn').attr('onclick', "doAdd()");
    173                 $('#channel').combobox('setValue', 0);
    174                 $('#state1').prop('checked', 'checked');
    175                 $('#isLogin1').prop('checked', 'checked');
    176                 $('#imgUrl').hide();
    177                 //新增校验
    178                 $('#img_file').filebox('enableValidation');
    179             } else {
    180                 //清空图片框里面的值
    181                 $('#img_file').filebox('clear');
    182                 //修改不校验图片必填
    183                 $('#img_file').filebox('disableValidation');
    184                 var selRows = $('#data_grid').datagrid('getChecked');
    185                 if (selRows.length != 1) {
    186                     layer.msg('请选择一行进行修改', {time: 1000});
    187                     return;
    188                 }
    189                 var rowsId = selRows[0].id;
    190                 $('#form_tag').dialog('setTitle', '修改活动');
    191                 $('#saveBtn').attr('onclick', "doAdd('edit')");
    192                 $('#addTag_form').form('load', selRows[0]);
    193                 //图片
    194                 $('#imgUrl').show().attr('src', selRows[0].imgUrl);
    195             }
    196             $('#form_tag').dialog('open');
    197         }
    198 
    199         /**
    200          * 保存
    201          */
    202         function doAdd(oper) {
    203             var url = contextPath+'/rest/manage/act/save/actInfo';
    204 
    205             $('#addTag_form').form('submit', {
    206                 url: url,
    207 
    208                 onSubmit: function (param) {
    209                     return $('#addTag_form').form('validate');
    210                 },
    211                 success: function (data) {
    212                     $('#form_tag').dialog('close');
    213                     var resMsg = $.parseJSON(data);
    214                     layer.msg(resMsg.msg, {time: 2000});
    215                     $('#data_grid').datagrid('load');
    216                     $('#data_grid').datagrid('clearSelections');
    217                     location.reload( true );
    218                     loadData(base_url);
    219                 }
    220             });
    221         }
    222 
    223         function refrash(){
    224             location.reload( true );
    225             loadData(base_url);
    226         }
    227     </script>
    228 </head>
    229 
    230 <body>
    231 
    232 <!--数据表格-->
    233 <table id="data_grid"></table>
    234 
    235 <!--grid 工具栏构建-->
    236 <div id="jform_contactListtb" style="padding:3px; height: auto">
    237     <form id="search_form" enctype="multipart/form-data">
    238         <div name="searchColums" class="table-container">
    239             <!--查询条件-->
    240             <table class="editTab">
    241                 <tr>
    242                     <th>活动上线时间:</th>
    243                     <td>
    244                         <input type="text" name="createTime" id="createTime" class="easyui-datebox"/>
    245                     </td>
    246 
    247 <!--                     <th>活动开始时间:</th>
    248                     <td>
    249                         <input type="text" name="qStartTime" id="qStartTime" class="easyui-datebox"/>
    250                     </td>
    251 
    252                     <th>活动结束时间:</th>
    253                     <td>
    254                         <input type="text" name="qEndTime" id="qEndTime" class="easyui-datebox"/>
    255                     </td>
    256  -->
    257                     <th>活动名称:</th>
    258                     <td>
    259                         <select style="80px;" name="activityName" id="activityName" class="easyui-combobox"
    260                                 data-options="editable:false,multiple:false">
    261                             <option value="">全部</option>
    262                         </select>
    263                     </td>
    264 
    265                     <th>地市:</th>
    266                     <td>
    267                         <select style="80px;" name="cityCode" id="cityCode">
    268                             <option value="0">全省</option>
    269                             <option value="A">A 郑州</option>
    270                             <option value="B">B 开封</option>
    271                             <option value="C">C 洛阳</option>
    272                             <option value="D">D 平顶山</option>
    273                             <option value="E">E 安阳</option>
    274                             <option value="F">F 鹤壁</option>
    275                             <option value="G">G 新乡</option>
    276                             <option value="H">H 焦作</option>
    277                             <option value="J">J 濮阳</option>
    278                             <option value="K">K 许昌</option>
    279                             <option value="L">L 漯河</option>
    280                             <option value="M">M 三门峡</option>
    281                             <option value="N">N 商丘</option>
    282                             <option value="P">P 周口</option>
    283                             <option value="Q">Q 驻马店</option>
    284                             <option value="R">R 南阳</option>
    285                             <option value="S">S 信阳</option>
    286                             <option value="U">U 济源</option>
    287                         </select>
    288                     </td>
    289                 </tr>
    290             </table>
    291             <!--操作按钮-->
    292             <div style="height:auto; 100%;" class="datagrid-toolbar">
    293                 <div style="float:left;line-height:40px;padding-top:5px;">
    294                     <input type="button" value="新增" class="btn btn-sm btn-success" onclick="oper('add')"/>
    295                     <input type="button" value="修改" class="btn btn-sm btn-warning" onclick="oper('edit')"/>
    296                     <input type="button" value="删除" class="btn btn-sm btn-danger" onclick="del()"/>
    297                     <input type="button" value="刷新" class="btn btn-sm btn-primary" onclick="refrash()"/>
    298                 </div>
    299                 <div style="float:right;line-height:40px;padding-top:5px;">
    300                     <input type="button" value="查询" class="btn btn-sm btn-success" onclick="query();"/>
    301                     <input type="button" value="重置" class="btn btn-sm btn-info" onclick="$('#search_form').form('clear');$('#qChannel').combobox('setValue',0);$('#qTagId').combobox('setValue','');$('#qState').combobox('setValue','')"/>
    302                 </div>
    303             </div>
    304         </div>
    305     </form>
    306 </div>
    307 
    308 
    309 <!--列表新增弹窗-->
    310 <div id="form_tag" class="easyui-dialog" title="新增热销服务列表" style="300px;height:auto;display:none;"
    311      data-options="resizable:true,modal:true,closed:true,buttons:'#bb'">
    312     <form method="post" id="addTag_form" enctype="multipart/form-data">
    313         <input type="hidden" id="id" name="id"/>
    314         <table class="editTab">
    315             <tr>
    316                 <th width="20%"><span style="color:red;">*</span>活动id:</th>
    317                 <td width="70%">
    318                     <input type="text" name="activityId" id="title"  style="100%;" class="easyui-textbox" data-options="required:true">
    319                 </td>
    320             </tr>
    321 
    322             <tr>
    323                 <th><span style="color:red;">*</span>活动名称:</th>
    324                 <td>
    325                     <input type="text" name="activityName" id="title" style="100%;" class="easyui-textbox" data-options="required:true">
    326                 </td>
    327             </tr>
    328 
    329             <tr>
    330                 <th>
    331                     地市:
    332                 </th>
    333                            <td>
    334                         <select class="easyui-combobox" data-options="multiple:true" style="100%;" name="cityCode">
    335                             <option value="0">全省</option>
    336                             <option value="A">A 郑州</option>
    337                             <option value="B">B 开封</option>
    338                             <option value="C">C 洛阳</option>
    339                             <option value="D">D 平顶山</option>
    340                             <option value="E">E 安阳</option>
    341                             <option value="F">F 鹤壁</option>
    342                             <option value="G">G 新乡</option>
    343                             <option value="H">H 焦作</option>
    344                             <option value="J">J 濮阳</option>
    345                             <option value="K">K 许昌</option>
    346                             <option value="L">L 漯河</option>
    347                             <option value="M">M 三门峡</option>
    348                             <option value="N">N 商丘</option>
    349                             <option value="P">P 周口</option>
    350                             <option value="Q">Q 驻马店</option>
    351                             <option value="R">R 南阳</option>
    352                             <option value="S">S 信阳</option>
    353                             <option value="U">U 济源</option>
    354                         </select>
    355                     </td>
    356             </tr>
    357             <tr>
    358                 <th>
    359                    活动开始时间:
    360                 </th>
    361                 <td>
    362                     <input type="text" name="startTime" id="startTime" class="easyui-datebox"/>
    363                 </td>
    364             </tr>
    365                 <th>
    366                     活动结束时间:
    367                 </th>
    368                 <td>
    369                     <input type="text" name="endTime" id="endTime" class="easyui-datebox"/>
    370                 </td>
    371             </tr>
    372             
    373             <th>
    374                     活动上线时间:
    375                 </th>
    376                 <td>
    377                     <input type="text" name="createTime" id="createTime" class="easyui-datetimebox"/>
    378                 </td>
    379             </tr>
    380 
    381         </table>
    382     </form>
    383 </div>
    384 
    385 <!--dialog 按钮-->
    386 <div id="bb" style="display: none;">
    387     <button type="button" id="saveBtn" class="btn btn-success btn-sm" onclick="doAdd('add');">保存</button>
    388     <button type="button" class="btn btn-warning btn-sm" onclick="$('#form_tag').dialog('close');">取消</button>
    389 </div>
    390 
    391 
    392 </body>
    393 </html>
    View Code

    流程说明:需要新增一个功能,先设计好表,然后生成mapper和xml以及实体类,其次,在Service里面的BeanNameMap放一下,其次复制页面到需要的目录去,然后,参照实体类更改datagrid相应字段以及form字段,修改下页面地址的最后一个名字为实体类的名字驼峰写法。

    约束:表字段建议最多两个单词,如果是图片,那么建议以img_*存储字段

    功能说明:自动根据url的name封装成对应的实体类,如果上传图片了,那么自动保存到一个图片字段里,自动判断是保存还是修改操作,最后几乎不写代码实现一个功能模块的添加

  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/swtjavaspace/p/6251930.html
Copyright © 2011-2022 走看看