自定义MVC

来源:互联网 发布:java 线程死锁 编辑:程序博客网 时间:2024/05/16 09:43


1、定义个servlet(ActionServlet)控制所有的*.do请求


2、获得请求路径(request.getRequestURI()),截取到后面的请求名(cname)


3、在webinf下创建一个config.properties文件,保存一个键值对,
根据不同的请求得到其对应的Class,同时创建好对应的处理类


4、在servlet的init方法中加载配置文件
Properties config=new Properties();
String path=this.getServletContext.getRealPath();//得到其绝对路径
path=path+"/WEB-INF/config.properties";
config.load(new FileInputStream(path));//加载到内存中来
this.getServletContext.setAttribute("config",config);//存入到application中


5、到dopost方法中取出application中的数据,结合前面取到的请求名得到其对应的类名
Properties config=(Properties)this.getServletContext.getAttribute("config");
String className=config.getProperty(cname);


6、将"/WEB-INF/config.properties"存入到web.xml文件中,并通过代码取出
String sname=this.getServletContext().getInitParameter("config");


7、根据取出来的类名(全路径名),实例化对象
Class.forName(classname).newInstance();


8、新建一个接口(Action),声明方法execute();将所有的实现类继承action接口


9、将Class.forName返回的对象统一为转换为Action,再统一的调用execute()方法(多态)


10、修改接口的方法execute(),让其带参数(request,response),其所有的继承类对应的做修改,
保证 能从ActionServlet传送到对应页面


11、将Action存入到一个池中,步骤:先在init方法中建立一个池(Properties),
再在dopost方法中判断,以保证每一个类只会 被实例化一次




代码如下:

@Override
public void init(ServletConfig config) throws ServletException {
try {
//3.加载配置文件config.properties
Properties properties=new Properties();
Properties propertiesObject=new Properties();
//3.1获取服务器的路径
String serverPath=config.getServletContext().getRealPath("/");
FileInputStream fis=new FileInputStream(serverPath+"WEB-INF/config.properties");
properties.load(fis);

//将properties存放到application中
config.getServletContext().setAttribute("properties", properties);
config.getServletContext().setAttribute("propertiesObject", propertiesObject);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}





@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

//1.获取请求路径
String uri=req.getRequestURI();

//2.截取
//2.1获取最后一个斜杠的位置
int lastXiePosition=uri.lastIndexOf("/");
//2.2获取最后一个点的位置
int lastPointPosition=uri.lastIndexOf(".");
uri=uri.substring(lastXiePosition+1, lastPointPosition);
System.out.println("请求路径:"+uri);

//从application中获取properties
Properties properties=(Properties) req.getSession().getServletContext().getAttribute("properties");

//3.2根据键获取值
String className=properties.getProperty(uri);
System.out.println("获取到相对应的全限定名为:"+className);

Properties propertiesObject=(Properties) req.getSession().getServletContext().getAttribute("propertiesObject");

TotalDo total=(TotalDo) propertiesObject.get(className);

//3.3 根据类的全限定名 来 实例化 该对象
try {
if(total==null){
System.out.println("初始化对象");
total=(TotalDo)Class.forName(className).newInstance();
//必须存放
propertiesObject.put(className, total);
}
total.execute(req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}