MVC分层方式读取xml文件并在页面显示
一、com.example.demo下创建dao包和service包
二、dao包(访问数据)下创建interface接口(poetDao)和imple包(存实现类poetDaoA)
poetDao代码如下:
package com.example.demo.dao;
import com.example.demo.pojo.poet;
import java.util.List;
public interface poetDao {
public List<poet> listpoet();
}
poetDaoA代码如下:
package com.example.demo.dao.imple;
import com.example.demo.dao.poetDao;
import com.example.demo.pojo.poet;
import com.example.demo.utils.poetParseUtils;
import java.util.List;
public class poetDaoA implements poetDao {
@Override
public List<poet> listpoet(){
//1. 加载并解析emp.xml
String file = this.getClass().getClassLoader().getResource("poem.xml").getFile();
List<poet> poetList = poetParseUtils.parse(file, poet.class);
return poetList;
}
}
三、service包(处理数据)下创建interface接口(poetServica)和imple包(存实现类poetServiceA)
poetServica代码如下:
package com.example.demo.service;
import com.example.demo.pojo.poet;
import java.util.List;
public interface poetService {
public List<poet> listpoet();
}
poetServicaA代码如下:
package com.example.demo.service.imple;
import com.example.demo.dao.imple.poetDaoA;
import com.example.demo.dao.poetDao;
import com.example.demo.pojo.poet;
import com.example.demo.service.poetService;
import java.util.List;
public class poetServiceA implements poetService {
private poetDao poetdao = new poetDaoA();
@Override
public List<poet> listpoet() {
List<poet> poetList = poetdao.listpoet();
//2. 对数据进行转换处理 - gender
poetList.stream().forEach(writer -> {
//处理 gender 1: 男, 2: 女
String gender = writer.getGender();
if ("1".equals(gender)) {
writer.setGender("男");
} else if ("2".equals(gender)) {
writer.setGender("女");
}
});
return poetList;
}
}
四、poetController(响应和响应数据)
poetController代码如下:
package com.example.demo.controller;
import com.example.demo.pojo.poet;
import com.example.demo.pojo.Result;
import com.example.demo.service.imple.poetServiceA;
import com.example.demo.service.poetService;
import com.example.demo.utils.poetParseUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class poetController {
private poetService poetservice=new poetServiceA();
@RequestMapping("/poet")
public Result list(){
List<poet> poetList=poetservice.listpoet();
return Result.success(poetList);
}
}
五、浏览器输入localhost:8080/poet.html