java的小细节

1,用mybatis框架做分页查询,直接用map

dao: 
     public List<Installment> findhistory( int limits, int pages, String sogo) {
		
		 Map<String, Object> data = new HashedMap();
	        data.put("currIndex", (pages-1)*limits);
	        data.put("pageSize", limits);
	        data.put("sogo", sogo);
		List<Installment> list = installmentMapper.selectall(data);
		return list;
}
     

mapper.xml:     //返回的是list集合  分页排序
   <select id="selectall" resultMap="BaseResultMap" parameterType="com.zhiyu.pojo.Installment">
  select * from installment  
  <where>
  sogo=#{sogo}
  </where>
  
 ORDER  BY id DESC limit #{currIndex} , #{pageSize} 
  </select>

//返回实体类
 <select id-"findphone" resulttype="com.xxxxx.pojo.userlogin">
select * from userlogin 
<where>phone=#{phone}</where>

</select>
  

2,去掉双引号

String sogo= sogo1.replace("\"", "");//去掉双引号

3,去掉小数点后面的0

String amt = amt2.toString();
		
		 if(amt.indexOf(".") > 0){
	           amt = amt.replaceAll("0+?$", "");//去掉后面无用的零

	          	 amt = amt.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点

	          	 }
		

4,uuid的工具类

	//32位的uuid
	public static String getUUID32() {
		
		String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

		
		return uuid;
	}

//生成指定个数的uuid
	public static String[] getUUID(int num) {
		
		if(num<=0) {
			return null;
		}
		String[] uuidAri=new String[num];
		
		for(int i=0;i<uuidAri.length;i++) {
			System.out.println(uuidAri[i]=getUUID32());
		}
		
		return uuidAri;
	}

5,mybatis的mapper的自带查询,要进行升序或降序查询example

//降序
   UserloginExample example = new UserloginExample();
		example.setOrderByClause("id DESC");
		Criteria criteria = example.createCriteria();
//条件
		criteria.andTogetherwayEqualTo(togetherway);
		criteria.andSogoEqualTo(sogo);

//升序
   UserloginExample example = new UserloginExample();
		example.setOrderByClause("id asc");
		Criteria criteria = example.createCriteria();
//条件
		criteria.andTogetherwayEqualTo(togetherway);
		criteria.andSogoEqualTo(sogo);

6,查询号码,返回数据 中间的数据用*代替

U  serloginExample example = new UserloginExample();
		example.setOrderByClause("id DESC");
		Criteria criteria = example.createCriteria();
		criteria.andTogetherwayEqualTo(togetherway);
		criteria.andSogoEqualTo(sogo);
		List<Userlogin> list = userloginMapper.selectByExample(example);
	    ArrayList<Userlogin> arrayList = new ArrayList<>();
		for(int k=0;k<list.size();k++) {
			Integer id = list.get(k).getId();
			String mobile = list.get(k).getPhone();
			String copy2 = list.get(k).getCopy2();
			String togetherway2 = list.get(k).getTogetherway();
			
			char[] m =  mobile.toCharArray();
            for(int i=0; i<m.length;i++){
                if(i>2 && i<7){
                    m[i] = '*';
                }
            }
            String phone =  String.valueOf(m);
			Userlogin userlogin = new Userlogin();
			userlogin.setId(id);
			userlogin.setPhone(phone);
			userlogin.setCopy2(copy2);
			userlogin.setTogetherway(togetherway2);
			arrayList.add(userlogin);
			

7,BigDecimal的加减乘除

加法 add()函数     减法substract()函数
乘法multipy()函数    除法divide()函数    绝对值abs()函数

 BigDecimal num1 = new BigDecimal(0.005);
        BigDecimal num2 = new BigDecimal(1000000);
        BigDecimal num3 = new BigDecimal(-1000000);
        //尽量用字符串的形式初始化
        BigDecimal num12 = new BigDecimal("0.005");
        BigDecimal num22 = new BigDecimal("1000000");
        BigDecimal num32 = new BigDecimal("-1000000");
 
        //加法
        BigDecimal result1 = num1.add(num2);
        BigDecimal result12 = num12.add(num22);
        //减法
        BigDecimal result2 = num1.subtract(num2);
        BigDecimal result22 = num12.subtract(num22);
        //乘法
        BigDecimal result3 = num1.multiply(num2);
        BigDecimal result32 = num12.multiply(num22);
        //绝对值
        BigDecimal result4 = num3.abs();
        BigDecimal result42 = num32.abs();
        //除法
        BigDecimal result5 = num2.divide(num1,20,BigDecimal.ROUND_HALF_UP);
        BigDecimal result52 = num22.divide(num12,20,BigDecimal.ROUND_HALF_UP);

8,日期的算法

   //逾期天数
      Date today1 = (Date)df.parse(today);
      
       Date latespaymenttime = (Date)df.parse(latestpaymenttime);
      
       long overdata=today1.getTime()-latespaymenttime.getTime();
       //System.out.println("相差毫秒数..."+overdata);
       long overdays=overdata/(1000 * 60 * 60 * 24);
    /* long overhours=  (overdata % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
     long minutes = (overdata % (1000 * 60 * 60)) / (1000 * 60);
		long seconds = (overdata % (1000 * 60)) / 1000;*/
		//String differenceFormat = overdays + " days " + overhours + " hours " + minutes + " minutes " + seconds + " seconds ";
        System.out.println("相差天数...."+overdays);
		//System.out.println("相差时间..."+differenceFormat);

9,map数据返给json数据

Map<String, Object> map = new HashMap<String, Object>();

 //还款
          map.put("repaidmount", repaidmount3);
          map.put("repaidretio", repaidretio);
          map.put("latesbill", latesbill);
          map.put("latestpaymenttime", latestpaymenttime);
          map.put("content", content);
            //历史记录
            map.put("historys", historys);
            String jsonString = JSON.toJSONString(map);
             return jsonString;

10.md5加密

    /**
     * MD5加密
     * @param source
     * @return
     */
    public static final String MD5Encrpytion(byte[] source) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(source);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
                str[(k++)] = hexDigits[(byte0 & 0xF)];
            }
            for (int m = 0; m < str.length; ++m) {
                if ((str[m] >= 'a') && (str[m] <= 'z')) {
                    str[m] = (char) (str[m] - ' ');
                }
            }
            return new String(str);
        } catch (Exception e) {
        }
        return null;
    }

11.httpclient

HttpClientUtil:
public class HttpClientUtil {
	   private static RequestConfig requestConfig = RequestConfig.custom()
	            //从连接池中获取连接的超时时间
	            // 要用连接时尝试从连接池中获取,若是在等待了一定的时间后还没有获取到可用连接(比如连接池中没有空闲连接了)则会抛出获取连接超时异常。
	            .setConnectionRequestTimeout(15000)
	            //与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
	            //连接目标url的连接超时时间,即客服端发送请求到与目标url建立起连接的最大时间。超时时间3000ms过后,系统报出异常
	            .setConnectTimeout(15000)
	            //socket读数据超时时间:从服务器获取响应数据的超时时间
	            //连接上一个url后,获取response的返回等待时间 ,即在与目标url建立连接后,等待放回response的最大时间,在规定时间内没有返回响应的话就抛出SocketTimeout。
	            .setSocketTimeout(15000)
	            .build();

	   public static String sendHttp(HttpRequestMethedEnum requestMethod,String url,Map<String, Object> params,Map<String,String> header) {
		   
		   //1,创建httpClient对象
		   CloseableHttpClient httpClient = HttpClients.createDefault();
		   
		   CloseableHttpResponse httpResponse=null;
		   String responseContent=null;
		   //2,创建一个http请求对象并设置请求的url,
		   HttpRequestBase request = requestMethod.createRequest(url);
		   //3,如果需要设置请求对象的请求头参数,也可以往请求对象中添加请求参数
		   if(header!=null) {
			   for (Map.Entry<String, String> entry : header.entrySet()) {
				
				   request.setHeader(entry.getKey(), entry.getValue());
			}
		   }
		   //往对象中添加相关的参数
		   try {
			   if(params!=null) {
				   
				   ((HttpEntityEnclosingRequest) request).setEntity(
	                        new StringEntity(JSON.toJSONString(params),
	                                ContentType.create("application/json", "UTF-8")));
				 //System.out.println("hehe"+ JSON.toJSONString(params));
			   }
			   //4,调用HttpClient对象的execute方法执行
			   httpResponse=httpClient.execute(request);
			   //5,获取请求响应对象和响应Enity
			   HttpEntity httpEntity=httpResponse.getEntity();
			   //6.从相应对象中,获取相应状态,从响应Entiy中获取响应内容
			   if(httpEntity!=null) {
				   String content = EntityUtils.toString(httpEntity, "utf-8");
				   responseContent=content;
				   //System.out.println("响应的内容...."+content);
			   }
			   
		   }catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				//7,关闭响应对象
				if(httpResponse!=null) {
					httpResponse.close();
				}
				//8,关闭Client
				if(httpClient!=null) {
					httpClient.close();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		   
		   return responseContent;
		   
	   }
httprequestMethedEnum:
public enum HttpRequestMethedEnum {
    // HttpGet请求
    HttpGet {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpGet(url); }
    },
    // HttpPost 请求
    HttpPost {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpPost(url); }
    },
    // HttpPut 请求
    HttpPut {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpPut(url); }
    },
    // HttpDelete 请求
    HttpDelete {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpDelete(url); }
    };
 
    public HttpRequestBase createRequest(String url) { return null; }
}
	

12.mybatis查看sql语句,在mybatis.cfg.xml里面配置

<!--配置查看sql语句  -->
  <!--   <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings> -->

13,日期

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

  String today = df.format(new Date());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值