詳解獲取Spring MVC中所有RequestMapping以及對(duì)應(yīng)方法和參數(shù)
在Spring MVC中想要對(duì)每一個(gè)URL進(jìn)行權(quán)限控制,不想手工整理這樣會(huì)有遺漏,所以就動(dòng)手寫(xiě)程序了。代碼如下:
/**
* @return
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2017年3月8日 上午11:48:22
* 功能:返回系統(tǒng)中的所有控制器映射路徑,以及對(duì)應(yīng)的方法
*/
@RequestMapping(value = "/maps", produces = "application/json; charset=utf-8")
@ResponseBody
public Object getMapPaths(){
String result="";
RequestMappingHandlerMapping rmhp = springHelper.getObject(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
for(RequestMappingInfo info : map.keySet()){
result +=info.getPatternsCondition().toString().replace("[", "").replace("]", "")+ "\t" ;
HandlerMethod hm=map.get(info);
result +=hm.getBeanType().getName()+ "\t" ;
result +=getMethodParams(hm.getBeanType().getName(),hm.getMethod().getName())+ "\t";
result +=info.getProducesCondition().toString().replace("[", "").replace("]", "")+ "\t" ;
result += "\r\n";
}
return result;
}
getMethodParams是專門(mén)用于獲取方法中參數(shù)名稱的函數(shù),因?yàn)橛肑ava自身的反射功能是獲取不到的,浪費(fèi)我不少時(shí)間,后來(lái)網(wǎng)上看到JBOSS的JAVAssist類可以。其實(shí)這個(gè)JAVAssist類庫(kù)也被封裝在Mybatis中,如果系統(tǒng)使用了Mybatis,則直接引入可以使用了。
import org.apache.ibatis.javassist.*; import org.apache.ibatis.javassist.bytecode.*;
getMethodParams 的實(shí)現(xiàn)如下:
/**
* @param className 類名
* @param methodName 方法名
* @return 該方法的聲明部分
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2017年3月8日 上午11:47:16
* 功能:返回一個(gè)方法的聲明部分,包括參數(shù)類型和參數(shù)名
*/
private String getMethodParams(String className,String methodName){
String result="";
try{
ClassPool pool=ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(this.getClass());
pool.insertClassPath(classPath);
CtMethod cm =pool.getMethod(className, methodName);
// 使用javaassist的反射方法獲取方法的參數(shù)名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
result=cm.getName() + "(";
if (attr == null) {
return result + ")";
}
CtClass[] pTypes=cm.getParameterTypes();
String[] paramNames = new String[pTypes.length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++) {
if(!pTypes[i].getSimpleName().startsWith("HttpServletRe")){
result += pTypes[i].getSimpleName();
paramNames[i] = attr.variableName(i + pos);
result += " " + paramNames[i]+",";
}
}
if(result.endsWith(",")){
result=result.substring(0, result.length()-1);
}
result+=")";
}catch(Exception e){
e.printStackTrace();
}
return result;
}
這樣就可以獲得每個(gè)URL路徑與期對(duì)應(yīng)的方法聲明了。
另外SpringHelper是自己封裝的Spring工具類,可以用來(lái)直接獲取Spring管理的Bean,代碼如下:
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
/**
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 上午9:12:13
* 功能:Spring 工具類,用于獲取Spring管理的Bean
*/
@Component
public class SpringHelper implements ApplicationContextAware {
// 日志輸出類
private static Logger logger = Logger.getLogger(SpringHelper.class);
// 當(dāng)前的Spring上下文
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
applicationContext = arg0;
}
/**
* @param beanName bean Id
* @return 如果獲取失敗,則返回Null
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 上午9:52:55
* 功能:通過(guò)BeanId獲取Spring管理的對(duì)象
*/
public Object getObject(String beanName) {
Object object = null;
try {
object = applicationContext.getBean(beanName);
} catch (Exception e) {
logger.error(e);
}
return object;
}
/**
* @return
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2017年3月7日 下午3:44:38
* 功能:獲取Spring的ApplicationContext
*/
public ApplicationContext getContext() {
return applicationContext;
}
/**
* @param clazz 要獲取的Bean類
* @return 如果獲取失敗,則返回Null
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 上午10:05:27
* 功能:通過(guò)類獲取Spring管理的對(duì)象
*/
public <T> T getObject(Class<T> clazz) {
try {
return applicationContext.getBean(clazz);
} catch (Exception e) {
logger.error(e);
}
return null;
}
/**
* @param code 配置文件中消息提示的代碼
* @param locale 當(dāng)前的語(yǔ)言環(huán)境
* @return 當(dāng)前語(yǔ)言對(duì)應(yīng)的消息內(nèi)容
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 上午10:34:25
* 功能:獲取當(dāng)前語(yǔ)言對(duì)應(yīng)的消息內(nèi)容
*/
public String getMessage(String code,Locale locale){
String message;
try{
message=applicationContext.getMessage(code, null, locale);
}catch(Exception e){
logger.error(e);
message="";
}
return message;
}
/**
*
* @param code 配置文件中消息提示的代碼
* @param request 當(dāng)前的HTTP請(qǐng)求
* @return 當(dāng)前語(yǔ)言對(duì)應(yīng)的消息內(nèi)容
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 下午3:03:37
* 功能:獲取當(dāng)前語(yǔ)言對(duì)應(yīng)的消息內(nèi)容
*/
public String getMessage(String code,HttpServletRequest request){
String message;
try{
message=applicationContext.getMessage(code, null, getCurrentLocale(request));
}catch(Exception e){
logger.error(e);
message="zh_CN";
}
return message;
}
/**
* @param request 當(dāng)前的HTTP請(qǐng)求
* @return 當(dāng)前用戶Cookie中的語(yǔ)言
* @author Elwin ZHANG
* 創(chuàng)建時(shí)間:2016年4月14日 下午2:59:21
* 功能:當(dāng)前用戶保存Cookie中的默認(rèn)語(yǔ)言
*/
public Locale getCurrentLocale(HttpServletRequest request){
return resolver.resolveLocale(request);
}
//Cookie本地語(yǔ)言解析器,Spring提供
@Autowired
CookieLocaleResolver resolver;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA中SpringBoot項(xiàng)目的yml多環(huán)境配置方式
這篇文章主要介紹了IDEA中SpringBoot項(xiàng)目的yml多環(huán)境配置,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-10-10
spring boot國(guó)際化之MessageSource的使用方法
這篇文章主要給大家介紹了spring boot國(guó)際化之MessageSource使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
SpringSecurity的TokenStore四種實(shí)現(xiàn)方式小結(jié)
本文主要介紹了SpringSecurity的TokenStore四種實(shí)現(xiàn)方式小結(jié),分別是InMemoryTokenStore,JdbcTokenStore,JwkTokenStore,RedisTokenStore,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
rocketmq client 日志的問(wèn)題處理方式
這篇文章主要介紹了rocketmq client 日志的問(wèn)題處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10

