Anatomia de uma solução - VRaptor linkTo para jsp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component | |
@ApplicationScoped | |
public class LinkToHandler implements StereotypeHandler { | |
private Map<String, Map<String, Linker>> linkTo = Maps.newHashMap(); | |
private final ServletContext context; | |
private final Router router; | |
public LinkToHandler(ServletContext context, Router router) { | |
this.context = context; | |
this.router = router; | |
context.setAttribute("linkTo", linkTo); //para ficar disponível para todos os jsps | |
} | |
public void handle(Class<?> type) { | |
String controller = type.getSimpleName(); | |
context.setAttribute(controller, controller); //para poder usar linkTo[ProdutoController] | |
Map<String, Linker> methodMap = Maps.newHashMap(); | |
List<Method> methods = new Mirror().on(type).reflectAll().methods(); | |
for (Method method : methods) { | |
if (!method.getDeclaringClass().equals(Object.class)) { | |
methodMap.put(method.getName(), new Linker(type, method)); | |
} | |
} | |
linkTo.put(controller, methodMap); | |
} | |
public Class<? extends Annotation> stereotype() { | |
return Resource.class; | |
} | |
class Linker extends ForwardingMap<Object, Linker> { | |
private final Method method; | |
private final Class<?> type; | |
private final Object[] args; | |
private final int index; | |
public Linker(Class<?> type, Method method) { | |
this(type, method, new Object[method.getParameterTypes().length], 0); | |
} | |
public Linker(Class<?> type, Method method, Object[] args, int index) { | |
this.type = type; | |
this.method = method; | |
this.args = args; | |
this.index = index; | |
} | |
@Override | |
protected Map<Object, Linker> delegate() { | |
return Maps.newHashMap(); | |
} | |
@Override | |
public Linker get(Object key) { | |
Object[] newArgs = args.clone(); //evitando cache indesejável de args | |
newArgs[index] = key; | |
return new Linker(type, method, newArgs, index + 1); | |
} | |
@Override | |
public String toString() { | |
return router.urlFor(type, method, args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment