Properties屬性文件中的值有等號和換行
Spring配置Shiro的過濾器時,有個filterChainDefinitions屬性,值中有等號有換行,嘗試寫到Properties屬性文件中遇到問題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!-- 配置shiro過濾器 --> < bean id = "shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean" > <!-- 表示現在要配置的是一個安全管理器 --> < property name = "securityManager" ref = "securityManager" /> <!-- 出現錯誤之后的跳轉路徑的配置 --> < property name = "loginUrl" value = "/login.html" /> <!-- 認證失敗之后的跳轉路徑頁面 --> < property name = "unauthorizedUrl" value = "/login.html" /> <!-- 登錄成功之后的跳轉訪問路徑 --> < property name = "successUrl" value = "/pages/welcome.jsp" /> < property name = "filterChainDefinitions" > < value > /admin=authc /logout=logout /xxxxxx=user </ value > </ property > </ bean > |
Properties屬性文件可以這樣寫
1
2
3
4
5
6
|
shiro.loginUrl=/login.html shiro.unauthorizedUrl=/login.html shiro.successUrl=/pages/welcome.jsp shiro.filterChainDefinitions=/admin=authc \n\ /logout=logout \n\ /info=authc |
后面的等號不需要轉義,\n表示值中的換行,再加個轉義符\表示值還沒結束,這樣就沒問題了
1
2
3
4
5
6
7
8
9
10
|
< bean id = "shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean" > < property name = "securityManager" ref = "securityManager" /> < property name = "loginUrl" value = "${shiro.loginUrl}" /> < property name = "unauthorizedUrl" value = "${shiro.unauthorizedUrl}" /> < property name = "successUrl" value = "${shiro.successUrl}" /> < property name = "filterChainDefinitions" > < value >${shiro.filterChainDefinitions}</ value > </ property > </ bean > |
處理properties文件中key包含空格和等號的情況
在properties文件中都是以key=value的方式存儲的,在java代碼中用java.util.Properties的load方法,存儲在一個map中,當key中有空格和等號的時候,要用\(斜杠)進行轉義,而用xml的話,就沒有轉義這么麻煩了,所以推薦使用xml了。
處理方案
Spike.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; public class Spike { public static void main(String[] args) throws Exception { readProperties(); System.out.println( "==================================================" ); readXml(); } private static void readProperties() throws IOException { Properties props = new Properties(); InputStream inStream = Spike. class .getResourceAsStream( "Mock.properties" ); props.load(inStream); Enumeration enums = props.propertyNames(); while (enums.hasMoreElements()) { String key = (String) enums.nextElement(); System.out.println( "Property--->>>>[" + key + "] " + "Value--->>>>" + props.getProperty(key)); } } private static void readXml() throws IOException { Properties props = new Properties(); InputStream inStream = Spike. class .getResourceAsStream( "Mock.xml" ); props.loadFromXML(inStream); Enumeration enums = props.propertyNames(); while (enums.hasMoreElements()) { String key = (String) enums.nextElement(); System.out.println( "Property--->>>>[" + key + "] " + "Value--->>>>" + props.getProperty(key)); } } } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/zhijian233/p/9881437.html