思维导图
解决子控制器初始化问题
缺陷:需要频繁改动init中代码;
解决方案:
1.必须有配置文件 config.xml
2.配置文件config.xml中要包含处理业务的子控制器
3.读取到配置文件config.xml中的对应的处理浏览器请求的子控制器
代码:
package com.zzf.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tyf.model.ActionModel;
import com.tyf.model.ConfigModel;
import com.tyf.model.ConfigModelFactory;
import com.tyf.model.ForwardModel;
import com.tyf.web.BookAction;
import com.tyf.web.GoodsAction;
@WebServlet("*.action")
public class DispatchServlet extends HttpServlet {
//存放子控制器的容器
private ConfigModel configModel = null;
@Override
public void init() throws ServletException {
try {
configModel = ConfigModelFactory.build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = req.getRequestURI();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.pop(url);
String type = actionModel.getType();
try {
ActionSupport action = (ActionSupport) Class.forName(type).newInstance();
action.execute(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
解决参数实体类封装问题
缺陷:对于前端传参,实体类属性封装req.getparameter("")代码 是重复的;
解决方案:泛型+反射;
代码:
ActionSupport action = (ActionSupport) Class.forName(type).newInstance();
if (action instanceof ModelDriver) {
ModelDriver m = (ModelDriver) action;
Object obj = m.getModel();
//有对象
//接受所有前端JSP传递到后台的参数
Map<String, String[]> parameterMap = req.getParameterMap();
//给对象赋值
BeanUtils.populate(obj, parameterMap);
}
运行结果:
解决结果集代码重复问题
缺陷:
1.出现大量重复代码
2.不好管理
思路:
1.方法执行完毕必须有一个返回值
2.通过返回值判断是重定向还是转发
3.通过返回值决定跳转哪一个页面
解决方案:在一个地方统一管理重定向还是转发,并且是定位跳转到哪一个页面
代码:
String res = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(res);
if (forwardModel.isRedirect()) {
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
else {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}