MVC模式核心控制类有两部分组成,即,反射机制和DOM解析
public class ControllerServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOExecption{
//反射机制
String path = req.getServletPath();
path=path.substring(0,path.lastIndexOf("."));
String servletClassPath=null;
try{
servletClassPath = getServletClasspath(path);
Class servletClass = Class.forName(servletClassPath);
Class[] consClassParams = {};
Constructor consClass = servletClass.getConstructor(consClassParams);
Object[] consObjectParams = {};
Object consObject = consClass.newInstance(consObjectParams);
Class[] methodClassParam = {ServletRequest.class,ServletResponse.class};
Method methodClass = servletClass.getMethod("service",methodClassParam);
Object[] methodObjectParam = {req,resp};
methodClass.invoke(consObject,methodObjectParams);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
doGet(req,resp);
}
//Dom解析方法
public String getServletClasspath(String url) throws ParserConfigurationException, SAXException, IOException{
String type=null;
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse(ControlerServlet.class.getResourceAsStream("../../../../../../config.xml"));
Element root=doc.getDocumentElement();
NodeList mappings=root.getElementsByTagName("mappings");
Element mapps=(Element)mappings.item(0);
NodeList maps=mapps.getElementsByTagName("mapping");
for(int i=0;i<maps.getLength();i++){
Element map=(Element)maps.item(i);
String path=map.getAttribute("path");
if(url.equals(path)){
type=map.getAttribute("type");
break;
}
}
return type;
}
}