1.创建Device实体类
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class Device implements Serializable {
private String devName;
private Integer devID;
private String image;
private String userName;
private String devState;
}
创建DeviceService接口 并声明两个方法
一个用于读取并解析xml文件,一个用于状态转换
import com.baomidou.mybatisplus.extension.service.IService;
import com.marcel.iotplatform.pojo.Device;
import java.util.List;
public interface DeviceService extends IService<Device> {
List<Device> getXml(String file);
List<Device> transferState(List<Device> devList);
}
创建DeviceServiceImpl实现类 并实现接口中声明的方法
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marcel.iotplatform.Mapper.DeviceMapper;
import com.marcel.iotplatform.Service.DeviceService;
import com.marcel.iotplatform.Utils.XmlParserUtils;
import com.marcel.iotplatform.pojo.Device;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {
@Override
public List<Device> getXml(String url) {
String file=this.getClass().getClassLoader().getResource(url).getFile();
return XmlParserUtils.parse(file, Device.class);
}
@Override
public List<Device> transferState(List<Device> devList) {
devList.stream().forEach(dev -> {
//处理 DevState 1: 开, 0: 关
String state = dev.getDevState();
if("1".equals(state)){
dev.setDevState("开");
}else if("0".equals(state)){
dev.setDevState("关");
}
});
return devList;
}
}
在DeviceController中@Autowired DeviceService 即可调用xml解析和状态转换方法
import com.marcel.iotplatform.Common.Result;
import com.marcel.iotplatform.Service.DeviceService;
import com.marcel.iotplatform.Utils.XmlParserUtils;
import com.marcel.iotplatform.pojo.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/hw2")
public class DeviceController {
@Autowired
private DeviceService deviceService;
@GetMapping("/listDev")
public Result list(){
List<Device> devList = deviceService.getXml("devices.xml");
devList=deviceService.transferState(devList);
return Result.success(devList);
}
}
运行SpringBoot项目 打开浏览器 转到localhost:8080/dev.html
前端页面成功显示