cgform_controllerTemplate.ftl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <#if packageStyle == "service">
  2. package ${bussiPackage}.${entityPackage}.controller;
  3. import ${bussiPackage}.${entityPackage}.entity.${entityName}Entity;
  4. import ${bussiPackage}.${entityPackage}.service.${entityName}ServiceI;
  5. <#else>
  6. package ${bussiPackage}.controller.${entityPackage};
  7. import ${bussiPackage}.entity.${entityPackage}.${entityName}Entity;
  8. import ${bussiPackage}.service.${entityPackage}.${entityName}ServiceI;
  9. </#if>
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.text.SimpleDateFormat;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import org.apache.log4j.Logger;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.stereotype.Controller;
  18. import org.springframework.ui.ModelMap;
  19. import org.springframework.web.bind.annotation.RequestMapping;
  20. import org.springframework.web.bind.annotation.ResponseBody;
  21. import org.springframework.web.servlet.ModelAndView;
  22. import org.jeecgframework.core.common.controller.BaseController;
  23. import org.jeecgframework.core.common.exception.BusinessException;
  24. import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
  25. import org.jeecgframework.core.common.model.common.TreeChildCount;
  26. import org.jeecgframework.core.common.model.json.AjaxJson;
  27. import org.jeecgframework.core.common.model.json.DataGrid;
  28. import org.jeecgframework.core.constant.Globals;
  29. import org.jeecgframework.core.util.StringUtil;
  30. import org.jeecgframework.tag.core.easyui.TagUtil;
  31. import org.jeecgframework.web.system.pojo.base.TSDepart;
  32. import org.jeecgframework.web.system.service.SystemService;
  33. import org.jeecgframework.core.util.MyBeanUtils;
  34. import java.io.OutputStream;
  35. import org.jeecgframework.core.util.BrowserUtils;
  36. import org.jeecgframework.poi.excel.ExcelExportUtil;
  37. import org.jeecgframework.poi.excel.ExcelImportUtil;
  38. import org.jeecgframework.poi.excel.entity.ExportParams;
  39. import org.jeecgframework.poi.excel.entity.ImportParams;
  40. import org.jeecgframework.poi.excel.entity.TemplateExportParams;
  41. import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
  42. import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
  43. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  44. import org.jeecgframework.core.util.ResourceUtil;
  45. import java.io.IOException;
  46. import org.springframework.web.bind.annotation.RequestMethod;
  47. import org.springframework.web.multipart.MultipartFile;
  48. import org.springframework.web.multipart.MultipartHttpServletRequest;
  49. import java.util.Map;
  50. import java.util.HashMap;
  51. import org.jeecgframework.core.util.ExceptionUtil;
  52. <#-- restful 通用方法生成 -->
  53. import org.springframework.http.ResponseEntity;
  54. import org.springframework.stereotype.Controller;
  55. import org.springframework.web.bind.annotation.PathVariable;
  56. import org.springframework.web.bind.annotation.RequestBody;
  57. import org.springframework.web.bind.annotation.RequestMapping;
  58. import org.springframework.web.bind.annotation.RequestMethod;
  59. import org.springframework.web.bind.annotation.ResponseBody;
  60. import org.springframework.web.bind.annotation.ResponseStatus;
  61. import org.springframework.http.HttpHeaders;
  62. import org.springframework.http.HttpStatus;
  63. import org.jeecgframework.core.beanvalidator.BeanValidators;
  64. import java.util.Set;
  65. import javax.validation.ConstraintViolation;
  66. import javax.validation.Validator;
  67. import java.net.URI;
  68. import org.springframework.http.MediaType;
  69. import org.springframework.web.util.UriComponentsBuilder;
  70. <#-- restful 通用方法生成 -->
  71. <#-- 列为文件类型的文件代码生成 -->
  72. <#assign fileFlag = false />
  73. <#list columns as filePo>
  74. <#if filePo.showType=='file'>
  75. <#assign fileFlag = true />
  76. </#if>
  77. </#list>
  78. <#if fileFlag==true>
  79. import org.jeecgframework.web.cgform.entity.upload.CgUploadEntity;
  80. import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI;
  81. import java.util.HashMap;
  82. </#if>
  83. <#-- 列为文件类型的文件代码生成 -->
  84. /**
  85. * @Title: Controller
  86. * @Description: ${ftl_description}
  87. * @author onlineGenerator
  88. * @date ${ftl_create_time}
  89. * @version V1.0
  90. *
  91. */
  92. @Controller
  93. @RequestMapping("/${entityName?uncap_first}Controller")
  94. public class ${entityName}Controller extends BaseController {
  95. /**
  96. * Logger for this class
  97. */
  98. private static final Logger logger = Logger.getLogger(${entityName}Controller.class);
  99. @Autowired
  100. private ${entityName}ServiceI ${entityName?uncap_first}Service;
  101. @Autowired
  102. private SystemService systemService;
  103. <#-- restful 通用方法生成 -->
  104. @Autowired
  105. private Validator validator;
  106. <#-- restful 通用方法生成 -->
  107. <#-- 列为文件类型的文件代码生成 -->
  108. <#if fileFlag==true>
  109. @Autowired
  110. private CgFormFieldServiceI cgFormFieldService;
  111. </#if>
  112. <#-- 列为文件类型的文件代码生成 -->
  113. /**
  114. * ${ftl_description}列表 页面跳转
  115. *
  116. * @return
  117. */
  118. @RequestMapping(params = "list")
  119. public ModelAndView list(HttpServletRequest request) {
  120. return new ModelAndView("${bussiPackage?replace(".","/")}/${entityPackage}/${entityName?uncap_first}List");
  121. }
  122. /**
  123. * easyui AJAX请求数据
  124. *
  125. * @param request
  126. * @param response
  127. * @param dataGrid
  128. * @param user
  129. */
  130. @RequestMapping(params = "datagrid")
  131. public void datagrid(${entityName}Entity ${entityName?uncap_first},HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
  132. CriteriaQuery cq = new CriteriaQuery(${entityName}Entity.class, dataGrid);
  133. <#if cgformConfig.cgFormHead.isTree == 'Y'>
  134. if(StringUtil.isEmpty(${entityName?uncap_first}.getId())){
  135. cq.isNull("${cgformConfig.cgFormHead.treeParentIdFieldNamePage}");
  136. }else{
  137. cq.eq("${cgformConfig.cgFormHead.treeParentIdFieldNamePage}", ${entityName?uncap_first}.getId());
  138. ${entityName?uncap_first}.setId(null);
  139. }
  140. </#if>
  141. //查询条件组装器
  142. org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ${entityName?uncap_first}, request.getParameterMap());
  143. try{
  144. //自定义追加查询条件
  145. <#list columns as po>
  146. <#if po.isQuery =='Y' && po.queryMode =='group'>
  147. String query_${po.fieldName}_begin = request.getParameter("${po.fieldName}_begin");
  148. String query_${po.fieldName}_end = request.getParameter("${po.fieldName}_end");
  149. if(StringUtil.isNotEmpty(query_${po.fieldName}_begin)){
  150. <#if po.type == "java.util.Date">
  151. cq.ge("${po.fieldName}", new SimpleDateFormat("yyyy-MM-dd").parse(query_${po.fieldName}_begin));
  152. <#else>
  153. cq.ge("${po.fieldName}", Integer.parseInt(query_${po.fieldName}_begin));
  154. </#if>
  155. }
  156. if(StringUtil.isNotEmpty(query_${po.fieldName}_end)){
  157. <#if po.type == "java.util.Date">
  158. cq.le("${po.fieldName}", new SimpleDateFormat("yyyy-MM-dd").parse(query_${po.fieldName}_end));
  159. <#else>
  160. cq.le("${po.fieldName}", Integer.parseInt(query_${po.fieldName}_end));
  161. </#if>
  162. }
  163. </#if>
  164. </#list>
  165. }catch (Exception e) {
  166. throw new BusinessException(e.getMessage());
  167. }
  168. cq.add();
  169. this.${entityName?uncap_first}Service.getDataGridReturn(cq, true);
  170. <#if cgformConfig.cgFormHead.isTree == 'Y'>
  171. TagUtil.treegrid(response, dataGrid);
  172. <#else>
  173. TagUtil.datagrid(response, dataGrid);
  174. </#if>
  175. }
  176. /**
  177. * 删除${ftl_description}
  178. *
  179. * @return
  180. */
  181. @RequestMapping(params = "doDel")
  182. @ResponseBody
  183. public AjaxJson doDel(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest request) {
  184. String message = null;
  185. AjaxJson j = new AjaxJson();
  186. ${entityName?uncap_first} = systemService.getEntity(${entityName}Entity.class, ${entityName?uncap_first}.getId());
  187. message = "${ftl_description}删除成功";
  188. try{
  189. ${entityName?uncap_first}Service.delete(${entityName?uncap_first});
  190. systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
  191. }catch(Exception e){
  192. e.printStackTrace();
  193. message = "${ftl_description}删除失败";
  194. throw new BusinessException(e.getMessage());
  195. }
  196. j.setMsg(message);
  197. return j;
  198. }
  199. /**
  200. * 批量删除${ftl_description}
  201. *
  202. * @return
  203. */
  204. @RequestMapping(params = "doBatchDel")
  205. @ResponseBody
  206. public AjaxJson doBatchDel(String ids,HttpServletRequest request){
  207. String message = null;
  208. AjaxJson j = new AjaxJson();
  209. message = "${ftl_description}删除成功";
  210. try{
  211. for(String id:ids.split(",")){
  212. ${entityName}Entity ${entityName?uncap_first} = systemService.getEntity(${entityName}Entity.class,
  213. <#if cgformConfig.cgFormHead.jformPkType?if_exists?html == "UUID">
  214. id
  215. <#elseif cgformConfig.cgFormHead.jformPkType?if_exists?html == "NATIVE">
  216. Integer.parseInt(id)
  217. <#elseif cgformConfig.cgFormHead.jformPkType?if_exists?html == "SEQUENCE">
  218. Integer.parseInt(id)
  219. <#else>
  220. id
  221. </#if>
  222. );
  223. ${entityName?uncap_first}Service.delete(${entityName?uncap_first});
  224. systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
  225. }
  226. }catch(Exception e){
  227. e.printStackTrace();
  228. message = "${ftl_description}删除失败";
  229. throw new BusinessException(e.getMessage());
  230. }
  231. j.setMsg(message);
  232. return j;
  233. }
  234. /**
  235. * 添加${ftl_description}
  236. *
  237. * @param ids
  238. * @return
  239. */
  240. @RequestMapping(params = "doAdd")
  241. @ResponseBody
  242. public AjaxJson doAdd(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest request) {
  243. String message = null;
  244. AjaxJson j = new AjaxJson();
  245. message = "${ftl_description}添加成功";
  246. try{
  247. <#if cgformConfig.cgFormHead.isTree == 'Y'>
  248. if(StringUtil.isEmpty(${entityName?uncap_first}.get${cgformConfig.cgFormHead.treeParentIdFieldNamePage?cap_first}())){
  249. ${entityName?uncap_first}.set${cgformConfig.cgFormHead.treeParentIdFieldNamePage?cap_first}(null);
  250. }
  251. </#if>
  252. ${entityName?uncap_first}Service.save(${entityName?uncap_first});
  253. systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
  254. }catch(Exception e){
  255. e.printStackTrace();
  256. message = "${ftl_description}添加失败";
  257. throw new BusinessException(e.getMessage());
  258. }
  259. j.setMsg(message);
  260. <#-- 列为文件类型的文件代码生成 -->
  261. <#if fileFlag==true>
  262. j.setObj(${entityName?uncap_first});
  263. </#if>
  264. <#-- 列为文件类型的文件代码生成 -->
  265. return j;
  266. }
  267. /**
  268. * 更新${ftl_description}
  269. *
  270. * @param ids
  271. * @return
  272. */
  273. @RequestMapping(params = "doUpdate")
  274. @ResponseBody
  275. public AjaxJson doUpdate(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest request) {
  276. String message = null;
  277. AjaxJson j = new AjaxJson();
  278. message = "${ftl_description}更新成功";
  279. ${entityName}Entity t = ${entityName?uncap_first}Service.get(${entityName}Entity.class, ${entityName?uncap_first}.getId());
  280. try {
  281. MyBeanUtils.copyBeanNotNull2Bean(${entityName?uncap_first}, t);
  282. <#if cgformConfig.cgFormHead.isTree == 'Y'>
  283. if(StringUtil.isEmpty(t.get${cgformConfig.cgFormHead.treeParentIdFieldNamePage?cap_first}())){
  284. t.set${cgformConfig.cgFormHead.treeParentIdFieldNamePage?cap_first}(null);
  285. }
  286. </#if>
  287. ${entityName?uncap_first}Service.saveOrUpdate(t);
  288. systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
  289. } catch (Exception e) {
  290. e.printStackTrace();
  291. message = "${ftl_description}更新失败";
  292. throw new BusinessException(e.getMessage());
  293. }
  294. j.setMsg(message);
  295. return j;
  296. }
  297. <#list buttons as btn>
  298. <#if btn.optType=='action'>
  299. /**
  300. * 自定义按钮-[${btn.buttonName}]业务
  301. * @param ids
  302. * @return
  303. */
  304. @RequestMapping(params = "do${btn.buttonCode?cap_first}")
  305. @ResponseBody
  306. public AjaxJson do${btn.buttonCode?cap_first}(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest request) {
  307. String message = null;
  308. AjaxJson j = new AjaxJson();
  309. message = "${btn.buttonName}成功";
  310. ${entityName}Entity t = ${entityName?uncap_first}Service.get(${entityName}Entity.class, ${entityName?uncap_first}.getId());
  311. try{
  312. ${entityName?uncap_first}Service.do${btn.buttonCode?cap_first}Bus(t);
  313. systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
  314. }catch(Exception e){
  315. e.printStackTrace();
  316. message = "${btn.buttonName}失败";
  317. }
  318. j.setMsg(message);
  319. return j;
  320. }
  321. </#if>
  322. </#list>
  323. /**
  324. * ${ftl_description}新增页面跳转
  325. *
  326. * @return
  327. */
  328. @RequestMapping(params = "goAdd")
  329. public ModelAndView goAdd(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest req) {
  330. if (StringUtil.isNotEmpty(${entityName?uncap_first}.getId())) {
  331. ${entityName?uncap_first} = ${entityName?uncap_first}Service.getEntity(${entityName}Entity.class, ${entityName?uncap_first}.getId());
  332. req.setAttribute("${entityName?uncap_first}Page", ${entityName?uncap_first});
  333. }
  334. return new ModelAndView("${bussiPackage?replace(".","/")}/${entityPackage}/${entityName?uncap_first}-add");
  335. }
  336. /**
  337. * ${ftl_description}编辑页面跳转
  338. *
  339. * @return
  340. */
  341. @RequestMapping(params = "goUpdate")
  342. public ModelAndView goUpdate(${entityName}Entity ${entityName?uncap_first}, HttpServletRequest req) {
  343. if (StringUtil.isNotEmpty(${entityName?uncap_first}.getId())) {
  344. ${entityName?uncap_first} = ${entityName?uncap_first}Service.getEntity(${entityName}Entity.class, ${entityName?uncap_first}.getId());
  345. req.setAttribute("${entityName?uncap_first}Page", ${entityName?uncap_first});
  346. }
  347. return new ModelAndView("${bussiPackage?replace(".","/")}/${entityPackage}/${entityName?uncap_first}-update");
  348. }
  349. /**
  350. * 导入功能跳转
  351. *
  352. * @return
  353. */
  354. @RequestMapping(params = "upload")
  355. public ModelAndView upload(HttpServletRequest req) {
  356. req.setAttribute("controller_name","${entityName?uncap_first}Controller");
  357. return new ModelAndView("common/upload/pub_excel_upload");
  358. }
  359. /**
  360. * 导出excel
  361. *
  362. * @param request
  363. * @param response
  364. */
  365. @RequestMapping(params = "exportXls")
  366. public String exportXls(${entityName}Entity ${entityName?uncap_first},HttpServletRequest request,HttpServletResponse response
  367. , DataGrid dataGrid,ModelMap modelMap) {
  368. CriteriaQuery cq = new CriteriaQuery(${entityName}Entity.class, dataGrid);
  369. org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ${entityName?uncap_first}, request.getParameterMap());
  370. List<${entityName}Entity> ${entityName?uncap_first}s = this.${entityName?uncap_first}Service.getListByCriteriaQuery(cq,false);
  371. modelMap.put(NormalExcelConstants.FILE_NAME,"${ftl_description}");
  372. modelMap.put(NormalExcelConstants.CLASS,${entityName}Entity.class);
  373. modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("${ftl_description}列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
  374. "导出信息"));
  375. modelMap.put(NormalExcelConstants.DATA_LIST,${entityName?uncap_first}s);
  376. return NormalExcelConstants.JEECG_EXCEL_VIEW;
  377. }
  378. /**
  379. * 导出excel 使模板
  380. *
  381. * @param request
  382. * @param response
  383. */
  384. @RequestMapping(params = "exportXlsByT")
  385. public String exportXlsByT(${entityName}Entity ${entityName?uncap_first},HttpServletRequest request,HttpServletResponse response
  386. , DataGrid dataGrid,ModelMap modelMap) {
  387. modelMap.put(NormalExcelConstants.FILE_NAME,"${ftl_description}");
  388. modelMap.put(NormalExcelConstants.CLASS,${entityName}Entity.class);
  389. modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("${ftl_description}列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
  390. "导出信息"));
  391. modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
  392. return NormalExcelConstants.JEECG_EXCEL_VIEW;
  393. }
  394. @SuppressWarnings("unchecked")
  395. @RequestMapping(params = "importExcel", method = RequestMethod.POST)
  396. @ResponseBody
  397. public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
  398. AjaxJson j = new AjaxJson();
  399. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  400. Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  401. for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
  402. MultipartFile file = entity.getValue();// 获取上传文件对象
  403. ImportParams params = new ImportParams();
  404. params.setTitleRows(2);
  405. params.setHeadRows(1);
  406. params.setNeedSave(true);
  407. try {
  408. List<${entityName}Entity> list${entityName}Entitys = ExcelImportUtil.importExcel(file.getInputStream(),${entityName}Entity.class,params);
  409. for (${entityName}Entity ${entityName?uncap_first} : list${entityName}Entitys) {
  410. ${entityName?uncap_first}Service.save(${entityName?uncap_first});
  411. }
  412. j.setMsg("文件导入成功!");
  413. } catch (Exception e) {
  414. j.setMsg("文件导入失败!");
  415. logger.error(ExceptionUtil.getExceptionMessage(e));
  416. }finally{
  417. try {
  418. file.getInputStream().close();
  419. } catch (IOException e) {
  420. e.printStackTrace();
  421. }
  422. }
  423. }
  424. return j;
  425. }
  426. <#-- 列为文件类型的文件代码生成 -->
  427. <#if fileFlag==true>
  428. /**
  429. * 获取文件附件信息
  430. *
  431. * @param id ${entityName?uncap_first}主键id
  432. */
  433. @RequestMapping(params = "getFiles")
  434. @ResponseBody
  435. public AjaxJson getFiles(String id){
  436. List<CgUploadEntity> uploadBeans = cgFormFieldService.findByProperty(CgUploadEntity.class, "cgformId", id);
  437. List<Map<String,Object>> files = new ArrayList<Map<String,Object>>(0);
  438. for(CgUploadEntity b:uploadBeans){
  439. String title = b.getAttachmenttitle();//附件名
  440. String fileKey = b.getId();//附件主键
  441. String path = b.getRealpath();//附件路径
  442. String field = b.getCgformField();//表单中作为附件控件的字段
  443. Map<String, Object> file = new HashMap<String, Object>();
  444. file.put("title", title);
  445. file.put("fileKey", fileKey);
  446. file.put("path", path);
  447. file.put("field", field==null?"":field);
  448. files.add(file);
  449. }
  450. AjaxJson j = new AjaxJson();
  451. j.setObj(files);
  452. return j;
  453. }
  454. </#if>
  455. <#-- 列为文件类型的文件代码生成 -->
  456. <#-- restful 通用方法生成 -->
  457. @RequestMapping(method = RequestMethod.GET)
  458. @ResponseBody
  459. public List<${entityName}Entity> list() {
  460. List<${entityName}Entity> list${entityName}s=${entityName?uncap_first}Service.getList(${entityName}Entity.class);
  461. return list${entityName}s;
  462. }
  463. @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  464. @ResponseBody
  465. public ResponseEntity<?> get(@PathVariable("id") String id) {
  466. ${entityName}Entity task = ${entityName?uncap_first}Service.get(${entityName}Entity.class, id);
  467. if (task == null) {
  468. return new ResponseEntity(HttpStatus.NOT_FOUND);
  469. }
  470. return new ResponseEntity(task, HttpStatus.OK);
  471. }
  472. @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  473. @ResponseBody
  474. public ResponseEntity<?> create(@RequestBody ${entityName}Entity ${entityName?uncap_first}, UriComponentsBuilder uriBuilder) {
  475. //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
  476. Set<ConstraintViolation<${entityName}Entity>> failures = validator.validate(${entityName?uncap_first});
  477. if (!failures.isEmpty()) {
  478. return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
  479. }
  480. //保存
  481. try{
  482. ${entityName?uncap_first}Service.save(${entityName?uncap_first});
  483. } catch (Exception e) {
  484. e.printStackTrace();
  485. return new ResponseEntity(HttpStatus.NO_CONTENT);
  486. }
  487. //按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象.
  488. String id = ${entityName?uncap_first}.getId();
  489. URI uri = uriBuilder.path("/rest/${entityName?uncap_first}Controller/" + id).build().toUri();
  490. HttpHeaders headers = new HttpHeaders();
  491. headers.setLocation(uri);
  492. return new ResponseEntity(headers, HttpStatus.CREATED);
  493. }
  494. @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
  495. public ResponseEntity<?> update(@RequestBody ${entityName}Entity ${entityName?uncap_first}) {
  496. //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
  497. Set<ConstraintViolation<${entityName}Entity>> failures = validator.validate(${entityName?uncap_first});
  498. if (!failures.isEmpty()) {
  499. return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
  500. }
  501. //保存
  502. try{
  503. ${entityName?uncap_first}Service.saveOrUpdate(${entityName?uncap_first});
  504. } catch (Exception e) {
  505. e.printStackTrace();
  506. return new ResponseEntity(HttpStatus.NO_CONTENT);
  507. }
  508. //按Restful约定,返回204状态码, 无内容. 也可以返回200状态码.
  509. return new ResponseEntity(HttpStatus.NO_CONTENT);
  510. }
  511. @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  512. @ResponseStatus(HttpStatus.NO_CONTENT)
  513. public void delete(@PathVariable("id") String id) {
  514. ${entityName?uncap_first}Service.deleteEntityById(${entityName}Entity.class, id);
  515. }
  516. <#-- restful 通用方法生成 -->
  517. }