有如下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;
}
}