XML operation example → implement user login

Source: Internet
Author: User

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;//3public 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.createpre        Ttyprint ();        Format.setencoding ("UTF-8");        XMLWriter writer = new XMLWriter (new FileOutputStream (filepath), format);        Writer.write (document); WritEr.close (); }}

Sometimes we want to do a small project to save certain data, if using a database is certainly possible. But it always feels like a waste of resources. So today I learned a little bit of XML summarized as follows:

The 1:xml file is as follows:

  

<?xml version= "1.0" encoding= "UTF-8"?><users>    <user id= "234343434" Username= "AAA" password= "123" email= "[email protected]" birthday= "1900-09-18" nickname= "Hadron"/></users>

2: Tool class for manipulating XML files

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 ();
}

}


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;//3public 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.createpre        Ttyprint ();        Format.setencoding ("UTF-8");        XMLWriter writer = new XMLWriter (new FileOutputStream (filepath), format);        Writer.write (document); WritEr.close (); }}

3: User login for 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);

Find whether registered users exist in the database
Boolean find (String username);

}


Package Cn.zyw.dao;import Cn.zyw.domain.user;//5public interface Userdao {    void Add (user user);    User Find (string Username, string password);    Finds whether the registered user has a Boolean find in the database    (String username);

4: Implementation class for user login

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 ();//Get root node
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"));//Get the value inside the 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);
}
}
Find whether registered users exist in the database
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);
}
}

}


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;//2public class UserDaoImpl            Implements Userdao {public void Add (user user) {try {Document document=xmlutils.getdocument ();            Element root=document.getrootelement ();//Get root node 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.getdocumen            T ();            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"));//Get the value inside the 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); }}//Find whether the registered user exists in the database with 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: Test of User Login

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 ("Plum");
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");

}
}


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;//4public class Userdaotest {    @Test public    Void Testadd () {        user user=new User ();        User.setbirthday (New Date ());        User.setemail ("[email protected]");        User.setid ("34343434");        User.setnickname ("Plum");        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 operation example → implement user login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.