如何使用struts2从xml查询数据查询到java类

时间:2014-06-19 07:34:51

标签: xml struts2

我正在使用struts2并且有一个DAO类,我有一个验证方法,我从db.properties文件中获取查询。但我的    问题是如何从xml文件中获取查询数据到此方法    而不是db.properties。在此先感谢。

AuthenticateUser方法

     'Properties properties = new Properties();
                   InputStream inputStream = DBConnection.class.getClassLoader()
                    .getResourceAsStream("db.properties");
           @Override
           /** function authenticateUser 
            *  @return UserBean
            */
           public UserBean authenticateUser(UserBean userBean) throws SQLException,
                NullPointerException {
            // logger.info("connection establishing ");
            // establishing connection
            con = conn.createConnection();
            userBean.setPassword(PasswordUtil.encryptPassword(userBean
                    .getPassword().toString()));
            try {
                properties.load(inputStream);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            String sql = properties.getProperty("users_signin_query");
            // PreparedStatement is used to execute queries.
            preparedstatement = con.prepareStatement(sql);
            preparedstatement.setString(1, userBean.getUserName());
            preparedstatement.setString(2, userBean.getPassword());
            resultSet = preparedstatement.executeQuery();

            UserBean bean = new UserBean();
            if (resultSet.next()) {
                bean.setIs_admin(resultSet.getString("is_admin"));
                bean.setEmail(resultSet.getString("email"));
                bean.setFirstname(resultSet.getString("first_name"));
                bean.setUserid(resultSet.getString("id"));
                bean.setMobile(resultSet.getString("mobile"));
                bean.setUserName(resultSet.getString("username"));
                bean.setLastname(resultSet.getString("last_name"));
                bean.setPassword(resultSet.getString("password"));
                return bean;
            } else {
                conn.close(con);
                return bean;
            }
           }'

db.properties

jdbc details driver=com.mysql.jdbc.Driver db_url=jdbc:mysql://localhost:3306/app

数据库凭据

db_user_name=root db_password=root users_query=
   insert into users(username,password,email,first_name,last_name,mobile,id)
   values(?,?,?,?,?,?,?)*

1 个答案:

答案 0 :(得分:0)

备选方案1:使用DOM解析器(不会因为速度慢而重新录制) 在项目中复制粘贴jaxp-api-x.x.x.jar和dom jar。

在代码中使用以下功能

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public String ReadAttributefromXML(String xmlFilepath,String AttributeName) {

try {

File fXmlFile = new File("xmlFilepath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("jdBCProperties");

for (int temp = 0; temp < nList.getLength(); temp++) {

    Node nNode = nList.item(temp);

    System.out.println("\nCurrent Element :" + nNode.getNodeName());

    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        Element eElement = (Element) nNode;
                  return(eElement.getElementsByTagName(AttributeName).item(0).getTextContent());
            //or return(eElement.getAttribute(AttributeName)); if your structure is simpler than I mensioned like <jdBCProperties query="....">
    }
}
} catch (Exception e) {
e.printStackTrace();
}

   }

yourxmlfile.xml

<? xml version="1.0"?>
<Properties>
<Properties>
<jdBCProperties>
        <jdbc_details_driver>com.mysql.jdbc.Driver</jdbc_details_driver>
        <db_url>jdbc:mysql://localhost:3306/app</db_url>
        <db_user_name>root</db_user_name>
     <db_password>root</db_password>
        <users_query>insert into users(username,password,email,first_name,last_name,mobile,id) values(?,?,?,?,?,?,?)*</users_query>
</jdBCProperties>

</Properties>

在您的代码中使用:

 String sql =  ReadAttributefromXML("/yourxmlFileName.xml","users_query");

如果我不明白你的问题,请告诉我......

参考Read this article

备选方案2:使用SAX Parser(重新命令,因为它比DOM Parser更快)

创建一个包xml.util并在其中创建一个calss ReadXML.java

复制并粘贴到课程

中的代码下方
package xml.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXML {
public String value="";
public String ReadXmlAttribute(String path,final String AtttributeName)
{
    value="";
    SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser;
    try {
        saxParser = factory.newSAXParser();


      DefaultHandler handler = new DefaultHandler() {

        boolean flag = false;


        public void startElement(String uri, String localName,
            String qName, Attributes attributes)
            throws SAXException {

         // System.out.println("Start Element :" + qName);

          if (qName.equalsIgnoreCase(AtttributeName)) {
              flag = true;
          }

        }

        public void endElement(String uri, String localName,
                String qName)
                throws SAXException {

              //System.out.println("End Element :" + qName);

        }

        public void characters(char ch[], int start, int length)
            throws SAXException {

          //System.out.println(new String(ch, start, length));


          if (flag) {
              value =  new String(ch, start, length);
              System.out.println("Attribute Found : "
                +value);


            flag = false;
          }
        }
      };

    File file = new File(path);
    InputStream inputStream = new FileInputStream(file);

    Reader reader = new InputStreamReader(inputStream,"UTF-8");


    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");

    saxParser.parse(is, handler);

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return value;
}
}    

在您的代码中使用

import xml.util.ReadXML;

 // in your action method
 ReadXML myxml = new ReadXML();
 String sql = myxml.ReadXmlAttribute("c:\\yourxmlfile.xml", "users_query");

参考SAX Parser Example