<%--List_8_10_1.jsp--%>
<%@ page import="java.io.InputStream,
                 java.io.IOException,
                 java.io.FileInputStream,
                 org.jdom.input.DOMBuilder,
                 org.jdom.Document,
                 org.jdom.Element,
                 org.jdom.JDOMException"%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<html>
  <head><title>使用XML配置文件</title></head>
  <body>
  <%
      MyConfig conf=new MyConfig(pageContext.getServletContext().getRealPath("cfg.xml"));
      out.println("       程序当前的配置：<br/>");
      out.println("----------------------------<br/>");
      out.println("User: "+conf.getUser()+"<br/>");
      out.println("Password: "+conf.getPassword()+"<br/>");
      out.println("Role: "+conf.getRole()+"<br/>");
  %>
  <%!
      public class MyConfig {

          /** The stream to read the XML configuration from */
          private InputStream in;
          //用户名
          private String user;
          //密码
          private String password;
          //角色
          private String role;

          public String getPassword() {
              return password;
          }

          public void setPassword(String password) {
              this.password = password;
          }

          public String getRole() {
              return role;
          }

          public void setRole(String role) {
              this.role = role;
          }

          public MyConfig(String filename)
                  throws IOException {

              this(new FileInputStream(filename));
          }

          public MyConfig(InputStream in)throws IOException {
              this.in = in;
              user = "";
              password = "";
              role="";
              // Parse the XML configuration information
              parseConfiguration();
          }

          public String getUser() {
              return user;
          }


          private void parseConfiguration() throws IOException {
              try {
                  DOMBuilder  db=new DOMBuilder();
                  Document doc =  db.build(in);
                  Element root = doc.getRootElement();
                  user = root.getChild("user").getText();
                  password = root.getChild("password").getText();
                  role=root.getChild("role").getText();
              } catch (JDOMException e) {
                  throw new IOException(e.getMessage());
              }
          }
      }
  %>
  </body>
</html>