要求:读取xml文件并在页面中显示出来。
采用三种方式实现,并体会其中的原理:
1.常规方式,controlller控制器不分层
代码:@RestController
public class PoetController {
@RequestMapping("/listPoet")
public Result list(){
String file = this.getClass().getClassLoader().getResource("poet.xml").getFile();
System.out.println(file);
List<Poet> poetList= XmlParserUtils.parse(file, Poet.class);
poetList.stream().forEach(poet ->{
String gender=poet.getGender;
if("1".equals(gender)){
poet.setGender("男");
}
else if("2".equals(gender)){
poet.setGender("女");
}
});
return Result.success(poetList);
}
}
2.按照MVC的分层方式实现,常规java代码方式
3.采用控制反转和依赖注入的MVC方式实现。
代码:@Component
public class PoetDaoA implements PoetDao {
@Override
public List<Poet> listPoet() {
String file=this.getClass().getClassLoader().getResource("poet.xml").getFile();
System.out.println(file);
List<Poet> poetList= XmlParserUtils.parse(file,Poet.class);
System.out.println(poetList);
return poetList;
}
}
@Component
public class PoetServiceA implements PoetService {
@Autowired
private PoetDao poetDao;
@Override
public List<Poet> listPoet() {
List<Poet> poetList=poetDao.listPoet();
poetList.stream().forEach(poet -> {
String gender = poet.getGender;
if ("1".equals(gender)) {
poet.setGender("男");
} else if ("2".equals(gender)) {
poet.setGender("女");
}
});
return poetList;
}
}
@RestController
public class PoetController {
private PoetService poetService;
@RequestMapping("/poetlist2")
public Result list(){
List<Poet> poetList=poetService.listPoet();
return Result.success(poetList);
}
}