带整理

 

 

 

private static Map<String, ServletAction> actionMap = new HashMap<String, ServletAction>(); static { actionMap.put("doShowMain", new showMainAction()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = null; String actionName = request.getParameter("action"); ServletAction action = actionMap.get(actionName); result = action.excute(request, response); request.getRequestDispatcher(result).forward(request, response); } public interface ServletAction { String excute(HttpServletRequest request, HttpServletResponse response); } public class showMainAction implements ServletAction { @Override public String excute(HttpServletRequest request, HttpServletResponse response) { List<BookType> bookTypeList = new ArrayList<BookType>(); BookTypeDao bookTypeDao = new BookTypeDao(); bookTypeList = bookTypeDao.selectAllBookType(); ServletContext application = request.getSession().getServletContext(); application.setAttribute("bookTypeList",bookTypeList); return null; } } ---------------------------------------------- 效率问题,所以。。。 可以由action的值,通过java的发射机制实现对象的动态创建,但好像还不太好。 更好的方法是,通过取得URI来得知请求的Action,所以。。。。 // 得到actionName String uri = request.getRequestURI(); int end = uri.indexOf(".do"); int start = uri.lastIndexOf("/"); String actionName = uri.substring(start, end); try { Class<?> actionClass = Class.forName(actionName); action = (ServletAction)actionClass.newInstance(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch bloc } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = this.getAction(actionName).excute(request, response); request.getRequestDispatcher(result).forward(request, response); ------------------------------------------------------ 效率,每次请求都创建一个对象,还是不好。。。 可以加一个ACTION_CACHE,即还是开始的map。。。 private static final Map<String, ServletAction> ACTION_CACHE = new HashMap<String, ServletAction>(); private ServletAction getAction(String actionName){ String fullName = "com.shop.action."+actionName; ServletAction action = ACTION_CACHE.get(fullName); if(action == null){ try { Class<?> actionClass = Class.forName(fullName); action = (ServletAction)actionClass.newInstance(); ACTION_CACHE.put(fullName, action); } catch (ClassNotFoundException e) { // TODO Auto-generated catch bloc } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return action; } --------------------------------------------------- 还是不好。。。 使用LRUMAP。。。。  

 

 

 

你可能感兴趣的:(带整理)