Last active
October 29, 2021 02:42
-
-
Save Benjamin1021523/5265a3b0c50c5f6560b7e1007a860e90 to your computer and use it in GitHub Desktop.
嘗試取得java spring專案下resources目錄xml內容的寫法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gist的title是認檔名「字串排序」最小的為準,建立後將其他檔案改名或新增檔案都無效 | |
參考資料: | |
https://stackoverflow.com/questions/9536737/load-a-xml-file-from-the-classpath-in-a-spring-web-app | |
https://zetcode.com/spring/classpathresource/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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