在实现用户权限管理模块的时候,我希望能将所有配置的action存储到行为表中,便于细粒度控制行为的权限.由于controller使用的是springMVC实现的,所以我希望在项目启动时,能够先获取到项目中所有配置的RequestMapping,存储到数据库中.
1.servlet
public class GetAllRequestMappingTest extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("GetAllRequestMappingTest in");
ServletContext context = config.getServletContext();
WebApplicationContext webApp = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
RequestMappingHandlerMapping rmhp = webApp.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator
.hasNext();) {
RequestMappingInfo info = iterator.next();
System.out.print(info.getConsumesCondition());
System.out.print(info.getCustomCondition());
System.out.print(info.getHeadersCondition());
System.out.print(info.getMethodsCondition());
System.out.print(info.getParamsCondition());
System.out.print(info.getPatternsCondition());
System.out.print(info.getProducesCondition());
System.out.print("===");
HandlerMethod method = map.get(info);
System.out.print(method.getMethod().getDeclaringClass().getName() + "--");
System.out.print(method.getMethod().getName());
//System.out.print(method.getMethodAnnotation(RequestMapping.class).params()[0]);
System.out.println();
}
}
}
2.效果图
3.注意
网上有很多都是把该功能作为一个controller中的一个方法.原因是RequestMappingHandlerMapping这个类只能在controller中获取.在我尝试的过程中确实不在controller中,通过自动注入的方式是无法获得RequestMappingHandlerMapping类的.但是通过全局WebApplicationContext可以不用自动注入的方式获得RequestMappingHandlerMapping类.