java 反射 spring mvc_Spring mvc  利用java的反射技术,来扫描对应包下的注解请求url 统一保存在数据库...

很有用的工具类

::  提前说明::::

对  @requestMapping("/xxxx/其他参数")

的格式

package com.er07.book.springmvc.util;

import java.io.File;

import java.lang.reflect.Method;

import java.net.URL;

import org.springframework.context.ApplicationContext;

import

org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.stereotype.Controller;

import

org.springframework.web.bind.annotation.RequestMapping;

import com.er07.book.springmvc.service.RightService;

public class RegRightUtils {

private static final String rootUrl = "/spring";

private static RightService rightService;

public static void main(String[] args) throws Exception

{

ApplicationContext context = new

ClassPathXmlApplicationContext("beans.xml");

rightService =

context.getBean(RightService.class);

ClassLoader classLoader =

RegRightUtils.class.getClassLoader();

URL url =

classLoader.getResource("com/er07/book/springmvc/controller");

String rootPath = url.getPath().toString();

File rootFile = new File(rootPath);

File [] files = rootFile.listFiles();

for(File f: files) {

System.err.println(f.getName());

String className = f.getName().substring(0,

f.getName().indexOf(".class"));

Class clazz =

Class.forName("com.er07.book.springmvc.controller."+className);

parseClass(clazz);  //解析

出url

}

}

public  static void parseClass(Class clazz)

{

if(clazz.isAnnotationPresent(Controller.class)) {

//是否为一个controller ?

String classUrl ="";

if(clazz.isAnnotationPresent(RequestMapping.class))

{

RequestMapping requestMapping_clazz =

(RequestMapping) clazz.getAnnotation(RequestMapping.class);

classUrl =

requestMapping_clazz.value()[0];

if(classUrl.equals("/")) {

//如果是"/" 的话  制空

classUrl ="";

}

}

Method [] ms =

clazz.getDeclaredMethods();

for(Method m :ms) {

if(m.isAnnotationPresent(RequestMapping.class))

{

RequestMapping requestMapping_method =

m.getAnnotation(RequestMapping.class);

String methodUrl =

requestMapping_method.value()[0];

int

index = methodUrl.indexOf("/");

index =

methodUrl.indexOf("/",index+1);

if(index!=-1) {

//如果存在 则进行截取前面的url

methodUrl =

methodUrl.substring(0, index);

}

String resultUrl =

rootUrl+classUrl+methodUrl;

rightService.appendRightByUrl(resultUrl);

}

}

}

}

}

//实现方法:

public void appendRightByUrl(String url) {

//查询 此url 在数据库中是否存在  此权限

String hql = "from Right where rightUrl =?";

Right r = (Right) this.rightDao.uniqueResult(hql, url);

if(r==null) { //不存在 , 插入数据库中

Right newRight = new Right();

newRight.setRightUrl(url);

this.saveOrUpdateRight(newRight);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值