lt;url-pattern>/controller/*</url-pattern>
</servlet-mapping>
struts简单案例-适合初学者(一)(3)
时间:2011-08-05
为了从附加路径信息中获得的字符串映射到一个特定的操作实例上,当然,同样有很多策略可供选择,其中最灵活的就是把这种映射外部化,例如可以通过一个XML文件。
为了简单起见,我们在这里建立一个单独的组件,用于封装这种映射。
public class ActionHelper {
private static HashMap actions = new HashMap();
static {
actions.put(”Login”, “com.sample.LoginAction”);
}
public static Action getAction(String name) {
Action action = null;
try {
Class c = Class.forName((String) actions.get(name));
action = (Action) c.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return action;
}
}
好了,以上就是要实现的一个简单的框架类FrontController,Action以及辅助的ActionHelper类
下一步是把所有这些处理插入到FrontController的processRequest方法中,这将是Web应用程序中所有请求的单一入口:
public class FrontController extends HttpServlet {
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String actionName =req.getPathInfo().substring(1);
Action action =ActionHelper.getAction(actionName);
String nextView =action.process(req, res);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(nextView);
dispatcher.forward(req, res);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
processRequest(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
processRequest(req, res);
}
}
具体相关内容可参见实例! |