《精通Spring MVC 4》——2.7 結束Hello World,開始獲取Tweet
本節書摘來自異步社區《精通Spring MVC 4》一書中的第2章,第2.7節,作者:【美】Geoffroy Warin著,更多章節內容可以訪問雲棲社區“異步社區”公眾號查看
2.7 結束Hello World,開始獲取Tweet
好了,畢竟這本書的名字不是“精通Hello World”,我們結束這一話題。借助Spring,使用Twitter的API進行查詢是非常容易的事情。
2.7.1 注冊應用
在開始之前,我們需要在Twitter的開發者控製台中注冊應用。
訪問https://apps.twitter.com,並創建一個新的應用。
根據你喜好為其設定一個名稱,在Website和Callback URL區域中,輸入https://127.0.0.1:8080(見圖2-6)。這樣的話,就能在本地機器上,測試開發階段的應用。
圖2-6
現在,導航至“Keys and Access Token”,並複製Consumer Key和Consumer Secret,稍後我們會用到它們,參見圖2-7所示的截圖。
圖2-7
默認情況下,應用會具有隻讀的權限,對於該應用來說,這就足夠了,但是如果你願意的話,可以對其進行調整。
2.7.2 搭建Spring Social Twitter
添加如下的依賴到build.gradle文件中:
compile 'org.springframework.boot:spring-boot-starter-social-twitter'
添加如下的兩行代碼到application.properties中:
spring.social.twitter.appId= <Consumer Key>
spring.social.twitter.appSecret= <Consumer Secret>
這是與剛才所創建的應用相關的key。
我們將會在第6章中詳細介紹OAuth。就現在而言,隻是使用這些憑證信息發送請求到Twitter的API上,以滿足我們應用的需要。
2.7.3 訪問Twitter
現在,就可以在控製器中使用Twitter了,將它的名字改為TweetController,從而能夠以更好的方式反映其新功能:
@Controller
public class TweetController {
@Autowired
private Twitter twitter;
@RequestMapping("/")
public String hello(@RequestParam(defaultValue =
"masterSpringMVC4") String search, Model model) {
SearchResults searchResults = twitter.searchOperations().
search(search);
String text = searchResults.getTweets().get(0).getText();
model.addAttribute("message", text);
return "resultPage";
}
}
我們可以看到,上麵的代碼會搜索匹配請求參數的Tweet。如果一切運行正常的話,結果中第一條記錄的文本將會顯示出來(見圖2-8)
圖2-8
當然,如果搜索沒有得到任何結果的話,這段蹩腳的代碼將會因為ArrayOutOfBoundException異常而導致失敗。因此,可以抓緊發一條Tweet來解決這個問題!
如果想展現Tweet列表的話,那該怎麼辦呢?讓我們修改一下resultPage.html文件:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8"/>
<title>Hello twitter</title>
</head>
<body>
<ul>
<li th:each="tweet : ${tweets}" th:text="${tweet}">Some
tweet</li>
</ul>
</body>
</html>
th:each是由Thymeleaf所定義的標簽,它允許我們遍曆一個集合並且能夠在循環中將集合中的每個值賦給一個變量。
我們也需要修改控製器:
@Controller
public class TweetController {
@Autowired
private Twitter twitter;
@RequestMapping("/")
public String hello(@RequestParam(defaultValue =
"masterSpringMVC4") String search, Model model) {
SearchResults searchResults = twitter.searchOperations().
search(search);
List<String> tweets =
searchResults.getTweets()
.stream()
.map(Tweet::getText)
.collect(Collectors.toList());
model.addAttribute("tweets", tweets);
return "resultPage";
}
}
注意,我們在這裏使用了Java 8的流來收集Tweet的信息。Tweet類包含了很多其他的屬性,如發送者、轉推的數量等。但是,現在我們盡可能地保持簡單,如圖2-9中的截圖所示。
圖2-9
最後更新:2017-05-27 16:01:27