java基于包结构的请求路由实现实例分享
webfilter.java
package com.hongyuan.route;
import java.io.file;
import java.io.ioexception;
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;
public class webfilter implements filter {
public static final string base_package="com.hongyuan";
public static final string class_flag="action";
@override
public void destroy() {}
@override
public void dofilter(servletrequest request, servletresponse response,filterchain chain) throws ioexception, servletexception {
if(!hasresouce(request)){
string requestpath=((httpservletrequest)request).getservletpath();
if(requestpath.indexof(".")>=0){
requestpath=requestpath.substring(0, requestpath.indexof("."));
}
if(requestpath.endswith("/")){
requestpath=requestpath.substring(0, requestpath.length()-1);
}
//获取请求的类全限定名
string classname=base_package+requestpath.replaceall("/", ".")+class_flag;
//获取请求方法名称
string methodname=request.getparameter("method");
if(methodname==null||"".equals(methodname.trim())){
methodname="index";
}
try {
//获取处理类并响应请求
class clazz=class.forname(classname);
object instance=this.initcontext(clazz,request,response);
method method=clazz.getmethod(methodname, new class[]{});
object result=method.invoke(instance, new object[]{});
response.getwriter().print(result);
} catch (exception e) {
e.printstacktrace(response.getwriter());
}
}else{
chain.dofilter(request, response);
}
}
//判断是否存在请求的资源
private boolean hasresouce(servletrequest request) {
string realpath=request.getservletcontext().getrealpath(((httpservletrequest)request).getservletpath());
file resouce=new file(realpath);
if(resouce.exists()){
return true;
}else{
return false;
}
}
//初始化上下文
private object initcontext(class clazz, servletrequest request,
servletresponse response) throws exception{
object instance=clazz.newinstance();
clazz.getmethod("setrequest",new class[]{servletrequest.class}).invoke(instance, new object[]{request});
clazz.getmethod("setresponse", new class[]{servletresponse.class}).invoke(instance, new object[]{response});
return instance;
}
@override
public void init(filterconfig arg0) throws servletexception {}
}
baseaction.java
package com.hongyuan.route;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
public abstract class baseaction {
protected servletrequest request=null;
protected servletresponse response=null;
public servletrequest getrequest() {
return request;
}
public void setrequest(servletrequest request) {
this.request = request;
}
public servletresponse getresponse() {
return response;
}
public void setresponse(servletresponse response) {
this.response = response;
}
}