我正在学习Web服务,目前我正在学习Tomcate6.0环境中的JAXB。我有一个xml文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user>
<email>bill@hotmail.com</email>
<name>Bill Gates</name>
<password>blahblah</password>
<gender>male</gender>
</user>
<user>
<email>joe@bloggs.com</email>
<name>Joe Bloggs</name>
<password>foobar</password>
<gender>male</gender>
</user>
</users>
,此文件位于WEB-INF / users.xml。
我有一个名为Blog.java的类,它有两个字段:
private Users users;
private String filePath;
在本课程中我有这个方法:
public void setFilePath(String filePath) throws JAXBException, IOException {
this.filePath = filePath;
JAXBContext jc = JAXBContext.newInstance(Users.class);
Unmarshaller u = jc.createUnmarshaller();
FileInputStream fin = new FileInputStream(filePath);
this.users = (Users)u.unmarshal(fin);
fin.close();
}
设置路径和用户。
这个方法:
public void saveUser(String filePath) throws JAXBException, FileNotFoundException {
// Boilerplate code to convert objects to XML...
JAXBContext jc = JAXBContext.newInstance(Users.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileOutputStream fos = new FileOutputStream(filePath);
m.marshal(users, fos);
}
写入给定的“filePath”中的xml文件。
最后在我的注册页面中,我收集了用户数据,然后在另一个我编码的页面中注册用户:
....
<% String filePath = application.getRealPath("WEB-INF/users.xml");%>
....
User user = new User(....);
Blog blog = new Blog();
blog.setFilePath(filePath);
blog.getUsers().addUser(user);//this is a method in Users class to add a user to a list
blog.saveUser(filePath);
....
但是,这根本不会更改WEB-INF / users.xml中的users.xml文件。任何人都可以在我错过的地方给我一些建议。
谢谢