Detailed explanation of web service interface development (with complete process demo)

abstract

Because the company has a lot of business with third-party systems, it uses webservice for docking. The project framework in this paper is built by SSH, and other frameworks can also refer to the specific use process. The demos in this paper pass the test and are successfully released. If necessary, they can be directly copied and modified according to their own business needs. The demos here can only give you a reference, You can't copy. No more nonsense, go straight to the code. Partners in need can refer to it.

preparation

  1. Download the jar package required by cfx (using cfx mode)

    1.1 download address: Click ---- > apache-cxf-2.6.16 to download
    1.2 after downloading, unzip it and put it into the project lib directory for recompilation, as shown in the following figure

step

Step 1: configure webservice in the project as follows:

1. Create service WS XML, as follows:

<?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:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	
	http://cxf.apache.org/jaxws 
    http://cxf.apache.org/schemas/jaxws.xsd">
	
	<import resource="classpath:META-INF/cxf/cxf.xml"/>
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
	
	<!-- Enterprise information synchronization interface -->
	<bean id="companyImpl" class="com.hontek.webservice.service.impl.CompanyImpl">
		<property name="interAccountDao" ref="interAccountDao"/>
		<property name="enterpriseDao" ref="enterpriseDao"/>
		<property name="proTypeDao" ref="proTypeDao"/>
		<property name="proTypeQrcodeDao" ref="proTypeQrcodeDao"/>
		<property name="enterprseService" ref="enterprseService"/>
		<property name="proTypeBatchDao" ref="proTypeBatchDao"/>
		<property name="orderService" ref="orderService"/>
		<property name="zizhiDao" ref="zizhiDao"/>
		<property name="zizhiTypeDao" ref="zizhiTypeDao"/>
		<property name="zizhiAppendixDao" ref="zizhiAppendixDao"/>
		<property name="productServiceInter" ref="productService"/>
		<property name="traceService" ref="traceService"/>
		<property name="certificateDao" ref="certificateDao"/>
		<property name="certificateCheckDao" ref="certificateCheckDao"/>
		<property name="certificatePrintDao" ref="certificatePrintDao"/>
		<property name="certificateScanDao" ref="certificateScanDao"/>
		
	</bean>
	
	<jaxws:server serviceClass="com.hontek.webservice.service.inter.CompanyInter" address="/company">
		<jaxws:serviceBean>
			<ref bean="companyImpl"/>
		</jaxws:serviceBean>
	</jaxws:server>


	<!-- Test equipment interface -->
	<bean id="detectionDeviceImpl" class="com.hontek.devicewebservice.service.impl.DetectionDeviceImpl">
		<property name="userDao" ref="userDao"/>
		<property name="enterpriseDao" ref="enterpriseDao"/>
		<property name="checkEquipmentDao" ref="checkEquipmentDao"/>
		<property name="proTypeQrcodeDao" ref="proTypeQrcodeDao"/>
		<property name="checkInfoDao" ref="checkInfoDao"/>
		<property name="checkInfoDetailDao" ref="checkInfoDetailDao"/>
		<property name="proTypeDao" ref="proTypeDao"/>
		<property name="spotCheckDao" ref="spotCheckDao"/>
		<property name="orderService" ref="orderService"/>
		<property name="dimennoRecordService" ref="dimennoRecordService"/>
		<property name="certificateService" ref="certificateServiceInter"/>
		<property name="caInfoDao" ref="caInfoDao"/>
		<property name="certificateCheckDao" ref="certificateCheckDao"/>
	</bean>

	<jaxws:server serviceClass="com.hontek.devicewebservice.service.inter.DetectionDeviceInter" address="/detectionDevice">
		<jaxws:serviceBean>
			<ref bean="detectionDeviceImpl"/>
		</jaxws:serviceBean>
	</jaxws:server>

	<!-- Docking interface of Shenzhen product and vegetable basket platform -->
	<bean id="platformsImpl" class="com.hontek.platformswebservice.service.impl.PlatformsImpl">
		<property name="interAccountDao" ref="interAccountDao"/>
		<property name="enterprseService" ref="enterprseService"/>
		<property name="certificateServiceInter" ref="certificateServiceInter"/>
		<property name="proTypeDao" ref="proTypeDao"/>
		<property name="enterpriseDao" ref="enterpriseDao"/>
		<property name="proTypeQrcodeDao" ref="proTypeQrcodeDao"/>
		<property name="caInfoDao" ref="caInfoDao"/>
		<property name="userDao" ref="userDao"/>
		<property name="spotCheckDao" ref="spotCheckDao"/>
		<property name="checkReportDao" ref="checkReportDao"/>
		<property name="checkContentDao" ref="checkContentDao"/>
		<property name="xydaAppendixDao" ref="xydaAppendixDao"/>
		<property name="checkInfoDao" ref="checkInfoDao"/>
		<property name="checkInfoDetailDao" ref="checkInfoDetailDao"/>
	</bean>

	<jaxws:server serviceClass="com.hontek.platformswebservice.service.inter.PlatformsInter" address="/platform">
		<jaxws:serviceBean>
			<ref bean="platformsImpl"/>
		</jaxws:serviceBean>
	</jaxws:server>
	
	
	
</beans> 

apache-cxf-2.6.16 needs to add the following three lines to the above configuration file

	<import resource="classpath:META-INF/cxf/cxf.xml"/>
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

Note: if your version is above 3.0, you will also report an error because of the following two xml files; You only need to introduce the first one; If your CXF version is below 3.0; Then three configuration files need to be introduced.

2. Configure ApplicationContext XML, as follows:

	<!-- webservice Interface profile -->
	<import resource="config/webservice/application/service-ws.xml"/>

3. Configure web XML, as follows:

  <servlet>
    <servlet-name>CXFService</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CXFService</servlet-name>
    <url-pattern>/CXFService/*</url-pattern>
  </servlet-mapping>

Step 2: create a webservice interface, as follows:

package com.hontek.platformswebservice.service.inter;
import com.hontek.platformswebservice.comm.*;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import java.util.List;

@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
public interface PlatformsInter {
	
	/**
	 * Get password
	 * @Author yang
	 * @Date   2020/05/06 16:55
	 **/
	public String getToken(@WebParam(name="account")String account,@WebParam(name="password")String password);

	/**
	 * Update heartbeat interface
	 * @Author yang
	 * @Date   2020/05/06 16:59
	 **/
	public String active(@WebParam(name = "token") String token);

	/**
	 * Exit interface
	 * @Author yang
	 * @Date   2020/05/06 16:59
	 **/
	public String logout(@WebParam(name = "token") String token);

	/**
	 * Synchronize product information
	 * @Author yang
	 * @Date   2020/05/07 18:07
	 **/
	public String syncProTypeQrCode(@WebParam(name="token")String token, @WebParam(name="proTypeQrcode") ProTypeQrcodeEntity proTypeQrcode);
}

The above webservice interfaces use RPC mode and include the security verification interfaces required for system docking (obtaining token, updating heartbeat and exiting can be modified according to your own needs)

Step 3: create a webservice implementation class, as follows

package com.hontek.platformswebservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.hontek.certificate.dao.CaInfoDao;
import com.hontek.certificate.pojo.CaInfo;
import com.hontek.certificate.pojo.Certificate;
import com.hontek.certificate.service.inter.CertificateServiceInter;
import com.hontek.comm.util.DateUtil;
import com.hontek.comm.util.DirectoryUtil;
import com.hontek.comm.util.IDUtil;
import com.hontek.comm.util.StringUtil;
import com.hontek.company.dao.CheckContentDao;
import com.hontek.company.dao.CheckReportDao;
import com.hontek.company.dao.SpotCheckDao;
import com.hontek.company.dao.XydaAppendixDao;
import com.hontek.company.pojo.CheckContent;
import com.hontek.company.pojo.CheckReport;
import com.hontek.company.pojo.SpotCheck;
import com.hontek.company.pojo.XydaAppendix;
import com.hontek.detectiondevice.comm.DetectionReportUtils;
import com.hontek.detectiondevice.dao.CheckInfoDao;
import com.hontek.detectiondevice.dao.CheckInfoDetailDao;
import com.hontek.detectiondevice.pojo.CheckInfo;
import com.hontek.detectiondevice.pojo.CheckInfoDetail;
import com.hontek.platformswebservice.comm.*;
import com.hontek.platformswebservice.service.inter.PlatformsInter;
import com.hontek.record.dao.ProTypeQrcodeDao;
import com.hontek.record.pojo.TbProTypeQrcode;
import com.hontek.review.dao.ProTypeDao;
import com.hontek.review.pojo.TbProType;
import com.hontek.sys.dao.EnterpriseDao;
import com.hontek.sys.dao.InterAccountDao;
import com.hontek.sys.dao.UserDao;
import com.hontek.sys.pojo.TbInterAccount;
import com.hontek.sys.pojo.TsEnterprise;
import com.hontek.sys.pojo.TsUser;
import com.hontek.sys.service.inter.EnterpriseServiceInter;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@WebService
@SOAPBinding(style = Style.RPC)
public class PlatformsImpl implements PlatformsInter {


	private Logger logger = Logger.getLogger(PlatformsImpl.class);

	private InterAccountDao interAccountDao;
	private EnterpriseServiceInter enterprseService;
	private CertificateServiceInter certificateServiceInter;
	private ProTypeDao proTypeDao;
	private EnterpriseDao enterpriseDao;
	private ProTypeQrcodeDao proTypeQrcodeDao;
	private CaInfoDao caInfoDao;
	private UserDao userDao;


	public void setInterAccountDao(InterAccountDao interAccountDao) { this.interAccountDao = interAccountDao; }
	public void setEnterprseService(EnterpriseServiceInter enterprseService) { this.enterprseService = enterprseService; }
	public void setCertificateServiceInter(CertificateServiceInter certificateServiceInter) { this.certificateServiceInter = certificateServiceInter; }
	public void setProTypeDao(ProTypeDao proTypeDao) { this.proTypeDao = proTypeDao; }
	public void setEnterpriseDao(EnterpriseDao enterpriseDao) { this.enterpriseDao = enterpriseDao; }
	public void setProTypeQrcodeDao(ProTypeQrcodeDao proTypeQrcodeDao) { this.proTypeQrcodeDao = proTypeQrcodeDao; }
	public void setCaInfoDao(CaInfoDao caInfoDao) { this.caInfoDao = caInfoDao; }
	public void setUserDao(UserDao userDao) { this.userDao = userDao; }


	@Resource
	private WebServiceContext context;

	private HttpServletRequest getRequest(){
		MessageContext ctx = context.getMessageContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(AbstractHTTPDestination.HTTP_REQUEST);
		return request;
	}


	@Override
	public String getToken(String account, String password) {
		logger.info("-----obtain token start-----");
		ResultInfo result = new ResultInfo();
		result.setSuccess(false);
		try {
			if(account!=null&&!"".equals(account)&&password!=null&&!"".equals(password)){
				// Here, the account information is obtained according to the account and password, which can be modified according to your business needs
				String condition = " and account='"+account+"' and pass='"+password+"'";
				TbInterAccount interAccount = interAccountDao.getInterAccount(condition);
				if(interAccount!=null){
					String token = UUID.randomUUID().toString().replace("-", "");
					SoleManager manager = SoleManager.getInstance();
					interAccount.setTime(System.currentTimeMillis());
					manager.putAccount(token, interAccount);
					result.setCode("1000");
					result.setMsg("obtain token success");
					result.setData(token);
					result.setSuccess(true);
				}else {
					result.setCode("1003");
					result.setMsg("Wrong account or password");
				}
			}else {
				result.setCode("1002");
				result.setMsg("Account or password is empty");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("obtain token Failed:"+e.getMessage());
			result.setCode("1001");
			result.setMsg("obtain token fail");
		}
		return JSONObject.fromObject(result).toString();
	}

	@Override
	public String active(String token) {
		logger.info("-----Update heartbeat start-----");
		SoleManager manager = SoleManager.getInstance();
		TbInterAccount account = manager.getAccount(token);
		ResultInfo result = new ResultInfo();
		result.setSuccess(false);
		if(account != null){
			account.setTime(System.currentTimeMillis());
			result.setSuccess(true);
			result.setCode("1000");
			result.setMsg("Update heartbeat succeeded");
		}else {
			result.setCode("1004");
			result.setMsg("The token is invalid");
		}
		return JSONObject.fromObject(result).toString();
	}

	@Override
	public String logout(String token) {
		SoleManager manager = SoleManager.getInstance();
		TbInterAccount account = manager.getAccount(token);
		ResultInfo result = new ResultInfo();
		if(account != null){
			manager.cleanMap(token);
		}
		result.setSuccess(true);
		result.setCode("1000");
		result.setMsg("Exit successful");
		return JSONObject.fromObject(result).toString();
	}

	@Override
	public String syncCompanyInfo(String token, CompanyEntity company) {
		logger.info("-----Synchronize enterprise information-----");
		ResultInfo result = new ResultInfo();
		result.setSuccess(false);
		SoleManager manager = SoleManager.getInstance();
		TbInterAccount account = manager.getAccount(token);
		if(account != null){
			try {
				//Update heartbeat
				manager.active(account);
				if(company != null){
					TsEnterprise ent = new TsEnterprise();
					ent.setParentId(account.getEntId());
					ent.setName(company.getCompanyName());
					ent.setIntro(company.getIntro());
					ent.setOrgCode(company.getOrgCode());
					ent.setLegalPerson(company.getLegalPerson());
					ent.setRegAddr(company.getRegAddr());
					ent.setManageAddr(company.getManagerAddr());
					ent.setEmail(company.getEmail());
					ent.setDomName(company.getDomName());
					ent.setCrtUserId(account.getUserId());
					ent.setFlag("3");//Set as enterprise
					ent.setSts("0");
					ent.setIsReported("1");//Set as reporting enterprise
					ent.setEntType(Integer.parseInt(company.getEntType()==null?"2":company.getEntType()));//The default setting is private enterprise 2
					ent.setCrtDt(DateUtil.formatDateTime());
					ent.setMobile(company.getMobile());
					ent.setSysCode(account.getSysCode());
					ent.setOldEntId(company.getCompanyId());
					ent.setAreaName(company.getAreaName());
					ent.setQualificationType(company.getQualificationType());
					ent.setBusiness(company.getBusiness());
					ent.setPurl("");
					ent.setMurl("");
					Map<String, String> restMap = enterprseService.addSynchCompanyInfo(ent,getRequest());

					String flag = restMap.get("flag");
					if(flag!=null&&"0".equals(flag)){
						result.setCode("1000");
						result.setSuccess(true);
						result.setMsg("Enterprise data synchronization succeeded");
					}else if(flag!=null&&"2".equals(flag)){
						result.setCode("1000");
						result.setSuccess(true);
						result.setMsg("Enterprise already exists, update enterprise data successfully");
					}else if(flag!=null&&"3".equals(flag)){
						result.setCode("1005");
						result.setMsg("Failed to synchronize enterprise data");
					}else {
						result.setCode("1006");
						result.setMsg("Parameter error");
					}
				}
			}catch (Exception e){
				e.printStackTrace();
				result.setCode("1007");
				result.setMsg("Enterprise data synchronization exception");
				logger.info(e.getMessage());
			}
		}else {
			result.setCode("1008");
			result.setMsg("Login timeout,Please log in again");
		}
		return JSONObject.fromObject(result).toString();
	}

	@Override
	public String syncProTypeQrCode(String token, ProTypeQrcodeEntity proTypeQrcode) {
		logger.info("-----Synchronize product information-----");
		ResultInfo result = new ResultInfo();
		result.setSuccess(false);
		SoleManager manager = SoleManager.getInstance();
		TbInterAccount account = manager.getAccount(token);
		if(account != null){
			try {
				//Update heartbeat
				manager.active(account);
				String entId = String.valueOf(proTypeQrcode.getCompanyId());
				TsEnterprise enterprise = enterpriseDao.findEnterpriseBySysCodeAndOldEndId(account.getSysCode(), entId);
				if(enterprise!=null){
					if(proTypeQrcode != null){
						TbProTypeQrcode proTypeQrcode2 = new TbProTypeQrcode();
						proTypeQrcode2.setTypeId(Integer.parseInt(proTypeQrcode.getTypeId()));
						proTypeQrcode2.setProName(proTypeQrcode.getProName());
						proTypeQrcode2.setSysCode(account.getSysCode());
						proTypeQrcode2.setOldPtqId(String.valueOf(proTypeQrcode.getPtqId()));
						proTypeQrcode2.setOldDimenno(proTypeQrcode.getProCode());
						proTypeQrcode2.setProDesc(proTypeQrcode.getProDesc());
						//Check for data
						int count = proTypeQrcodeDao.countBySql("select count(*) from tb_pro_type_qrcode where sys_code='"+account.getSysCode()+"' and old_ptq_id='"+proTypeQrcode.getPtqId()+"'");
						if(count==0){
							proTypeQrcode2.setEntId(enterprise.getEntId());
							String ptqIdStr  = IDUtil.getPrimaryID();
							proTypeQrcode2.setPtqId(ptqIdStr);
							//Generate QR code
							String dimenno = "";
							dimenno = enterprise.getEntCode();//entCode = 6-digit administrative region code + 6-digit (provincial) sequence code
							String dimennoSeq = "01";
							String maxDimenno = proTypeQrcodeDao.findMaxDimennoByEntId(enterprise.getEntId());
							String lastTwoStr="";
							if(maxDimenno!=null&&!"".equals(maxDimenno)){
								lastTwoStr = maxDimenno.substring(maxDimenno.length()-2);
								dimennoSeq = StringUtil.getPtqLastTwoStr(lastTwoStr);
							}
							if("Z9".equals(dimennoSeq)){
								result.setCode("1010");
								result.setMsg("The quantity of products exceeds the allowable range of the system!");
							}else{
								dimenno += dimennoSeq;
								proTypeQrcode2.setDimenno(dimenno);
								proTypeQrcode2.setCrrtime(DateUtil.formatDateTime());
								logger.info("Sync product:"+ JSON.toJSONString(proTypeQrcode2));
								proTypeQrcodeDao.save(proTypeQrcode2);
								result.setSuccess(true);
								result.setCode("1000");
								result.setMsg("Product data synchronization succeeded!");
								result.setData(ptqIdStr);

							}
						}else {
							TbProTypeQrcode typeQrcode = proTypeQrcodeDao.getProTypeQrcode(" and sysCode = '"+account.getSysCode()+"' and oldPtqId = '"+proTypeQrcode.getPtqId()+"'");
							logger.info("The product has been synchronized:"+JSON.toJSONString(proTypeQrcode));
							result.setCode("1011");
							result.setMsg("The product has been synchronized!");
							result.setData(typeQrcode.getPtqId());
						}
					}
				}else {
					logger.info("Failed to synchronize product, the enterprise is not synchronized:"+JSON.toJSONString(proTypeQrcode));
					result.setCode("1012");
					result.setMsg("Failed to synchronize products. The enterprise is not synchronized!");
				}
			}catch (Exception e){
				e.printStackTrace();
				result.setCode("1013");
				result.setMsg("Abnormal synchronization of product data");
				logger.info(e.getMessage());
			}
		}else {
			result.setCode("1008");
			result.setMsg("Login timeout,Please log in again");
		}
		return JSONObject.fromObject(result).toString();
	}

	
}


3.1 create a ResultInfo return result entity class, as follows:

package com.hontek.platformswebservice.comm;

/**
 * Return result entity class
 * @Author yang
 **/
public class ResultInfo {

	private String code;		//Code code
	private boolean success;	// Judge whether the call is successful true: success false: failure
	private Object data;		// data
	private String msg;			// information

	public String getCode() { return code; }
	public void setCode(String code) { this.code = code; }
	public boolean isSuccess() { return success; }
	public void setSuccess(boolean success) { this.success = success; }
	public Object getData() { return data; }
	public void setData(Object data) { this.data = data; }
	public String getMsg() { return msg; }
	public void setMsg(String msg) { this.msg = msg; }

}

3.1 create a SoleManager thread class to implement token expiration time, update and destroy, as follows:

package com.hontek.platformswebservice.comm;

import com.hontek.sys.pojo.TbInterAccount;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class SoleManager {

	static final private SoleManager instance = new SoleManager();

	private Map<String, TbInterAccount> accountMap = new HashMap<String, TbInterAccount>();

	public static SoleManager getInstance(){
		return instance;
	 }

	public SoleManager() {
		TimeOut timeout = new TimeOut();
		timeout.start();
	}
	
	synchronized public TbInterAccount getAccount(String token){
		TbInterAccount interAccount = accountMap.get(token);
		if(interAccount!=null)
			interAccount.setTime(System.currentTimeMillis());
		return interAccount;
	}
	
	synchronized public void putAccount(String token,TbInterAccount interAcount){
		this.accountMap.put(token, interAcount);
	}

	
	public class TimeOut extends Thread{
		public void run(){
			long keepTime = 1000L*60*60*10;
			
			while(true){
				try {
					Thread.sleep(1000*60*60*3);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				Set<String> setKey = accountMap.keySet();
				Iterator<String> it = setKey.iterator();
				while(it.hasNext()){
					String key = it.next();
					TbInterAccount interAccount = accountMap.get(key);
					if(System.currentTimeMillis()-interAccount.getTime()>keepTime){
						accountMap.remove(key);
					}
				}
				
			}
		}
	}
	
	/**
	 * heartbeat
	 * @param interaccount
	 */
	public void active(TbInterAccount interaccount){
		if(interaccount!=null){
			interaccount.setTime(System.currentTimeMillis());
		}
	}
	/**
	 * cancellation
	 * @param token
	 */
	synchronized public void cleanMap(String token){
		TbInterAccount interAccount = accountMap.get(token);
		if(interAccount!=null){
		    interAccount = null;
		    accountMap.remove(token);
		}
	}
}

Step 4: publish

*Access path: domain name/project/CXFService/platform?wsdl,Appear as follows xml The data description in format is published successfully*


Step 5: Test

5.1 create a webservice client in idea for testing, as follows:



5.2 use test tools such as postman and SoapUI Pro 5.1.2 to test, as shown in soapui:

Step 6: Summary:

After the interface is written in the early stage, first test the code to see if there is any problem and whether the interface can be adjusted. If there is no problem, it is best to write a docking document to explain (as shown in the figure below). When docking with the three parties, first conduct joint debugging in the test environment or your own local server (use intranet penetration, I use peanut shell for intranet penetration), Finally, it is released to the formal environment.

Welcome to leave a message and comment. If you need a complete code, add me QQ: 450938667

Keywords: Java ssh webservice

Added by jbloom on Sat, 15 Jan 2022 08:39:03 +0200