Spring MVC 自定義標簽如何使用@Autowired自動裝配注解


在用Spring MVC框架做Web應用開發中,在一些特殊請款下我們都會用自定標簽來完成一些特殊的功能。

在通常情況下,自定義標簽的內容如果不通過訪問服務就能實現,那么繼承TagSupport,重寫doStartTag()方法就可以實現基本功能。

eg. 實現一個html標記的反轉義功能的自定義標簽

/**

 

 * @Comment
 * @Author Ron
 * @date 2016年8月30日 上午9:02:56
 */
public class HtmlUnEncodeTags extends TagSupport {
private Logger logger = LogManager.getLogger(this.getClass());
private String encodeStr;
private static final long serialVersionUID = 1L;
@Override
public int doStartTag() throws JspException {
String outStr = "";
try {
if(StringUtils.isNotBlank(encodeStr)){
outStr = StringEscapeUtils.unescapeHtml4(encodeStr);
}
pageContext.getOut().write(outStr);
} catch (IOException e) {
logger.error("",e);
}
return super.doStartTag();
}
public String getEncodeStr() {
return encodeStr;
}
public void setEncodeStr(String encodeStr) {
this.encodeStr = encodeStr;
}
}

但是在特殊情況下,我們需要在自定義標簽的邏輯代碼中訪問服務層獲取信息,那么如何通過注解的方式自動裝配服務呢?在Spring MVC中,用上面所說的方法是不行的。

這里需要自定義標簽繼承的是RequestContextAwareTag 而不是TagSupport。

例如我們需要實現一個獲取未讀郵件數目的功能,我們首先需要在自己的服務中寫好獲取或者計算郵件未讀數量的方法,這里假定為:

queryMsgCount(userId,EmailConsts.ReadStatus.NO.getValue()); 

 userId:用戶唯一標示

EmailConsts.ReadStatus.NO.getValue():獲取枚舉的郵件未讀狀態值

 自定義標簽邏輯class為MsgUnReadMsgTags

那么要實現獲取未讀郵件數目的功能,那么實現代碼如下所示:

public class MsgUnReadMsgTags extends RequestContextAwareTag  {
private Logger logger = LogManager.getLogger(this.getClass());
private int userId;
private static final long serialVersionUID = 1L;
@Autowired
private UserMessageFacade userMessageService;
@Override
public int doStartTagInternal() throws JspException {
String outStr = "";
try {
JspWriter writer = pageContext.getOut();  
userMessageService = this.getRequestContext().getWebApplicationContext().getBean(UserMessageFacade.class);
int count = userMessageService.queryMsgCount(userId,EmailConsts.ReadStatus.NO.getValue());
if(count > 0){
if(count > 99){
outStr = "<span class=\"badge\">99+</span>";
}else{
outStr = "<span class=\"badge\">"+ count +"</span>";
}
}
writer.write(outStr);
writer.flush();
} catch (IOException e) {
logger.error("Get Messages Count IOException-------------->>>>>>>>>>",e);
}
return 0;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}

注意:

在定義userMessageService服務時@Autowired自動裝配注解是不夠的,你還需要在使用時使用ApplicationContext的getBean方法獲取服務的Bean。

如以上代碼中的代碼塊: 

userMessageService = this.getRequestContext().getWebApplicationContext().getBean(UserMessageFacade.class);  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM