自定义MVC (2)

来源:互联网 发布:淘宝如何使用网银支付 编辑:程序博客网 时间:2024/06/07 15:01

这次的MVC (2) 是上一次MVC  的优化版,优化的代码如下:

@Override
public void init(ServletConfig config) throws ServletException {
try {
Properties properties=new Properties();
Properties propertiesObject=new Properties();
String serverPath=config.getServletContext().getRealPath("/");
FileInputStream fis=new FileInputStream(serverPath+"WEB-INF/config.properties");
properties.load(fis);

config.getServletContext().setAttribute("config", properties);
config.getServletContext().setAttribute("object", propertiesObject);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}



}



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

try {
//1.获取路径
String uri=req.getRequestURI();
//2.截取
uri=uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf("."));

//3.获取
Properties properties=(Properties) req.getSession().getServletContext().getAttribute("config");
Properties propertiesObject=(Properties) req.getSession().getServletContext().getAttribute("object");

String className=properties.getProperty(uri);


//4.实例化对象
TotalDo totalDo=(TotalDo) propertiesObject.get(className);
if(totalDo==null){
totalDo=(TotalDo) Class.forName(className).newInstance();
propertiesObject.put(className, totalDo);
}

//获取表单的值,给了LoginForm
//获取表单上所有的参数名
String formUri=uri+"Form";
String classNameForm=properties.getProperty(formUri);//拿权限定名

Class clazzForm=Class.forName(classNameForm); //通过权限定名找到相应的类对象
TotalForm totalForm=(TotalForm)clazzForm.newInstance(); //

Enumeration enumeration=req.getParameterNames(); //获得参数名的集合
while(enumeration.hasMoreElements()){
String paramName=(String) enumeration.nextElement();
String paramValue=req.getParameter(paramName);


//利用反射技术 获取 LoginForm中所有的set方法
//拼接方法名
String menthodName="set"+paramName.substring(0,1).toUpperCase()+paramName.substring(1);
Method method=clazzForm.getDeclaredMethod(menthodName, String.class);
method.setAccessible(true);
//执行方法
method.invoke(totalForm, paramValue);
}
Jump jump=totalDo.execute(totalForm);
jump.jumpPage(req,resp);
} catch (Exception e) {
e.printStackTrace();

}



原创粉丝点击