XML操作举例→实现用户登录

XmlUtils.java
package cn.zyw.utils;



import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.UnsupportedEncodingException;



import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;



//3

public class XmlUtils {

    private static String filepath;

    static{

        filepath=XmlUtils.class.getClassLoader().getResource("users.xml").getPath();

        filepath=filepath.replace("%20", " ");

    }

    public static Document getDocument() throws Exception{

        SAXReader reader = new SAXReader();

        Document document = reader.read(new File(filepath));

        return document;

    }

    public static void write2Xml(Document document) throws Exception{

        OutputFormat format = OutputFormat.createPrettyPrint();

        format.setEncoding("UTF-8");

        XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format );

        writer.write( document );

        writer.close();

    }



}

 

有时我们想做做一个小的项目需要保存一定的数据,如果用数据库当然是可以的。但是总觉得有点浪费资源。所以今天就学习了一点Xml总结如下:

 

1:Xml文件如下:

users.xml
<?xml version="1.0" encoding="UTF-8"?>

<users>

    <user id="234343434" username="aaa" password="123" email="[email protected]" birthday="1900-09-18" nickname="强子" />

</users>


2:操作Xml文件的工具类

XmlUtils.java
package cn.zyw.utils;



import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.UnsupportedEncodingException;



import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;



//3

public class XmlUtils {

    private static String filepath;

    static{

        filepath=XmlUtils.class.getClassLoader().getResource("users.xml").getPath();

        filepath=filepath.replace("%20", " ");

    }

    public static Document getDocument() throws Exception{

        SAXReader reader = new SAXReader();

        Document document = reader.read(new File(filepath));

        return document;

    }

    public static void write2Xml(Document document) throws Exception{

        OutputFormat format = OutputFormat.createPrettyPrint();

        format.setEncoding("UTF-8");

        XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format );

        writer.write( document );

        writer.close();

    }



}

3:用户登录的Dao

UserDao .java
package cn.zyw.dao;



import cn.zyw.domain.User;

//5

public interface UserDao {



    void add(User user);



    User find(String username, String password);



    //查找注册的用户是否在数据库中存在

    boolean find(String username);



}

 

4:用户登录的实现类

UserDaoImpl .java
package cn.zyw.dao.impl;



import java.text.SimpleDateFormat;



import org.dom4j.Document;

import org.dom4j.Element;



import cn.zyw.dao.UserDao;

import cn.zyw.domain.User;

import cn.zyw.utils.XmlUtils;

//2

public class UserDaoImpl implements UserDao {

    public void add(User user){

        try {

            Document document=XmlUtils.getDocument();

            Element root=document.getRootElement();//得到根节点

            Element user_tag=root.addElement("user");

            user_tag.setAttributeValue("id", user.getId());

            user_tag.setAttributeValue("username", user.getUsername());

            user_tag.setAttributeValue("password", user.getPassword());

            user_tag.setAttributeValue("email", user.getEmail());

            user_tag.setAttributeValue("nickname", user.getNickname());

            user_tag.setAttributeValue("birthday", user.getBirthday()==null ? "" : user.getBirthday().toLocaleString());

            XmlUtils.write2Xml(document);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    public User find(String username,String password){



        try {

            Document document=XmlUtils.getDocument();

            Element e=(Element) document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");

            if(e==null)

                return null;

            User user=new User();

            user.setUsername(e.attributeValue("username"));//获取xml里面的值

            user.setNickname(e.attributeValue("nickname"));

            user.setPassword(e.attributeValue("password"));

            user.setEmail(e.attributeValue("email"));

            user.setId(e.attributeValue("id"));

            String date=e.attributeValue("birthday");

            if(date==null || date.equals("")){

                user.setBirthday(null);                

            }else{

                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

                user.setBirthday(df.parse(date));

            }

            return user;            

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    //查找注册的用户是否在数据库中存在

    public boolean find(String username){ 

        try {

            Document document=XmlUtils.getDocument();

            Element e=(Element) document.selectSingleNode("//user[@username='"+username+"']");

            if(e==null){

                return false;

            }

                

            return true;                    

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    

}


5:用户登录的测试

UserDaoTest.java
package junit.test;



import java.util.Date;

import org.junit.Test;

import cn.zyw.dao.UserDao;

import cn.zyw.dao.impl.UserDaoImpl;

import cn.zyw.domain.User;

//4

public class UserDaoTest {

    @Test

    public void testAdd(){

        User user=new User();

        user.setBirthday(new Date());

        user.setEmail("[email protected]");

        user.setId("34343434");

        user.setNickname("李子");

        user.setPassword("123");

        user.setUsername("aaa");        

        

        UserDao dao=new UserDaoImpl();

        dao.add(user);

    }

    @Test

    public void testFind(){

        UserDao dao=new UserDaoImpl();

        User user=dao.find("aaa","123");

        String aa=user.getEmail();

        if(aa.endsWith("kk"))

        {

            System.out.println("kkdf");

        }

    }

    @Test

    public void testFindByUsername(){

        UserDao dao=new UserDaoImpl();

        boolean b=dao.find("aaa");



    }

}

 

 

你可能感兴趣的:(xml)