REST風格框架實戰:從MVC到前後端分離(附完整Demo)

* 也就是說,每個REST請求將返回相同結構的JSON響應結構。不妨定義一個相對通用的JSON響應結構,其 * @author rico * @author rico * @author rico * @author rico * @author rico * @author rico * @author rico * @author rico *
* @author rico


* @created 2017年7月4日 下午4:32:34
*/
@Component
@Aspect
public class SecurityAspect {
/** Log4j日誌處理(@author: rico) */
private static final Logger log = Logger.getLogger(SecurityAspect.class);
private TokenManager tokenManager;
@Resource(name = "tokenManager")
public void setTokenManager(TokenManager tokenManager) {
this.tokenManager = tokenManager;
}
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
// 從切點上獲取目標方法
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
log.debug("methodSignature : " + methodSignature);
Method method = methodSignature.getMethod();
log.debug("Method : " + method.getName() + " : "
+ method.isAnnotationPresent(IgnoreSecurity.class));
// 若目標方法忽略了安全性檢查,則直接調用目標方法
if (method.isAnnotationPresent(IgnoreSecurity.class)) {
return pjp.proceed();
}
// 從 request header 中獲取當前 token
String token = WebContextUtil.getRequest().getHeader(
Constants.DEFAULT_TOKEN_NAME);
// 檢查 token 有效性
if (!tokenManager.checkToken(token)) {
String message = String.format("token [%s] is invalid", token);
log.debug("message : " + message);
throw new TokenException(message);
}
// 調用目標方法
return pjp.proceed();
}
}

若要使SecurityAspect生效,則需要在SpringMVC配置文件中添加如下Spring 配置:

  


use-default-filters="false">

expression="org.springframework.stereotype.Controller" />

expression="org.springframework.web.bind.annotation.ControllerAdvice" />



最後,別忘了在web.xml中添加允許的X-Token響應頭,配置如下:

 
allowHeaders
Content-Type,X-Token


四. 關於Demo部署的若干建議

關於REST服務的調試推薦大家使用Postman這款工具,請大家自行下載與安裝,具體見《postman的安裝與使用(模擬請求)》;


五. 總結

本文從經典的MVC模式開始,對MVC模式是什麼以及該模式存在的不足進行了簡述。然後引出瞭如何對MVC模式的改良,讓其轉變為前後端分離架構,以及解釋了為何要進行前後端分離。最後通過REST服務將前後端進行解耦,並提供了一款基於Java的REST框架的主要實現過程,尤其是需要注意的核心技術問題及其解決方案。希望本文對正在探索前後端分離的讀者們有所幫助,期待與大家共同探討。


分享到:


相關文章: