准备工作:
首先导入poet.xml文件,并为其创建一个xml解析工具XmlParserUtils(需要导入org.dom4j包,在pom文件中提前配置org.dom4j依赖),还有poet的实体类,定义好相关属性并为其创建一系列方法,随后创建Result类用于统一返回响应结果:
我这里创建Result和Poet类时利用了Lombok注解,需要在创建文件时提前导入。
Result类:
package edu.wust.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
private Integer code ;//1 成功 , 0 失败
private String msg; //提示信息
private Object data; //数据 date
public static Result success(Object data){
return new Result(1, "success", data);
}
public static Result success(){
return new Result(1, "success", null);
}
public static Result error(String msg){
return new Result(0, msg, null);
}
}
Poet类(由于后续性别转化过程中需要用到字符串转化,因此这里直接使用String类型的gender变量):
package edu.wust.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Poet {
private String author;
private String gender;
private String dynasty;
private String title;
private String style;
}
随后创建service、dao、controller包,并配置相关文件:
前端程序:
(使用异步请求获取数据,基于Vue框架使用插值表达式创建表格)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>poet information display</title>
</head>
<script src="./js/vue.js"></script>
<script src="./js/axios-0.18.0.js"></script>
<body>
<h1 align="center">诗人信息列表展示</h1>
<div id="app">
<table style="width: 100%; border-collapse: collapse; border: 1px solid black;">
<thead>
<tr>
<th style="text-align: center; min-width: 20%;">编号</th>
<th style="text-align: center; min-width: 20%;">姓名</th>
<th style="text-align: center; min-width: 20%;">性别</th>
<th style="text-align: center; min-width: 20%;">朝代</th>
<th style="text-align: center; min-width: 20%;">头衔</th>
<th style="text-align: center; min-width: 20%;">风格</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in tableData">
<td style="text-align: center; border: 1px solid black;">{{ index+1}}</td>
<td style="text-align: center; border: 1px solid black;">{{ item.author }}</td>
<td style="text-align: center; border: 1px solid black;">{{ item.gender }}</td>
<td style="text-align: center; border: 1px solid black;">{{ item.dynasty }}</td>
<td style="text-align: center; border: 1px solid black;">{{ item.title }}</td>
<td style="text-align: center; border: 1px solid black;">{{ item.style }}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
new Vue({
el: "#app",
data() {
return {
tableData: []
}
},
mounted(){
axios.get('/poet').then(res=>{
if(res.data.code){
this.tableData = res.data.data;
}
});
},
methods: {
}
});
</script>
</html>
页面展示效果:
(使用element-ui组件库,提升界面美观程度)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>poet information display</title>
</head>
<link rel="stylesheet" href="element-ui/index.css">
<script src="./js/vue.js"></script>
<script src="./element-ui/index.js"></script>
<script src="./js/axios-0.18.0.js"></script>
<body>
<h1 align="center">诗人信息列表展示</h1>
<div id="app">
<el-table :data="tableData" style="width: 100%" stripe border >
<el-table-column prop="number" label="编号" align="center" min-width="20%"></el-table-column>
<el-table-column prop="author" label="姓名" align="center" min-width="20%"></el-table-column>
<el-table-column prop="gender" label="性别" align="center" min-width="20%"></el-table-column>
<el-table-column prop="dynasty" label="朝代" align="center" min-width="20%"></el-table-column>
<el-table-column prop="title" label="头衔" align="center" min-width="20%"></el-table-column>
<el-table-column prop="style" label="风格" align="center" min-width="20%"></el-table-column>
</el-table>
</div>
</body>
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
<script>
new Vue({
el: "#app",
data() {
return {
tableData: []
}
},
mounted(){
axios.get('/poet').then(res=>{
if(res.data.code){
this.tableData = res.data.data;
}
});
},
methods: {
}
});
</script>
</html>
xml解析方法:
xml解析方法是获取xml文件非常重要的部分
相关代码如下:
package utils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class XmlParserUtils {
public static <T> List<T> parse(String file , Class<T> targetClass) {
ArrayList<T> list = new ArrayList<T>(); //封装解析出来的数据
try {
//1.获取一个解析器对象
SAXReader saxReader = new SAXReader();
//2.利用解析器把xml文件加载到内存中,并返回一个文档对象
Document document = saxReader.read(new File(file));
//3.获取到根标签
Element rootElement = document.getRootElement();
//4.通过根标签来获取 user 标签
List<Element> elements = rootElement.elements("writer");
//5.遍历集合,得到每一个 user 标签
for (Element element : elements) {
//获取 name 属性
String author = element.element("author").getText();
//获取 age 属性
String gender = element.element("gender").getText();
//获取 image 属性
String dynasty = element.element("dynasty").getText();
//获取 gender 属性
String title = element.element("title").getText();
//获取 job 属性
String style = element.element("style").getText();
//组装数据
Constructor<T> constructor = targetClass.getDeclaredConstructor(String.class, String.class, String.class, String.class, String.class);
constructor.setAccessible(true);
T object = constructor.newInstance(author,gender,dynasty,title,style);
list.add(object);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
(由于作家是被<writer>标签页包围,因此要获取元素必须使用
List<Element> elements = rootElement.elements("writer"); )
controller:
代码:
package edu.wust.controller;
import edu.wust.pojo.Poet;
import edu.wust.pojo.Result;
import edu.wust.service.PoetService;
import edu.wust.service.impl.PoetServiceA;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.XmlParserUtils;
import java.util.List;
import java.util.Objects;
@RestController
public class PoetController {
@RequestMapping("/poet")
public Result list(){
//加载并解析poet.xml文件
String file=this.getClass().getClassLoader().getResource("poet.xml").getFile();
List<Poet> poetList = XmlParserUtils.parse(file, Poet.class);
//性别转化处理
poetList.forEach(poet->{
String gender=poet.getGender();
if("1".equals(gender)){
poet.setGender("男");
}else if("2".equals(gender)){
poet.setGender("女");
}
});
//响应数据
return Result.success(poetList);
}
}
运行调试:
使用postman发起请求后,可以看到listPoet已经获取到xml文件的元素了,不过此时获取到的是原始数据,没有进行处理:
再往下调试之后已经能够正常显示了:
运行:
编号问题解决方案
这里发现编号一列没有任何数据,有两种解决方案:
1.xml文件中没有编号数据,需要在解析器中手动编辑:
// 初始化编号
int number = 1;
//组装数据
Constructor<T> constructor = targetClass.getDeclaredConstructor(Integer.class, String.class, String.class, String.class, String.class, String.class);
constructor.setAccessible(true);
T object = constructor.newInstance(number, author, gender, dynasty, title, style);
// 将编号加一
number++;
list.add(object);
还需要在Poet实体类中添加一个Integer类型的number字段:
private Integer number;
2.使用v-for循环遍历poetData列表时,添加一个index索引(如上第一个html页面)
再次运行结果即为要求结果:
分层:
controller类:
package edu.wust.controller;
import edu.wust.pojo.Poet;
import edu.wust.pojo.Result;
import edu.wust.service.PoetService;
import edu.wust.service.impl.PoetServiceA;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.XmlParserUtils;
import java.util.List;
import java.util.Objects;
@RestController
public class PoetController {
private PoetService poetService=new PoetServiceA();
@RequestMapping("/poet")
public Result list(){
//1. 调用service, 获取数据
List<Poet> poetList = poetService.listPoet();
//3. 响应数据
return Result.success(poetList);
}
}
service类:
service接口:
package edu.wust.service;
import edu.wust.pojo.Poet;
import java.util.List;
public interface PoetService {
public List<Poet> listPoet();
}
serviceA实现类:
package edu.wust.service.impl;
import edu.wust.dao.PoetDao;
import edu.wust.dao.impl.PoetDaoA;
import edu.wust.pojo.Poet;
import edu.wust.service.PoetService;
import java.util.List;
public class PoetServiceA implements PoetService {
private PoetDao poetDao=new PoetDaoA();
List<Poet> poetList = poetDao.listPoet();
@Override
public List<Poet> listPoet() {
poetList.forEach(poet -> {
//处理 gender 1: 男, 2: 女
String gender = poet.getGender();
if ("1".equals(gender)) {
poet.setGender("男");
} else if ("2".equals(gender)) {
poet.setGender("女");
}
});
return poetList;
}
}
dao类:
dao接口:
package edu.wust.dao;
import edu.wust.pojo.Poet;
import java.util.List;
public interface PoetDao {
public List<Poet> listPoet();
}
daoA实现类 :
package edu.wust.dao.impl;
import edu.wust.dao.PoetDao;
import edu.wust.pojo.Poet;
import utils.XmlParserUtils;
import java.util.List;
import java.util.Objects;
public class PoetDaoA implements PoetDao {
@Override
public List<Poet> listPoet() {
//1. 加载并解析emp.xml
String file= Objects.requireNonNull(this.getClass().getClassLoader().getResource("poet.xml")).getFile();
System.out.println(file);
return XmlParserUtils.parse(file,Poet.class);
}
}
运行结果仍然正确
解耦:
将controller类中
private PoetService poetService=new PoerService();通过使用 @Autowired 注解,将 PoetService 的实例化过程交给Spring框架处理:
@Autowired private PoetService poetService;
PoetService实例化过程由Spring框架的IoC(控制反转)机制负责,需要在实体类PoetServiceA上添加 @Component 注解
同理PoetServiceA类中的
private PoetDao poetDao = new PoetDao();注入:
@Autowired private PoetDao poetDao;
在dao类中的实体类PoetDaoA类中加入 @Component 注解
以此来降低耦合性,提高代码可维护性。