2月 182020
 

题外话,前端也可以调用已有的接口获取ip,例如调用搜狐接口 https://pv.sohu.com/cityjson?ie=utf-8

在spring框架中,获取IP接口,则需要获取 HttpServletRequest 对象,该对象中包含了客户端请求的相关信息。

java代码如下:

/** 
 * @Description: 获取客户端IP地址   
 */  
private String getIpAddr(HttpServletRequest request) {   
    String ip = request.getHeader("x-forwarded-for");   
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
        ip = request.getHeader("Proxy-Client-IP");   
    }   
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
        ip = request.getHeader("WL-Proxy-Client-IP");   
    }   
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
        ip = request.getRemoteAddr();   
        if(ip.equals("127.0.0.1")){     
            //根据网卡取本机配置的IP     
            InetAddress inet=null;     
            try {     
                inet = InetAddress.getLocalHost();     
            } catch (Exception e) {     
                e.printStackTrace();     
            }     
            ip= inet.getHostAddress();     
        }  
    }   
    // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
    if(ip != null && ip.length() > 15){    
        if(ip.indexOf(",")>0){     
            ip = ip.substring(0,ip.indexOf(","));     
        }     
    }     
    return ip;   
}

Continue reading »

1月 162020
 

Java中日期格式化yyyyMMdd和YYYYMMdd的区别

示例代码:

 public static void main(String[] args) {
        //YYYY 是表示:当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。
        //2019-12-29至2020-1-4跨年周
        Calendar calendar = Calendar.getInstance();
        //2019-12-28
        calendar.set(2019, Calendar.DECEMBER, 28);  
        Date strDate1 = calendar.getTime(); 
        //2019-12-29
        calendar.set(2019, Calendar.DECEMBER, 29);  
        Date strDate2 = calendar.getTime(); 
        // 2019-12-31  
        calendar.set(2019, Calendar.DECEMBER, 31);  
        Date strDate3 = calendar.getTime();  
        // 2020-01-01  
        calendar.set(2020, Calendar.JANUARY, 1);  
        Date strDate4 = calendar.getTime();  
        
        DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
        DateFormat df2 = new SimpleDateFormat("YYYYMMdd");
        //yyyyMMdd
        System.out.println("yyyyMMdd");
        System.out.println("2019-12-28: " + df1.format(strDate1)); 
        System.out.println("2019-12-29: " + df1.format(strDate2)); 
        System.out.println("2019-12-31: " + df1.format(strDate3));  
        System.out.println("2020-01-01: " + df1.format(strDate4));  
        //YYYYMMdd
        System.out.println("YYYYMMdd");
        System.out.println("2019-12-28: " + df2.format(strDate1));
        System.out.println("2019-12-29: " + df2.format(strDate2));
        System.out.println("2019-12-31: " + df2.format(strDate3));  
        System.out.println("2020-01-01: " + df2.format(strDate4));
    }

输出结果: Continue reading »

12月 132019
 

问题与原因

启动spring boot程序时,报异常,导致程序启动失败,遇到形如下面的错误:

A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/Integration]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
……

然而,这个只是结果,实际上并不能定位问题,笔者继续找异常,看到类似下面的错误: Continue reading »

12月 052019
 

代码取自:JAVA根据URL网址获取输入流

/**
 * 根据地址获得数据的输入流
 * @param strUrl 网络连接地址
 * @return url的输入流
 */
    public static InputStream getInputStreamByUrl(String strUrl){
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(),output);
            return  new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            logger.error(e+"");
        }finally {
            try{
                if (conn != null) {
                    conn.disconnect();
                }
            }catch (Exception e){
                logger.error(e+"");
            }
        }
        return null;
    }

如若想下载文件,则可以在上面方法基础上,进一步封装即可:
Continue reading »

10月 192019
 

需求:xml中传入参数中包含一个list,需要在where中拼接in语句

假设查询person表,参数类型为XXXVo,XXXVo中包含一个List对象,保存了状态列表,此时可以参考如下查询

<select id="queryXXX" parameterType="XXXVo"
			resultMap="XXXResult">
		select *
		from person
		 WHERE 1=1
		<if test="statusFilter != null and statusFilter.size() > 0">
            and status in
            <foreach collection="statusFilter" item="statusId" index="i" open="(" close=")" separator=",">
                #{statusId}
            </foreach>
        </if>
		 ORDER BY DEPTID
	</select>

Continue reading »

9月 262019
 

google guava使用教程系列(3)- 前置条件检查

原文地址:[https://github.com/google/guava/wiki/PreconditionsExplained])(https://github.com/google/guava/wiki/PreconditionsExplained)

简而言之,guava提供了一系列检查参数的方案,个人感觉一般,实际业务场景中对于参数判断自己写可能比这种封装更方便。

官方举的例子:

checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s >= %s", i, j);

大致有如下几类:

  • checkArgument(boolean)
  • checkNotNull(T)
  • checkState(boolean)
  • checkElementIndex(int index, int size)
  • checkPositionIndex(int index, int size)
  • checkPositionIndexes(int start, int end, int size)

http://ifeve.com/google-guava-preconditions/有翻译,但翻译不全,建议github上的原版wiki。看名字基本能猜到方法用途,看个人喜好吧,我个人倒是更喜欢apache commons里的校验方法,比如StringUtils.isEmpty()

9月 132019
 

课程链接

课程:https://url.163.com/VD8

java锁

synchronized

在jdk 1.5以后,优化了,使其性能并不是像很多帖子说的那样,“非常重”

JUC lock

方法 说明
lock() 获取锁,如果锁被暂用则一直等待
tryLock() 如果获取锁的时候锁被占用就返回false,否则返回true
tryLock(long time, TimeUnit unit) 比起tryLock,多出等待时间
unLock()
lockInterruptibly()

Continue reading »

8月 242019
 

本文仅展示总体配置,具体注解用法请另行搜索、查询。

1.加上maven依赖,引入相关包

</pre>
<pre><dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-annotations -->
<dependency>
    <groupId>io.swagger.core.v3</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>2.0.8</version>
</dependency>
<!-- http://localhost:18004/doc.html -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.8.8</version>
</dependency>
<!-- Swagger用了高版本的 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.0-jre</version>
</dependency></pre>
<pre>

Continue reading »