杂记
原始引入mapper
Public void testfindOrdersList()throws Exception{ //获取session SqlSession session = sqlSessionFactory.openSession(); //获限mapper接口实例 UserMapper userMapper = session.getMapper(UserMapper.class); //查询订单信息 List<OrdersCustom> list = userMapper.findOrdersList(); System.out.println(list); //关闭session session.close(); }
sql片段
//抽取条件 <sql id="query_user_where"> <if test="id!=null and id!=''"> and id=#{id} </if> <if test="username!=null and username!=''"> and username like '%${username}%' </if> </sql> * 使用include引用: <select id="findUserList" parameterType="user" resultType="user"> select * from user <where> <include refid="query_user_where"/> </where> </select> 注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下: <include refid="namespace.sql片段”/>
实体类转map
public static Map<String, Object> object2Map(Object obj) { Map<String, Object> map = new LinkedHashMap<>(); if (obj == null) { return map; } Class clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); try { for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(obj)); } } catch (Exception e) { e.printStackTrace(); } return map; }
date转换
//date转字符串 Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(date); //字符串转Date SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; String str = "2017-02-18"; try { date = format.parse(str); } catch (ParseException e) { e.printStackTrace(); }
获取map的key
for(String key : map.keySet()){ String value = map.get(key); System.out.println(key+" "+value); }
Calendar
Calendar calendar = new GregorianCalendar(); calendar.setTime(announceEnd); calendar.add(Calendar.YEAR, 1); //年加一年
JSONObject 转换
Object SalesIncome = ((JSONObject) ((JSONArray) icr).get(0)).get("SalesIncome"); ((JSONObject) ((JSONArray) icr).get(0)).put("SalesIncome",SalesIncome);
日期转换
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") private Date htIdentifyTime; //默认格式 $('.changeTime').datepicker({ format: 'yyyy-mm-dd', });
后台request接受数组型数据,并做转换
String productCategoryId = TypeUtil.toString(request.getParameter("productCategoryId")); String[] str = request.getParameterMap().get("orgList[]"); List<Integer> ids =new ArrayList<Integer>(); for(int i = 0 ;i<str.length;i++){ ids.add(Integer.parseInt(str[i])); }
ResponseMessage格式
controller
@SystemLog @ResponseBody @RequestMapping("findByParentId") public ResponseMessage selectByParentId(HttpServletRequest request,@RequestParam String level){ ResponseMessage re = new ResponseMessage(); re = productService.selectByParentId(request,level); re.setSuccess(true); return re; }
service:
/** * 修改补贴上限额度 cy */ @Override @Transactional(rollbackFor = Exception.class) public ResponseMessage updateSubsidyLimit(HttpServletRequest request) throws Exception { ResponseMessage rm = new ResponseMessage(); Map<String,Object> map = new HashMap<>(); //接收参数 String id = TypeUtil.toString(request.getParameter("id")); int subsidyLimit = TypeUtil.toInt(request.getParameter("subsidyLimit")); String express = TypeUtil.toString(request.getParameter("express")); String remark = TypeUtil.toString(request.getParameter("remark")); map.put("id",id); map.put("subsidyLimit",subsidyLimit); map.put("express",express); map.put("remark",remark); try { int a = productCategoryMapper.updateSubsidyLimit(map); } catch (Exception e) { e.printStackTrace(); log.error("更新补贴上限失败"); throw new Exception("查询提交信息失败",e); return this.fail("获取服务商信息失败"); } return this.success(rm); }
页面请求
function lookPro(attribute){ $.ajax({ type: 'POST', url: adminCtx + "/product/findByParentId", data: {'attribute': attribute,"level":1}, dataType: 'json', success: function (data) { console.log(data); var pros = data.result; if (data.success) { if(pros.length == 0){ $("#product").append("<div> 暂无服务产品 </div>"); } $("#product").append('<div ></div>'); pros.forEach(function(ele,i){ $("#product").append("<div style='float:left;width:200px' class=' layui-layer-padding layui-icon layui-icon-auz color:#009688' id=" + pros[i].id + " value=" + pros[i].id + ">" + pros[i].name + "</div>"); }) } } }); }
表格 table.render({ elem: "#productTable", url: adminCtx + "/product/shu", skin: 'line', cols: [[ {field: 'name', title: '属性', minWidth: 200, align: 'center'} ,{field: 'des', title: '说明', minWidth: 200, align: 'center'} ,{field: 'updateTime', title: '时间', minWidth: 200,templet: "#updateTime", align: 'center'} , {field: 'id', title: '操作', width: 250, align: 'center',templet: "#btnTpl",fixed: 'right'} ]], response: { statusName: 'code' //数据状态的字段名称,默认:code , statusCode: 200 //成功的状态码,默认:0 , msgName: 'message' //状态信息的字段名称,默认:msg , countName: 'total' //数据总数的字段名称,默认:count , dataName: 'result' //数据列表的字段名称,默认:data } });
ModelAndView格式
controller: @RequestMapping(value ="/reviewStatus") @ResponseBody @SystemLog public ModelAndView reviewStatus(String id,String name){ ModelAndView modelAndView = this.createHtmlView("admin/prodAndService/reviewStatus"); modelAndView.addObject("comOAndServiceObject", prodAndSerService.comOAndServiceObject(name)); modelAndView.addObject("prodObject", prodAndSerService.prodObject(id)); modelAndView.addObject("id", id); return modelAndView; } service: @Override public List treadInfo(String id) { Map<String, Object> map = new HashMap<>(); map.put("orderId",id); return transactioninfoMapper.selectMap(map); } 页面 <td> <ul class="order-list"> <li><span >单价:</span><span class="nl_ft_orange" th:text=" '¥'+${comOAndServiceObject[0].productPrice}" ></span></li> <li><span >数量:</span><span class="nl_ft_orange" th:text=" ${comOAndServiceObject[0].quantity}" ></span></li> <li><span >小计:</span><span class="nl_ft_orange" th:text=" '¥'+${comOAndServiceObject[0].price}"></span></li> <li><span >合创券抵用:</span><span class="nl_ft_orange" th:text=" '¥'+${comOAndServiceObject[0].deduction}"></span></li> <li><span>待付总额</span><span class="nl_ft_red" style="font-weight: bold;font-size: 15px;" th:text=" '¥'+${comOAndServiceObject[0].discount}"></span></li> </ul> </td>
thymeleaf
循环select 的option项
<select class="form-control" id="slaId" th:field="*{slaId}"> <option value="0">请选择</option> <option th:each="slaItem : ${slaItems}" th:value="${slaItem.id}" th:text="${slaItem.name}">Options</option> </select>
赋值判断
<li>支持自定义知识库:<strong th:text="${slaItem.supportCustomize eq 1}?'是':'否'"></strong></li> 判断集合长度是否是0 <div style="text-align: center" th:if="${fishObject.size()} eq 0"> <strong style="color: #f75e5e">暂无记录</strong> </div>
单击事件
th:onclick="'javascript:deleteBilling(\''+${appInfoForm.billingId}+'\',\''+${appInfoForm.appKey}+'\');'" th:onclick="'showImge(\''+${data.serviceMaterial.materialUrl}+'\')'"
传参
th:href="@{/console/createBilling(appKey=${appInfoForm.appKey})}" <a target="_blank" th:href="@{http://localhost:8081/anon/orgsByProType(typeNew=${productObj.id},attribute=${productObj.attribute})}"></a>
日期的格式化
th:text="${#dates.format(billingForm.startTime,'yyyy-MM-dd HH:mm:ss')}"
图片回显
th:src="@{'../resources/goods/'+${table.path}}" <img th:src="@{${productObj.icon}}"/>
js取值
<script th:inline="javascript"> var message = [[${message}]]; console.log(message); </script>
获取系统当前日期
System.currentTimeMillis() < vou.getDisableTime().getTime()
Mybatis拼接
and operateUser LIKE concat("%", #{name}, "%")
注释生成
前后台处理多个参数
1、前台封装
前台 // 6 JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个 JSON字符串 // 把arr字符串放入jsonStr 中,所以我们只需要把jsonStr 传入后台就能得到arr中所有的参数 param.jsonStr = JSON.stringify(arr); param.roleId = roleId; param.deleteIds = deleteIds; 。。。。 后台 public String saveAccountRole(String jsonStr, String deleteIds, Long roleId) { //获取角色list数据(对象数组) List<SysUserRole> userList = new ArrayList<SysUserRole>(); if (StringUtils.isNotBlank(jsonStr)) { userList = JSON.parseArray(jsonStr, SysUserRole.class); } 。。。。
2、使用@RequestParam注解
@Controller public class Login{ @RequestMapping("/login") //使用@RequestParam注解接收前台参数 public String login(@RequestParam("userName") String userName , @RequestParam("passWord") String passWord , Model model){ if("admin".equals(userName) && "admin".equals(passWord)){ model.addAttribute("username" , userName); model.addAttribute("password" , passWord); return "loginSuccess.jsp"; }else { returne "login.jsp"; } } } mapper中 int editStatusById(@Param("id") String id, @Param("status") String status);
3、参数少的时候,直接写
@Controller publib class Login{ public String login(String userName , String passWord , Model model){ if("admin".equals(userName) && "admin".equals(passWord)) {。。。。
4、 使用HttpServletRequest接收(get和post方式都可以)
public String login(HttpServletRequest request){ String username = request.getParameter("userName"); String password = request.getParameter("password"); System.out.print(username); System.out.print(password); }
5、将封装到参数bean中,名称必须和前端一致
public class User{ private String name; private String pass; } @RequestMapping("/login.do") public String login(User user) { syso(user.getName()); syso(user.getPass()); }
用map接收,再转成实体类
传递参数时json字符串
跨域问题
/** * 跨域过滤器 * * @return */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new CorsFilter(source); }
smile

浙公网安备 33010602011771号