码迷,mamicode.com
首页 > 其他好文 > 详细

XML小项目------dom4j操作联系人(图形界面版)

时间:2016-07-16 15:52:21      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

在进行此项目之前需要将dom4j的jar包及其依赖包导入,具体操作间本博客文章:XML之------dom4j对XML文档增删改查点击打开链接

公共类:DocumentFactory.java

package cn.hncu.contact.common;

import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DocumentFactory {
	private static Document dom=null;
	static{
		try {
			SAXReader sax=new SAXReader();
			dom=sax.read("xml/contact.xml");
		} catch (Exception e) {
			throw new RuntimeException("xml文件解析出错", e);
		}
	}
	private DocumentFactory(){
	}
	public static Document getDocument(){
		return dom;
	}
	public static void save(){
		try {
			XMLWriter writer=new XMLWriter(new FileWriter("xml/contact.xml"));
			writer.write(dom);
			writer.close();
		} catch (IOException e) {
			throw new RuntimeException("xml文件保存出错", e);
		}
	}
}

工具类:

IDGenerate.java

package cn.hncu.contact.utils;

import java.util.UUID;

public class IDGenerate {
	private IDGenerate(){
	}
	public static String getId(){
		String uuid=UUID.randomUUID().toString();
		uuid=uuid.replace("-", "");
		return uuid;
	}
}
PwdMd5Utils.java

package cn.hncu.contact.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class PwdMd5Utils {

	public static String mkPwd(String pwd){
		String pwd2="";
		try {
			MessageDigest msg=MessageDigest.getInstance("MD5");
			byte buf[]=msg.digest(pwd.getBytes());//buf的长度是16
			for (byte b:buf){
				String s=Integer.toHexString(b & 0xff);
				if (s.length()==1){
					s+="f";//可以把'f'换成其它的16进制数如'a'
				}
				pwd2+=s;
			}
			return pwd2;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("加密失败", e);
		}
	}
	
	public static void main(String[] args) {
		//introduce1();
		//introduce2();
		md5_2();
	}

	//该加密方式目前可以用,但不建议,因为使用了oracle公司没有公开的类
	private static void introduce1() {
		String pwd="1234";
		try {
			MessageDigest msg=MessageDigest.getInstance("MD5");
			byte buf[]=msg.digest(pwd.getBytes());
			for (byte b:buf){
				System.out.print(b+" ");
			}
			System.out.println();
			System.out.println(buf.length);
			
			//BASE64Encoder在API文档中不存在,即该类是oracle公司没有公开的,因此我们要谨用!!!
			BASE64Encoder en=new BASE64Encoder();
			String pwd2=en.encode(buf);
			System.out.println("pwd2: "+pwd2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//该加密方式可用,我们自己写一段替代BASE64Encoder类中encode()方法的代码
	private static void introduce2() {
		String pwd="1234";
		String pwd2="";
		try {
			MessageDigest msg=MessageDigest.getInstance("MD5");
			byte buf[]=msg.digest(pwd.getBytes());
			for (byte b:buf){
				String s=Integer.toHexString(b & 0xff);
				if (s.length()==1){
					s+="f";
				}
				pwd2+=s;
			}
			System.out.println(pwd2);
			System.out.println("len: "+pwd2.length());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
	}
	
	private static void md5_2() {
		String pwd="1234";
		String pwd2="";
		try {
			MessageDigest msg=MessageDigest.getInstance("MD5");
			byte buf[]=msg.digest(pwd.getBytes());
			for (byte b:buf){
				String s=Integer.toHexString(b & 0xff);
				if (Math.abs(b)<16){
					s="a"+s;
				}
				pwd2+=s;
			}
			System.out.println(pwd2);
			System.out.println("len: "+pwd2.length());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
	}

}

表现层:ContactWin.java

package cn.hncu.contact.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import org.dom4j.Element;

import cn.hncu.contact.dao.ContactDAO;
import cn.hncu.contact.utils.IDGenerate;

public class ContactWin extends JFrame implements ActionListener{
	private static Element currentUser=null;
	
	private JTable jTable;
	private DefaultTableModel dtm;
	JTextField tfdName,tfdTel,tfdAddr,tfdSex;
	JButton btnAdd,btnDel;
	
	private ContactDAO dao=new ContactDAO();
	
	public ContactWin(Element user){
		this.currentUser=user;
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBounds(200, 200, 500, 400);
		this.setTitle("联系人管理界面");
		Container c=this.getContentPane();
		
		jTable=getTable();
		c.add(new JScrollPane(jTable));
		
		tfdName=new JTextField(5);
		tfdAddr=new JTextField(5);
		tfdSex=new JTextField(5);
		tfdTel=new JTextField(5);
		JPanel p=new JPanel();
		p.add(new JLabel("联系人信息"));
		p.add(tfdName);
		p.add(tfdTel);
		p.add(tfdSex);
		p.add(tfdAddr);
		btnAdd=new JButton("添加");
		btnDel=new JButton("删除");
		p.add(btnAdd);
		p.add(btnDel);
		c.add(p,BorderLayout.SOUTH);
		
		btnAdd.addActionListener(this);
		btnDel.addActionListener(this);
		
		this.setVisible(true);
	}
	
	private JTable getTable() {
		//表头
		Vector<Object> vHeader=new Vector<Object>();
		vHeader.add("id");
		vHeader.add("name");
		vHeader.add("telephone");
		vHeader.add("sex");
		vHeader.add("address");
		
		Vector<Vector<Object>>datas=dao.getContacts(currentUser);
		dtm=new DefaultTableModel(datas, vHeader);
		
		JTable jt=new JTable(dtm);
		//删除第一列,即不显示id
		jt.removeColumn(jt.getColumn("id"));
		
		return jt;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==btnAdd){
			//收集参数
			String name=tfdName.getText();
			String tel=tfdTel.getText();
			String sex=tfdSex.getText();
			String addr=tfdAddr.getText();
			//补一个id
			String id=IDGenerate.getId();
			//保存到后台
			boolean boo=dao.addContact(currentUser,id,name,tel,sex,addr);
			//保存成功,刷新界面
			if (boo){
				Vector<Object> v=new Vector<Object>();
				v.add(id);
				v.add(name);
				v.add(tel);
				v.add(sex);
				v.add(addr);
				dtm.addRow(v);
			} else {
				JOptionPane.showMessageDialog(this, "添加联系人失败");
				return;
			}
		} else if (e.getSource()==btnDel){
			int row=jTable.getSelectedRow();
			if (row==-1){
				JOptionPane.showMessageDialog(null, "前选择要删除的行");
				return;
			}
			String id=(String) dtm.getValueAt(row, 0);
			boolean isSuccess=dao.delete(currentUser,id);
			if (isSuccess){
				dtm.removeRow(row);
			} else {
				JOptionPane.showMessageDialog(this, "删除联系人失败");
				return;
			}
		}
	}
}

数据层:ContactDAO.java

package cn.hncu.contact.dao;

import java.util.Iterator;
import java.util.Vector;

import org.dom4j.Document;
import org.dom4j.Element;

import cn.hncu.contact.common.DocumentFactory;
import cn.hncu.contact.utils.PwdMd5Utils;

public class ContactDAO {
	private Document dom=DocumentFactory.getDocument();
	//private static Element currentUser=null;
	
	//登录
	public Element login(String name, String pwd){
		name=name.toLowerCase();
		pwd=PwdMd5Utils.mkPwd(pwd);
		String xpath="//user[fn:lower-case(@name)='"+name+"'][@pwd='"+pwd+"']";
		Element e=(Element) dom.selectSingleNode(xpath);
		//currentUser=e;
		return e;
	}
	
	//查询所有联系人
	public Vector<Vector<Object>> getContacts(Element currentUser) {
		Vector<Vector<Object>> datas=new Vector<Vector<Object>>();
		Iterator<Element> it=currentUser.elementIterator("contact");
		while (it.hasNext()){
			Element e=it.next();
			Vector<Object> v=new Vector<Object>();
			v.add(e.attributeValue("id"));
			v.add(e.elementText("name"));
			v.add(e.elementText("tel"));
			v.add(e.elementText("sex"));
			v.add(e.elementText("addr"));
			datas.add(v);
		}
		return datas;
	}

	public boolean addContact(Element currentUser, String id, String name, String tel, String sex, String addr) {
		Element e=currentUser.addElement("contact");
		e.addAttribute("id", id);
		e.addElement("name").setText(name);
		e.addElement("tel").setText(tel);
		e.addElement("sex").setText(sex);
		e.addElement("addr").setText(addr);
		try {
			DocumentFactory.save();
			return true;
		} catch (Exception e1) {
			return false;
		}
	}

	public boolean delete(Element currentUser, String id) {
		String xpath="//contact[@id='"+id+"']";
		Element e=(Element) dom.selectSingleNode(xpath);
		boolean boo=e.getParent().remove(e);
		if (boo){
			try {
				DocumentFactory.save();
				return true;
			} catch (Exception e1) {
				return false;
			}
		}
		return false;
	}
}

登陆界面:LoginWin.java

package cn.hncu.contact;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.dom4j.Element;

import cn.hncu.contact.dao.ContactDAO;
import cn.hncu.contact.ui.ContactWin;

public class LoginWin extends JFrame {
	private static Element currentUser=null;
	
	public LoginWin(){
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBounds(200, 200, 400, 140);
		
		JPanel p1=new JPanel(new GridLayout(2,2));
		p1.add(new JLabel("用户名: "));
		final JTextField tfdName=new JTextField(10);
		p1.add(tfdName);
		p1.add(new JLabel("用户名: "));
		final JPasswordField jpfPwd=new JPasswordField(10);
		p1.add(jpfPwd);
		
		JPanel p2=new JPanel();
		JButton btnLogin=new JButton("登录");
		JButton btnCancel=new JButton("取消");
		p2.add(btnLogin);
		p2.add(btnCancel);
		
		this.getContentPane().add(p1);
		this.getContentPane().add(p2,BorderLayout.SOUTH);
		
		btnLogin.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String name=tfdName.getText();
				String pwd=new String(jpfPwd.getPassword());
				if (name.trim().equals("")){
					JOptionPane.showMessageDialog(LoginWin.this, "请输入用户名");
					return;
				}
				Element user=new ContactDAO().login(name,pwd);
				if (!(user==null)){
					currentUser=user;
					new ContactWin(currentUser);
					LoginWin.this.setVisible(false);
				} else {
					JOptionPane.showConfirmDialog(LoginWin.this, "用户名或密码不正确");
					return;
				}
			}
		});
		
		btnCancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		
		this.setVisible(true);
	}
	
	public static void main(String[] args) {
		new LoginWin();
	}
	
}

xml文档:

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
	<user name="Jack" pwd="81dc9bdb52d04dc20f36dbd8313ed055">
    <contact id="a001">
        <name>Tom</name>
        <sex>Male</sex>
        <tel>13812345678</tel>
        <addr>湖南益阳</addr>
    </contact>
    <contact id="a002">
    	<name>Rose</name>
        <sex>Female</sex>
        <tel>13887654321</tel>
        <addr>浙江杭州</addr>
    </contact>
  
	</user>
 
	<user name="Tom" pwd="d93591bdf786ef1e4ee2fca799911215">
	    <contact id="b001">
	    	<name>Jack</name>
	    	<sex>Male</sex>
	    	<tel>13800000000</tel>
	   		<addr>浙江杭州</addr>
	    </contact>
	    <contact id="b002">
	        <name>Rose</name>
	        <sex>Female</sex>
	        <tel>13887654321</tel>
	        <addr>中国上海</addr>
	    </contact>
	</user>

</contacts>


XML小项目------dom4j操作联系人(图形界面版)

标签:

原文地址:http://blog.csdn.net/x121850182/article/details/51902023

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!