Skip to content

Instantly share code, notes, and snippets.

@Benjamin1021523
Last active October 29, 2021 02:42
Show Gist options
  • Save Benjamin1021523/5265a3b0c50c5f6560b7e1007a860e90 to your computer and use it in GitHub Desktop.
Save Benjamin1021523/5265a3b0c50c5f6560b7e1007a860e90 to your computer and use it in GitHub Desktop.
嘗試取得java spring專案下resources目錄xml內容的寫法
gist的title是認檔名「字串排序」最小的為準,建立後將其他檔案改名或新增檔案都無效
參考資料:
https://stackoverflow.com/questions/9536737/load-a-xml-file-from-the-classpath-in-a-spring-web-app
https://zetcode.com/spring/classpathresource/
public boolean checkLogin(String name, String password) throws Exception {
String sql = ParseXml.getSqlByName("Account.checkLogin");
List<Object> condition = new ArrayList<Object>();
condition.add(name);
condition.add(password);
return jdbcTemplate.queryForInt(sql, condition.toArray()) != 0;
}
package website.common;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.Element;
import org.springframework.core.io.ClassPathResource;
public class ParseXml {
private static Document getSQLDocument() throws DocumentException, IOException {
SAXReader reader = new SAXReader();
// ClassPathResource填入的是resources內的路徑
ClassPathResource cpr = new ClassPathResource("Sql.xml");
Document document = reader.read(cpr.getURL());
return document;
}
public static String getSqlByName (String sqlName) throws Exception {
Document document = getSQLDocument();
Element element = document.getRootElement();
return element.elementText(sqlName).trim();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<sqls>
<Account.checkLogin>
SELECT count(*) FROM ACCOUNT WHERE name = ? and password = ?
</Account.checkLogin>
</sqls>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment