============================================ Process.java package idv.senshaw.Business.Process; import idv.senshaw.Struts.Exception.*; import java.util.*; /** * 交易處理介面 * Last Modified Date:2002/12/27 * @author Senshaw * @version 1.2 */ public interface Process { public String doProcess(HashMap inputMap,HashMap outputMap) throws FailException; } =========================================== ========================================= employee idv.senshaw.Business.Process.EmployeeProcess ====================================== ================================= InitProcessService.java package idv.senshaw.Servlet; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import idv.senshaw.Struts.Util.ProcessService; /** * 在Application Server啟動時產生ProcessService,並存入ServletContext attribute
* Last Modified Date: 2002/12/27
* @author Senshaw * @version */ public class InitProcessService extends HttpServlet { private boolean isShowMsg = true; //是否顯示偵錯訊息 public void init() throws ServletException { ServletContext context = getServletContext(); String project_config = context.getInitParameter("project-config"); URL url = null; try { url = context.getResource(project_config); } catch (MalformedURLException ex) { System.out.println("InitProcessService error: "+ex); } ProcessService ps = new ProcessService(url); String ProjectName = context.getInitParameter("ProjectName"); context.setAttribute(ProjectName+"_ProcessService",ps); show("InitProcessService初始完成!"); } private void show(String msg) { if (isShowMsg) System.out.println("InitProcessService: "+msg); } //end public void show(String msg) } ====================================== ===================================== ProcessService.java package idv.senshaw.Struts.Util; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.*; import org.xml.sax.*; import java.io.*; import java.util.*; import java.sql.*; import java.net.*; import idv.senshaw.Business.Process.Process; /** * 透過project-config取得相關設定,產生Process instance存入HashMap
* Last Modified Date:2002/12/27
* @author Senshaw * @version */ public class ProcessService implements Serializable { boolean isShowMsg = true; //是否顯示偵錯訊息 HashMap serviceMap; public ProcessService(URL config_url) { serviceMap = new HashMap();    try { InputSource config_source = new InputSource(config_url.openStream()); //DOM process DOMParser myParser = new DOMParser(); myParser.parse(config_source); Document doc = myParser.getDocument(); Node node = doc.getFirstChild(); //root node NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { node = nodeList.item(i); if (node.getNodeName().equalsIgnoreCase("Processes")) { NodeList nodeList2 = node.getChildNodes(); for (int j = 0; j < nodeList2.getLength(); j++) { Node node2 = nodeList2.item(j); if (node2.getNodeName().equalsIgnoreCase("Process")) { NodeList nodeList3 = node2.getChildNodes(); String Pgid="",Class_name=""; for (int k = 0; k < nodeList3.getLength(); k++) { Node node3 = nodeList3.item(k); if (node3.getNodeName().equalsIgnoreCase("Pgid")) { Pgid = node3.getFirstChild().getNodeValue(); show("pgid="+Pgid); } else if (node3.getNodeName().equalsIgnoreCase("Class")) { Class_name = node3.getFirstChild().getNodeValue(); show("Class_name="+Class_name); } } //產生instance存入HashMap Object process = Class.forName(Class_name).newInstance(); serviceMap.put(Pgid,process); } } //end for (int j=0;j < nodeList2.getLength();j++)      } //end if (node.getNodeName().equalsIgnoreCase("Processes")) } //end for (int i = 0; i < nodeList.getLength(); i++) } catch(Exception ex) { System.out.println("ProcessService error: "+ex); }   } //end ProcessService() /** * 依pgid取得Process instance,若無對應值則傳回null; */ public Process getProcess(String pgid) { Process process = null; try { process = (Process)this.serviceMap.get(pgid); } catch (Exception ex) { } return process; } private void show(String msg) { if (isShowMsg) System.out.println("ProcessService: "+msg); } //end public void show(String msg) } ========================================== =============================================== MultiAction1.java package idv.senshaw.Struts.Action; import javax.servlet.http.*; import org.apache.struts.action.*; import java.util.*; import idv.senshaw.Business.Process.Process; import idv.senshaw.Struts.Exception.*; import idv.senshaw.Struts.Util.*; import idv.senshaw.DB.*; /** * 泛用型Action,若無特殊需求不須修改 * Last Modified Data:2003/01/09 * @author Senshaw * @version 1.3 */ public final class MultiAction1 extends Action { private boolean isShowMsg = true; //是否顯示偵錯訊息 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors = new ActionErrors(); HashMap inputMap = new HashMap(); //輸入資料用 HashMap outputMap = new HashMap(); //輸出資料用 //Data Access Ojbect DAOBean dao = new DAOBean(); inputMap.put("dao",dao); //系統控制parameter String command = request.getParameter("command"); show("command="+command); String pgid = request.getParameter("pgid"); show("pgid="+pgid); //將request parameter置入inputMap Enumeration enum_param = request.getParameterNames(); show("parameters"); while (enum_param.hasMoreElements()) { String key = (String)enum_param.nextElement(); String value = request.getParameter(key); show(key+"="+value); if (value == null) value = ""; inputMap.put(key,value); } //將session attribute為pgid開頭置入inputMap Enumeration enum_attr = request.getSession().getAttributeNames(); show("session attributes"); while (enum_attr.hasMoreElements()) { String key = (String)enum_attr.nextElement(); if (key.length() <= pgid.length() || !key.substring(0,pgid.length()).equals(pgid)) continue; Object value = request.getSession().getAttribute(key); show(key+"="+value); if (value == null) value = ""; //將key之前置碼"pgid_"去除後再傳入 String new_key = key.substring(pgid.length()+1); inputMap.put(new_key,value); } //運用ProcessService取得對應pgid之Process String ProjectName = this.servlet.getServletContext().getInitParameter("ProjectName"); ProcessService ps = (ProcessService)this.servlet.getServletContext().getAttribute(ProjectName+"_ProcessService"); Process process = ps.getProcess(pgid); show("pgid="+pgid); show("class name="+process.getClass().getName()); if (process == null) System.out.println("MultiAction1 error: Process not found!"); String forward_screen = ""; try { show("start process"); try { show("start process2"); forward_screen = process.doProcess(inputMap,outputMap); show("start process3"); } catch (FailException ex) { // fail 錯誤處理 if (ex.getErrorArgs() != null && ex.getErrorArgs().length > 0) errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ex.getErrorKey(),ex.getErrorArgs())); else errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(ex.getErrorKey())); forward_screen = ex.getForwardScreen(); this.saveErrors(request,errors); } catch (Exception ex2) { show("start process4"); System.out.println(process.getClass().getName()+" error: "+ex2); } show("end process"); //回傳資料處理 Iterator iter = outputMap.keySet().iterator(); show("outputMap key"); while (iter.hasNext()) { String key = (String)iter.next(); show(key); //若key值前七碼為"session",則將資料置入session,key值為pgid+"_"+(原key扣除前置"session_") if (key.length() > 8 && key.substring(0,8).equals(Command.SESSION_SCOPE)) { Object data = outputMap.get(key); request.getSession().setAttribute(pgid+"_"+key.substring(8),data); } //若key值前七碼為"request",則將資料置入request,key值為原key扣除前置"request_" if (key.length() > 8 && key.substring(0,8).equals(Command.REQUEST_SCOPE)) { Object data = outputMap.get(key); request.setAttribute(key.substring(8),data); } } //處理訊息 if (outputMap.containsKey(Command.MSG)) { Object obj_msg = outputMap.get(Command.MSG); show("msg not null"); MessageBean mb = (MessageBean)obj_msg; ActionMessages messages = new ActionMessages(); if (mb.getMsgArgs() != null && mb.getMsgArgs().length > 0) { show("msg have args"); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(mb.getMsgKey(),mb.getMsgArgs())); } else { show("msg no args"); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(mb.getMsgKey())); } this.saveMessages(request,messages); } } catch (Exception ex) { System.out.println("MultiAction1 error: "+ex); } show("forward_screen="+forward_screen); if (forward_screen != null && !forward_screen.equals("")) return (mapping.findForward(forward_screen)); else { System.out.println("MultiAction1 error: no forward!"); return (mapping.findForward("error")); } } private void show(String msg) { if (isShowMsg) System.out.println("MultiAction1: "+msg); } //end public void show(String msg) } ========================================== =========================================== FailException.java package idv.senshaw.Struts.Exception; /** * 錯誤處理Exceipton * Last Modified Date:2003/02/28 * @author Senshaw * @version 1.3 */ public class FailException extends Exception { /** * Struts Message Resource Key */ private String errorKey = ""; /** * Struts Message Resource arguments */ private Object[] errorArgs = null; /** * Struts Forward Screen Key */ private String forwardScreen = ""; /** * 供錯誤使用,不傳參數 * @param errorKey * @param forwardScreen */ public FailException(String errorKey,String forwardScreen) { super(errorKey); this.errorKey = errorKey; this.forwardScreen = forwardScreen; } /** * 供錯誤使用,要傳參數 * @param errorKey * @param forwardScreen */ public FailException(String errorKey,Object[] args,String forwardScreen) { super(errorKey); this.errorKey = errorKey; this.errorArgs = args; this.forwardScreen = forwardScreen; } /** * 取得Struts對應Error Key */ public String getErrorKey() { return errorKey; } /** * 取得Struts對應ForwardScreen Key */ public String getForwardScreen() { return forwardScreen; } /** * 取得Struts對應Error Arguments */ public Object[] getErrorArgs() { return errorArgs; } } =================================== ================================= Command.java package idv.senshaw.Struts.Util; /** * Action與Process溝通之命令 * Last Modified Date:2002/12/29 * @author Senshaw * @version 1.2 */ public class Command { /** * 通知Action有資料回傳,要存入session */ public static String SESSION_SCOPE = "session_"; /** * 通知Action有資料回傳,要存入request */ public static String REQUEST_SCOPE = "request_"; /** * 通知Action訊息 */ public static String MSG = "msg"; } ================================== ================================== MessageBean.java package idv.senshaw.Struts.Util; import java.io.Serializable; /** * 訊息處理JavaBean * Last Modified Date:2003/02/28 * @author Senshaw * @version 1.3 */ public class MessageBean implements Serializable { /** * Struts Message Resource Key */ private String msgKey = ""; /** * Struts Message Resource arguments */ private Object[] msgArgs = null; /** * 供訊息使用,不傳參數 * @param errorKey */ public MessageBean(String msgKey) { this.msgKey = msgKey; } /** * 供訊息使用,要傳參數 * @param errorKey * @param args */ public MessageBean(String msgKey,Object[] args) { this.msgKey = msgKey; this.msgArgs = args; } /** * 取得Struts對應Message Key */ public String getMsgKey() { return msgKey; } /** * 取得Struts對應Message Arguments */ public Object[] getMsgArgs() { return msgArgs; } } ====================================== ============================= EmployeeProcess.java package idv.senshaw.Business.Process; import javax.servlet.http.*; import org.apache.struts.action.*; import idv.senshaw.DB.*; import idv.senshaw.Struts.Exception.*; import idv.senshaw.Struts.Util.*; import java.util.*; /** * 員工基本資料商業邏輯入處理 * Last Modified Date:2003/01/09 * @author Senshaw * @version 1.0 */ public class EmployeeProcess implements Process { boolean isShowMsg = true; //是否顯示偵錯訊息 String forward_screen = "main"; //決定顯示畫面 DAOBean dao = null; String pgid=""; public String doProcess(HashMap inputMap,HashMap outputMap) throws FailException{ //接收參數 dao = (DAOBean)inputMap.get("dao"); show("get dao"); pgid = (String)inputMap.get("pgid"); show("get pgid"); String command = (String)inputMap.get("command"); show("get command="+command); String toRecord = (String)inputMap.get("toRecord"); String id = (String)inputMap.get("id"); String name = (String)inputMap.get("name"); String age = (String)inputMap.get("age"); String address = (String)inputMap.get("address"); if (command.equals("add") || command.equals("update")) { if (age == null || age.equals("")) age = "NULL"; } String sql = ""; //新增處理 if (command.equals("add")) { sql = "insert into employee ("+ "id,"+ "name,"+ "age,"+ "address "+ " ) values ( "+ "'"+id+"',"+ "'"+name+"',"+ ""+age+","+ "'"+address+"' "+ " ) "; show("sql="+sql); int affect_row = dao.executeUpdate(sql); if (affect_row > 0) { outputMap.put(Command.MSG,new MessageBean("messages.add.succeed")); show("insert succeed!"); } else { show("insert fail!"); throw new FailException("messages.add.fail",forward_screen); } //end if (affect_row > 0) return forward_screen; } else if (command.equals("query")) { //查詢處理 sql = "select * from employee where "; if (id != null && !id.equals("")) { sql += " id like '%"+id+"%' and "; } if (name != null && !name.equals("")) { sql += " name like '%"+name+"%' and "; } if (age != null && !age.equals("")) { sql += " age = "+age+" and "; } if (address != null && !address.equals("")) { sql += " address like '%"+address+"%' and "; } //去除結尾"and " if (sql.indexOf("and ") > 0) { sql = sql.substring(0,sql.length() - 4); } //不下任何條件則去除"where " if (sql.substring(sql.length() - 6).equalsIgnoreCase("where ")) { sql = sql.substring(0,sql.length() - 6); } //加order by sql += " order by id "; show("query sql="+sql); HashData hd = dao.executeQuery(sql); //存入session outputMap.put(Command.SESSION_SCOPE+"query_data",hd); outputMap.put(Command.SESSION_SCOPE+"query_sql",sql); outputMap.put(Command.SESSION_SCOPE+"status","update"); //將目前顯示筆數存入request attribute outputMap.put(Command.REQUEST_SCOPE+"toRecord","1"); return forward_screen; } else if (command.equals("clear")) { //清除處理 outputMap.put(Command.SESSION_SCOPE+"query_data",null); outputMap.put(Command.SESSION_SCOPE+"status","add"); return forward_screen; } else if (command.equals("update")) { //修改處理 sql = "update employee set "+ " name = '"+name+"',"+ " age = "+age+","+ " address = '"+address+"' "+ " where ID = '"+id+"' "; show("udpate sql="+sql); int affect_row = dao.executeUpdate(sql); if (affect_row > 0) { //重新讀取資料存入session String query_sql = (String)inputMap.get("query_sql"); HashData hd = dao.executeQuery(query_sql); outputMap.put(Command.SESSION_SCOPE+"query_data",hd); outputMap.put(Command.MSG,new MessageBean("messages.update.succeed")); outputMap.put(Command.REQUEST_SCOPE+"toRecord",toRecord); show("insert succeed!"); } else { throw new FailException("messages.update.fail",forward_screen); } //end if (affect_row > 0) return forward_screen; } else if (command.equals("delete")) { //刪除處理 sql = "delete from employee where "+ " ID = '"+id+"' "; show("sql="+sql); int affect_row = dao.executeUpdate(sql); if (affect_row > 0) { //重新讀取資料存入session String query_sql = (String)inputMap.get("query_sql"); HashData hd = dao.executeQuery(query_sql); outputMap.put(Command.SESSION_SCOPE+"query_data",hd); int i_toRecord = Integer.parseInt(toRecord); if ( i_toRecord > hd.getRowcount()) { toRecord = new Integer(hd.getRowcount()).toString(); } outputMap.put(Command.MSG,new MessageBean("messages.delete.succeed")); outputMap.put(Command.REQUEST_SCOPE+"toRecord",toRecord); show("delete succeed!"); } else { throw new FailException("messages.delete.fail",forward_screen); } //end if (affect_row > 0) return forward_screen; } //end if (command.equals("add")) return forward_screen; } private void show(String msg) { if (isShowMsg) System.out.println("EmployeeProcess: "+msg); } //end public void show(String msg) } ==================================== ================================== project-config /WEB-INF/project-config.xml ProjectName struts-jstl-xslt EncodingFilter EncodingFilter no description idv.senshaw.Servlet.EncodingFilter encoding UTF-8 EncodingFilter /* action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 3 detail 3 2 InitProcessService idv.senshaw.Servlet.InitProcessService 0 以下略... =================================== ================================== struts-config.xml異動如下: ================================= ========================================= employee.jsp <%--錯誤處理--%> ==================