常用的功能代码

在开发工作中,要注意积累,避免重复开发

 

 

目录

1.定时任务

1.1spring-task(配置文件)

1.2spring-quartz(配置文件)

1.3springboot-task(显示配置/配置文件)

2.提供/调用接口

2.1struts2提供接口

2.2springmvc提供接口

2.3调用接口

2.3.1post请求-返回fastJson

2.3.2get请求-返回fastJson

2.3.3fastJson转 net.sf.json

2.3.4json转javaBean

2.3.5 json转泛型javaBean

2.4 访问https接口

3.图片处理

3.1图片转base64字符串

3.2base64字符串转图片 

4.配置文件

5.mysql索引

6.枚举

7.基本开发功能总结

1.多条件查询的分页页面

2.poi导入导出

3.树形结构

4.提供接口,调用第三方接口

5.权限shiro,spring security

6.redis

7.activeMq


1.定时任务

1.1spring-task(配置文件)

spring-task.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">


    <!--
      任务调度器配置:
        task:scheduler/@pool-size:调度线程池的大小,调度线程在被调度任务完成前不会空闲
        task:scheduled/@cron:cron表达式,注意,若上次任务未完成,即使到了下一次调度时间,任务也不会重复调度
     -->
    <task:scheduler id="scheduler" pool-size="5"/>

    <!-- 定时同步高端客户任务-->
    <bean id="updateFaceoneDataTask" class="com.hikvision.rpc.service.vip.updateVipInfoTask.UpdateFaceoneDataTask"/>
    <task:scheduled-tasks scheduler="scheduler">
        <task:scheduled ref="updateFaceoneDataTask" method="updateAccessData" cron="0/10 * * * * ?"/>
    </task:scheduled-tasks>

</beans>

在applicationContext.xml中引入

	<!--定时任务-->
	<import resource="classpath:spring-task.xml" />

定时任务类

public class UpdateFaceoneDataTask {

    public void updateAccessData() {
        System.out.println("begin...");
    }

 

1.2spring-quartz(配置文件)

配置文件方式

spring-task.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
       default-lazy-init="false">

    <!-- 在spring配置文件中配置任务类-->
    <bean id="UpdateCustomDataTask" class="com.hikvision.rpc.service.vip.updateVipInfoTask.UpdateFaceoneDataTask"/>

    <!-- 配置JobDetail -->
    <bean id="updateJobDataDetail"
          class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 指定任务类 -->
        <property name="targetObject" ref="UpdateCustomDataTask"/>
        <!-- 指定任务方法 -->
        <property name="targetMethod" value="updateAccessData"/>
        <property name="concurrent" value="false"/>
    </bean>

    <!-- 配置触发器 -->
    <bean id="updateJobDetailCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="updateJobDataDetail"/>
        </property>
        <property name="cronExpression">
            <value>0 0 2 * * ?</value> <!-- 任务触发时间 -->
        </property>
    </bean>

    <!-- 启动定时器 -->
    <bean id="springSchedulerFactory"
          class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
          lazy-init="false">
        <property name="triggers">
            <list>
                <ref local="updateJobDetailCronTrigger"/>
            </list>
        </property>
    </bean>
</beans>

定时任务类

public class UpdateFaceoneDataTask {

    /**
     * 更新数据
     */
    public void updateCustomDate() {

    }
}

 在applicationContext.xml中引入

	<!--定时任务-->
	<import resource="classpath:spring-task.xml" />

 pom引入

		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>1.8.5</version>
		</dependency>

 配置链接:quartz的xml配置和注解配置

1.3springboot-task(显示配置/配置文件)

<1>配置文件

spring-task.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">


    <!--
      任务调度器配置:
        task:scheduler/@pool-size:调度线程池的大小,调度线程在被调度任务完成前不会空闲
        task:scheduled/@cron:cron表达式,注意,若上次任务未完成,即使到了下一次调度时间,任务也不会重复调度
     -->
    <task:scheduler id="scheduler" pool-size="5"/>


    <!-- 定时计算用户数量-->
    <bean id="countSysUserTask" class="com.hikvision.shiro.common.task.CountSysUserTask"/>
    <task:scheduled-tasks scheduler="scheduler">
        <task:scheduled ref="countSysUserTask" method="countSysUser" cron="0/5 * * * * ?"/>
    </task:scheduled-tasks>
</beans>

定时任务类

 

public class CountSysUserTask {

    @Autowired
    private SysUserService sysUserService;

    public void countSysUser(){
        Integer count = sysUserService.countSysUser();
        System.out.println(count);
    }

}

把spring-task.xml引入spring中

@Configuration
@ImportResource(locations = {"classpath:spring-task.xml"})
public class TimeTaskConfig {
}

 

2.提供/调用接口

2.1struts2提供接口

action

@Controller(value = "VipTrajectoryAction")
@Scope("prototype")
public class VipTrajectoryAction extends BaseAction {
 private static final Logger LOGGER = Logger.getLogger(VipTrajectoryAction.class);
    
        /**
     * 获取人员的历史轨迹
     */
    public void getHistoryTrajectory(){
        try {
            HistoryTrajectoryVo historyTrajectoryVo = vipInnerEmapInfoService.getHistoryTrajectoryVo(vipInfologId);
            msg = "获取人员历史轨迹列表信息";
            json.put("success", true);
            json.put("msg", msg);
            json.put("data", historyTrajectoryVo);
        } catch (Exception e) {
            LOGGER.error("报错",e);
            msg = "获取人员历史轨迹列表信息失败";
            json.put("success", false);
            json.put("msg", msg);
        }
        outOfRealJSON(json);
    }
}

 

	/**
	 * 真json输出
	 * @param object
	 */
	public void outOfRealJSON(JSONObject object){
		String str = object.toString();
		PrintWriter pw = null;
		try {
			response.setHeader("content-length", String.valueOf(str
					.getBytes("UTF-8").length));
			response.setContentType("application/json;charset=UTF-8");
			pw = response.getWriter();
			pw.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(pw!=null){
				pw.close();
			}
		}
	}

struts-monitor-vipTrajectory.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="vipTrajectory" extends="struts-default" namespace="/webmonitor/vipTrajectory">
		<action name="VipTrajectoryAction!*" method="{1}"  class="VipTrajectoryAction"></action>
		<action name="HistoricalTrajectoryAction!*" method="{1}"  class="HistoricalTrajectoryAction"></action>
	</package>
</struts>

 引入struts.xml

<include file="com/hikvision/monitor/VipTrajectory/struts-monitor-vipTrajectory.xml"></include><!-- 人员轨迹 -->

2.2springmvc提供接口

很多时候需要调用第三方接口,使用springboot快速搭建项目,提供接口来模拟第三方接口,提供测试环境

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.19.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gua</groupId>
    <artifactId>httpDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>httpDemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 controller

@RestController
@RequestMapping("/demo")
public class Controller {
    @RequestMapping("/api")
    public String api(){
        return "{\"name\":\"王建国\"}";
    }
}

 多层json数据

@RestController
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("/object")
    public Person ObjectJson() {
        Person person = new Person();
        person.setName("杨过");
        person.setAge(25);

        List<Product> list = new ArrayList<>();
        Product p1 = new Product();
        p1.setCode("1");
        p1.setName("歼10");
        Product p2 = new Product();
        p2.setCode("2");
        p2.setName("歼20");
        list.add(p1);
        list.add(p2);
        person.setProduct(list);
        Assets asserts = new Assets();
        asserts.setBill(100);
        asserts.setBund(200);
        person.setAssets(asserts);
        return person;
    }
}

class Person {
    private String name;
    private Integer age;
    private List<Product> product;

    private Assets assets;

    public String getName() {
        return name;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }

    public Integer getAge() {
        return age;
    }

    public Person setAge(Integer age) {
        this.age = age;
        return this;
    }

    public List<Product> getProduct() {
        return product;
    }

    public Person setProduct(List<Product> product) {
        this.product = product;
        return this;
    }

    public Assets getAssets() {
        return assets;
    }

    public Person setAssets(Assets assets) {
        this.assets = assets;
        return this;
    }
}

class Product {
    private String code;
    private String name;

    public String getCode() {
        return code;
    }

    public Product setCode(String code) {
        this.code = code;
        return this;
    }

    public String getName() {
        return name;
    }

    public Product setName(String name) {
        this.name = name;
        return this;
    }
}

class Assets {
    private int bill;
    private int bund;

    public int getBill() {
        return bill;
    }

    public Assets setBill(int bill) {
        this.bill = bill;
        return this;
    }

    public int getBund() {
        return bund;
    }

    public Assets setBund(int bund) {
        this.bund = bund;
        return this;
    }
}

2.3调用接口

2.3.1post请求-返回fastJson

package com.hikvision.common.util;

import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpUtils {

	private static final Logger logger = Logger.getLogger(HttpUtils.class);

	private static final String ENCODE_CHAR = "UTF-8";

	private static final int time_out = 10000;

	/**
	 * 发起http post请求
	 * 
	 * @param url
	 *            请求的地址 参数拼接在url
	 * @param params
	 *            请求的参数
	 * @return 请求成功返回请求的数据
	 * @throws Exception
	 *             请求发生异常
	 */
	public static JSONObject sendHttpClient(String url, JSONObject params) {

		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(time_out) // 设置连接超时时间
				.setConnectTimeout(time_out) // 数据传输的最长时间
				.setConnectionRequestTimeout(time_out) // 设置连接请求最长时间
				.build();
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

		// 查询推送参数
		JSONObject resultJsonObject = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(params.toString(), Charset.forName(ENCODE_CHAR));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == HttpStatus.SC_OK) {
				logger.info("第三方推送服务器正常响应.....");
				HttpEntity resEntity = response.getEntity();
				resultJsonObject = JSON.parseObject(EntityUtils.toString(resEntity).toString());
				logger.info("第三方接口返回  " + resultJsonObject.toJSONString());
			}
		} catch (Exception e) {
			logger.info("post请求异常", e);
		}
		return resultJsonObject;
	}
}

2.3.2get请求-返回fastJson

 

package com.hikvision.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @Title: HttpGetUtil
 * @Description: http-get请求工具类
 * @date 2019/4/9 16:28
 */
public class HttpGetUtil {

	private static final Logger LOGGER = Logger.getLogger(HttpGetUtil.class);

	private static final int TIME_OUT = 10000;

	/**
	 * http get请求
	 *
	 * @param url
	 * @return
	 */
	public static JSONObject httpGet(String url) {

		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT) // 设置连接超时时间
				.setConnectTimeout(TIME_OUT) // 数据传输的最长时间
				.setConnectionRequestTimeout(TIME_OUT) // 设置连接请求最长时间
				.build();
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

		// 查询推送参数
		JSONObject resultJsonObject = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			LOGGER.info("get请求url:" + url);
			HttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = response.getEntity();
				resultJsonObject = JSON.parseObject(EntityUtils.toString(resEntity).toString());
				LOGGER.info("接口返回值:" + resultJsonObject.toJSONString());
			}
		} catch (Exception e) {
			LOGGER.error("get请求异常", e);
		}
		return resultJsonObject;
	}

}

 

2.3.3fastJson转 net.sf.json

com.alibaba.fastjson.JSONObject json = HttpGetUtil.httpGet(url);
String string = json.toJSONString();
JSONObject jsonObject = JSONObject.fromObject(string);

2.3.4json转javaBean

public class FastJsonUtil {
    private FastJsonUtil() {
    }

    public static Custom jsonToCustom(String jsonStr) {
        return JSONObject.parseObject(jsonStr, Custom.class);
    }

    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"王建国\",\"age\":24,\"cellPhone\":\"18829037917\"}";
        Custom custom = JSONObject.parseObject(jsonStr, Custom.class);
        System.out.println(custom);
    }
}

 javaBean

public class Custom {
    private String name;
    private Integer age;
    private String cellPhone;

    @Override
    public String toString() {
        return "Custom{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", cellPhone='" + cellPhone + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public Custom setName(String name) {
        this.name = name;
        return this;
    }

    public Integer getAge() {
        return age;
    }

    public Custom setAge(Integer age) {
        this.age = age;
        return this;
    }

    public String getCellPhone() {
        return cellPhone;
    }

    public Custom setCellPhone(String cellPhone) {
        this.cellPhone = cellPhone;
        return this;
    }
}

2.3.5 json转泛型javaBean

Result<User> obj = (Result<User>) JSON.parseObject(js, new TypeReference<Result<User>>(){});

2.4 访问https接口

这个必须使用jdk8,jdk7不支持

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsClientUtil {
    public HttpsClientUtil() {

    }

    public static CloseableHttpClient httpsClient = null;


    public static void main(String[] args) {
        HttpsClientUtil.httpsClientInit("10.10.84.200", "admin", "hik12345");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dataType", "URL");

        JSONObject targetJson = new JSONObject();
        targetJson.put("URL", "http://10.10.84.200:8080/kms/services/rest/dataInfoService/downloadFile?id=Static/10001/001/t001/01d&token=7a57a5a7ffffffffc1a0316369671314");
        jsonObject.put("TargetImage", targetJson);


        JSONObject contrastJson = new JSONObject();
        contrastJson.put("URL", "http://10.10.84.200:8080/kms/services/rest/dataInfoService/downloadFile?id=Static/10001/001/t001/01d&token=7a57a5a7ffffffffc1a0316369671314");
        jsonObject.put("ContrastImage", contrastJson);

        String s = HttpsClientUtil.httpsPost("https://10.10.84.200/ISAPI/Intelligent/imagesComparision/face", jsonObject.toString());
        System.out.println(s);
    }

    public static String getISAPIPost(String ip, String username, String password, String url, String jsonStr) {
        httpsClientInit(ip, username, password);
        String result = httpsPost(url, jsonStr);
        return result;
    }


    public static void httpsClientInit(String IP, String user, String Password) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(user, Password);
        credentialsProvider.setCredentials(new AuthScope(IP, 443), credentials);
        HttpsClientUtil.httpsClient = HttpClients.custom()
                .setSSLSocketFactory(HttpsClientUtil.createSSLConnSocketFactory())
                .setDefaultCredentialsProvider(credentialsProvider).build();
    }

    public static SSLConnectionSocketFactory createSSLConnSocketFactory() {

        SSLConnectionSocketFactory sslsf = null;
        try {

            TrustStrategy trustStrategy = new TrustStrategy() {

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            };

            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();

            X509HostnameVerifier x509HostnameVerifier = new X509HostnameVerifier() {

                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            };

            sslsf = new SSLConnectionSocketFactory(sslContext, x509HostnameVerifier);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }


    public static String httpsGet(String url) {
        String Ret = "";
        try {
            CloseableHttpResponse response = null;
            HttpGet httpGet = new HttpGet(url);

            response = httpsClient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Ret = "error " + statusCode;
            }

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                Ret = "error response is null";
            }

            Ret = EntityUtils.toString(entity, "utf-8");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Ret;
    }

    public static String httpsPut(String url, String inboundInfo) {
        String Ret = "";
        try {
            CloseableHttpResponse response = null;
            HttpPut httpPut = new HttpPut(url);

            HttpEntity inboundInfoEntity = new StringEntity(inboundInfo, "UTF-8");
            httpPut.setEntity(inboundInfoEntity);

            response = httpsClient.execute(httpPut);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Ret = "error " + statusCode;
            }

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                Ret = "error response is null";
            }

            Ret = EntityUtils.toString(entity, "utf-8");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Ret;
    }

    public static String httpsPost(String url, String inboundInfo) {
        String Ret = "";
        try {
            CloseableHttpResponse response = null;
            HttpPost httpPost = new HttpPost(url);

            HttpEntity inboundInfoEntity = new StringEntity(inboundInfo, "UTF-8");
            httpPost.setEntity(inboundInfoEntity);

            response = httpsClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Ret = "error " + statusCode + response.toString();
            }

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                Ret = "error response is null";
            }

            Ret = EntityUtils.toString(entity, "utf-8");

        } catch (ClientProtocolException e) {
            return e.toString();
        } catch (IOException e) {
            return e.toString();
        }
        return Ret;
    }

    public static String httpsDelete(String url) {
        String Ret = "";
        try {
            CloseableHttpResponse response = null;
            HttpDelete httpDelete = new HttpDelete(url);

            response = httpsClient.execute(httpDelete);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Ret = "error " + statusCode;
            }

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                Ret = "error response is null";
            }

            Ret = EntityUtils.toString(entity, "utf-8");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Ret;
    }
}

 

3.图片处理

图片接收方式-base64-接口化处理

3.1图片转base64字符串

图片以url形式或者文件形式

    /**
    * 请求连接时长
    */
    private final int time_out = 10000;

	/**
	 * 根据图片url获取图片的base64字符串
	 * @author xionghao5 2018年9月4日 下午5:07:16
	 * @param strUrl
	 * @return
	 * @since 2.1
	 */
	private String getImageBase64(String strUrl) {
		String base64Str = null;
		try {
			base64Str = byteArrayToString(getImageFromNetByUrl(strUrl));
		} catch (Exception e) {
			logger.info("根据图片url转化成base64字符串失败!" + e);
		}
		return base64Str;
	}

    	/**
	 * base64把文件转成字符串
	 * @param uploadFile1
	 * @return
	 */
	private String fileToString(File uploadFile1) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(uploadFile1);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 4];
			int n = 0;
			while ((n = fis.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			byte[] data = out.toByteArray();
			return byteArrayToString(data);
		} catch (IOException e) {
			LoggerUtil.info(logger, "base64转文件为字符串失败" + e);
			return null;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					LoggerUtil.info(logger, "关流失败" + e);
				}
			}
		}
	}
	

	/**
	 * 根据url获取图片的字节数组
	 * @author xionghao5 2018年8月30日 下午5:06:31
	 * @param strUrl
	 * @return
	 * @since 2.1
	 */
	private byte[] getImageFromNetByUrl(String strUrl) {
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(time_out);
			InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
			byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
			return btImg;
		} catch (Exception e) {
			LoggerUtil.info(logger, "图片读取失败" + e);
		}
		return null;
	}

	/**
	 * base64把字节数组转成字符串
	 * @author xionghao5 2018年8月30日 下午5:10:47
	 * @param data
	 * @return
	 * @since 2.1
	 */
	private String byteArrayToString(byte[] data) {
		try {
			String encode = new BASE64Encoder().encode(data);
			return encode;
		} catch (Exception e) {
			LoggerUtil.info(logger, "字节数组转base64字符串失败" + e);
			return null;
		}
	}

3.2base64字符串转图片 

图片base64字符串解码成字节数组,再转成文件

	/**
	 * base64解码并生成文件
	 * @param srcImageStr
	 * @param srcImage
	 * @param temp
	 * @return
	 */
	private boolean strConvertImageByBase64(String srcImageStr, File srcImage) {
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(srcImageStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			out = new FileOutputStream(srcImage);
			out.write(b);
			out.flush();
			return true;
		} catch (Exception e) {
			LoggerUtil.info(logger, "解码生成图片失败" + e);
			return false;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LoggerUtil.info(logger, "关流失败" + e);
				}
			}
		}
	}

如果有开头,去掉开头

图片格式判断

4.配置文件

@value

类统一管理

@Component
public class TrajectoryConfig {
    @Value("${trajectory_static_time}")
    private int staticTime; // 静止不动时间,单位:分钟

    public int getStaticTime() {
        return staticTime;
    }
}

config.properties(springboot在application.properties中)

trajectory_static_time=10

使用

    @Autowired
    private TrajectoryConfig trajectoryConfig;

    public void clearCustomInDataCenter() {
        try {
            vipInnerEmapInfoService.clearCustomInDataCenter(trajectoryConfig.getStaticTime());
        } catch (SQLException e) {
            LOGGER.error("清理数据中心的人员报错", e);
        }
        LOGGER.info("定期清理数据中心的人员");
    }

 

5.mysql索引

经常会遇到项目上线后的查询性能问题.通过添加索引可以提高查询速度

SELECT * FROM information_schema.columns WHERE table_schema='ivms8100v3' AND table_name = 'vip_infolog' 
AND column_name = 'server_time'; -- 查看字段

SELECT * FROM information_schema.statistics WHERE table_schema='ivms8100v3' AND table_name = 'vip_infolog' 
AND index_name = 'server_time'  -- 查看索引

alter table vip_infolog add index(server_time); -- 添加索引

DROP INDEX server_time ON vip_infolog           -- 删除索引

6.枚举

public enum CustomTypeEnum {
    /**
     * 1-帅哥
     */
    HANDSOME_MAN(1, "帅哥"),
    /**
     * 2-美女
     */
    BEAUTIFUL_WOMAN(2, "美女"),
    /**
     * 3-老头
     */
    OLD_MAN(3, "老头"),
    /**
     * 4-有钱人
     */
    RICH_MAN(4, "有钱人"),
    /**
     * 5-小孩
     */
    CHILD(5, "小孩"),
    ;
    private int code;
    private String msg;
    private static final Map<Integer, String> customTypeMap = new HashMap<>();

    CustomTypeEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    static {
        CustomTypeEnum[] values = CustomTypeEnum.values();
        for (CustomTypeEnum value : values) {
            customTypeMap.put(value.getCode(), value.getMsg());
        }
    }

    /**
     * 根据code获取msg
     *
     * @param code
     * @return
     */
    public static String getMsgByCode(int code) {
        return customTypeMap.get(code);
    }


    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

7.基本开发功能总结

1.多条件查询的分页页面

多条件查询,添加,删除,修改,分页;参数校验;事务;查询时的多条件校验;添加时的查重,关联,修改时的查重,关联;删除时的查重

2.poi导入导出

导入,导出,参数校验,excel,csv的格式

3.树形结构

sql加上path字段和sort字段,避免递归查询

sort字段的上下移动

4.提供接口,调用第三方接口

5.权限shiro,spring security

单点登录,权限设计

6.redis

redis的缓存,如何引入,如何使用

7.activeMq

消息中间件,如何引入,如何使用

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值