}
return actionConfig.actionInfos.get(path);
}
}
ActionServlet类:
public class ActionServlet extends HttpServlet {
public void init() throws ServletException {
// 根据参数去解析xml
try {
// 初始化action
String config = this.getInitParameter("action-config");
URL url = getServletContext().getResource(config);
ActionConfig.init(url);
// 初始化DataSource
config = this.getInitParameter("db-config");
url = getServletContext().getResource(config);
DbConfig.init(url);
// 初始化系统配置SysConfig
config = this.getInitParameter("sys-config");
url = getServletContext().getResource(config);
SysConfig.init(url);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
protected void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String path = parseURI(request);
ActionInfo actionInfo = ActionConfig.getActionInfo(path);
try {
if (actionInfo == null) {
throw new ActionException("不能找到“" + path + "”的Action映射关系");
}
Action action = ActionFactory.createAction(actionInfo);
// 为Action创建数据连接对象Connection,以提供处理请求时使用,请求处理完毕,关才连接
Connection conn=null;
String forward = null;
try {
conn = ConnFactory.getConn(SysConfig.getDbName());
action.setConn(conn);
forward = action.process(request, response);
} catch (Exception e) {
throw e;
} finally {
conn.close();
}
ActionForward actionForward = actionInfo.findActionForward(forward);
if (actionForward == null) {
throw new ActionException("在action:“" + path + "”中不能找到“"
+ forward + "”的映射关系");
}
if (actionForward.getRedirect()) {
response.sendRedirect(actionForward.getPath());
} else {
request.getRequestDispatcher(actionForward.getPath()).forward(
request, response);
}
} catch (ActionException e) {
e.printStackTrace();
} catch (Exception e) {
request.getRequestDispatcher("error.jsp")
.forward(request, response);
e.printStackTrace();
}
}
private String parseURI(HttpServletRequest request) {
String path = request.getRequestURI();
String contextPath = request.getContextPath();
if (path.startsWith(contextPath)) {
path = path.substring(contextPath.length());
}
int end = path.lastIndexOf(".");
path = path.substring(0, end);
return path;
}
public void destroy() {
}
}
|