Java编程练习:使用分层结构,基于XML文件,实现模拟用户登录

有如下XML文件 user.xml,里面存放的是用户登录信息。

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<user id="u01" username="well" password="1234"/>
	<user id="u02" username="lily" password="4321"/>
</root>


分层设计思想如下:

表现层:LoginUI::input():User    LoginUI::output():String

业务层:LoginBusiness::check(User):boolean

 

根据上面的要求,写出程序:

(1)编写User类

package web.java.xml.exercise1;

public class User {
	private String id;
	private String username;
	private String password;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

 

(2)编写表现层LoginUI类,用于在控制台接收用户输入,并封装为javaBean

package web.java.xml.exercise1;

import java.util.Scanner;

public class LoginUI {
	public User input(){
		User user = new User();
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("username:");
		String username = scanner.nextLine();
		System.out.print("password:");
		String password = scanner.nextLine();
		user.setUsername(username);
		user.setPassword(password);
		
		return user;
	}
	public void output(boolean flag){
		if(flag){
			System.out.println("Login success!");
		} else {
			System.out.println("Login failed!");
		}
	}
}


(3)编写业务层LoginBusiness类,实现用户登录

package web.java.xml.exercise1;

import java.io.File;

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

public class LoginBusiness {
	public static void main(String[] args) throws Exception {
		LoginUI loginUI = new LoginUI();
		LoginBusiness loginBusiness = new LoginBusiness();
		
		User user = loginUI.input();
		boolean flag = loginBusiness.check(user);
		loginUI.output(flag);
	}

	public boolean check(User user) throws Exception {
		boolean flag = false;
		SAXReader saxReader = new SAXReader();
		File file = new File("src/web/java/xml/exercise1/users.xml");
		Document doc = saxReader.read(file);
		String xpath = "//user[@username='"+user.getUsername()+"' and @password='"+user.getPassword()+"']";
		Element ele = (Element) doc.selectSingleNode(xpath);
		if(ele!=null){
			flag = true;
		}
		return flag;
	}
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值