package com.hmf.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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.hmf.web.BookAction;
/**
?* 中央控制器
?* jsp:/book.action/goods.action/order.action
?* @author T440s
?*
?*/
@WebServlet("*.action")
public class DispatchServlet extends HttpServlet{
?? ?//当前中央控制器中所有子控制器的集合
?? ?private Map<String, ActionSupport> actions=new HashMap<String, ActionSupport>();
?? ?
?? ?/**
?? ? * 初始化所有子控制器到当前的中央控制器中
?? ? */
?? ?public void init() throws ServletException{
?? ??? ?actions.put("/book", new BookAction());
?? ?}
?? ?
?? ?protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
?? ??? ?doPost(req, resp);
?? ?}
?? ?
?? ?protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
?? ??? ?//把子控制器与浏览器请求关联起来 ? 处理请求的子控制器
?? ??? ?/**
?? ??? ? * 1.得到url->/book
?? ??? ? * 2.通过book字符串在actions找到BookAction
?? ??? ? * 3.调用bookaction的add ?想要调用add ?就直接统一execute
?? ??? ? */
?? ??? ?//获取浏览器的请求地址
?? ??? ?String url = req.getRequestURI();
?? ??? ?url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
?? ??? ?ActionSupport action=actions.get(url);
?? ??? ?action.exectue(req, resp);
?? ?}
}
?
package com.hmf.framework;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
?* 作用:能够处理浏览器的“所有”请求,包括add/ref/other
?* BookServlet
?* @author T440s
?*
?*/
public class ActionSupport implements Action{
?? ?public void exectue(HttpServletRequest req, HttpServletResponse resp) {
?? ??? ?String methodName = req.getParameter("methodName");
?? ??? ?try {
?? ??? ??? ?Method m= this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
?? ??? ??? ?m.setAccessible(true);
?? ??? ??? ?m.invoke(this,req, resp);
?? ??? ?} catch (Exception e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ?}
}
?