oa_03


機構管理の業務ロジックを完了した後,プレゼンテーション層の実現を考える.
1、
まずページの流れを計画し、計画から全体的な概念を得て、これらの全体的な概念に基づいてActionForm/Actionおよび関連するプロファイルを作成します.
このステップの目的は、プログラムが正常に動作することを保証することです.
2、
各機能を段階的に深く実現し、簡単から複雑まで
本プロジェクトで重点的に理解する:
MVCモードでのパラメータ転送
Struts例外処理スキーム
package com.bjsxt.oa.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

import com.bjsxt.oa.manager.SystemException;

public class SystemExceptionHandler extends ExceptionHandler {

	@Override
	public ActionForward execute(Exception ex, ExceptionConfig ae,
			ActionMapping mapping, ActionForm formInstance,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		//
        ActionForward forward = null;
        ActionMessage error = null;

        // Build the forward from the exception mapping if it exists
        // or from the form input
        if (ae.getPath() != null) {
            forward = new ActionForward(ae.getPath());
        } else {
            forward = mapping.getInputForward();
        }
        
        //  SystemException  
        if(ex instanceof SystemException){
        	SystemException se = (SystemException)ex;
        	String key = se.getKey();
        	if(key == null){
        		error = new ActionMessage(ae.getKey(),se.getMessage());
        	}else{
        		if(se.getValues() != null){
        			error = new ActionMessage(key,se.getValues());
        		}else{
        			error = new ActionMessage(key);
        		}
        	}
        	
        	this.storeException(request, key, error, forward, ae.getScope());
        	
        	return forward;
        }
		
		return super.execute(ex, ae, mapping, formInstance, request, response);
	}

}
package com.bjsxt.oa.manager;

public class SystemException extends RuntimeException {
	private String key;
	private Object[] values;
	public String getKey() {
		return key;
	}
	public Object[] getValues() {
		return values;
	}
	public SystemException() {
		super();
	}
	public SystemException(String message, Throwable throwable) {
		super(message, throwable);
	}
	public SystemException(String message) {
		super(message);
	}
	public SystemException(Throwable throwable) {
		super(throwable);
	}
	
	public SystemException(String key,String message) {
		super(message);
		this.key = key;
	}
	
	public SystemException(String key,Object value,String message) {
		super(message);
		this.key = key;
		this.values = new Object[]{value};
	}
	
	public SystemException(String key,Object[] values,String message) {
		super(message);
		this.key = key;
		this.values = values;
	}
	
}
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
	<form-beans>
		<form-bean name="orgForm" type="com.bjsxt.oa.web.forms.OrgActionForm"></form-bean>
	</form-beans>
	<global-exceptions>
		<exception 
			path="/common/exception.jsp" 
			handler="com.bjsxt.oa.web.SystemExceptionHandler" 
			scope="request" 
			key="errors.detail" 
			type="java.lang.Exception">
		</exception>
	</global-exceptions>
	<global-forwards>
		<forward name="pub_add_success" path="/common/pub_add_success.jsp"></forward>
		<forward name="pub_del_success" path="/common/pub_del_success.jsp"></forward>
		<forward name="pub_update_success" path="/common/pub_update_success.jsp"></forward>
	</global-forwards>
	<action-mappings>
		<action 
			path="/org"
			type="org.springframework.web.struts.DelegatingActionProxy"
			name="orgForm"
			scope="request"
			parameter="method"
			
		>
			<forward name="index" path="/org/index.jsp"></forward>
			<forward name="add_input" path="/org/add_input.jsp"></forward>
			<forward name="update_input" path="/org/update_input.jsp"></forward>
		</action>
	</action-mappings>

    <message-resources parameter="MessageResources" />
</struts-config>
package com.bjsxt.oa.web.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.bjsxt.oa.manager.OrgManager;
import com.bjsxt.oa.model.Organization;
import com.bjsxt.oa.web.forms.OrgActionForm;

public class OrgAction extends DispatchAction {

	private OrgManager orgManager;
	
	/**
	 *      
	 */
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//
		
		OrgActionForm oaf = (OrgActionForm)form;
		int parentId = oaf.getParentId();
		List orgs = orgManager.searchOrgs(parentId);
		request.setAttribute("orgs", orgs);
		
		int ppid = 0;
		if(parentId != 0){
			Organization parent = orgManager.findOrg(parentId);
			if(parent.getParent() != null){
				ppid = parent.getParent().getId();
			}
		}
		request.setAttribute("ppid", ppid);
		
		return mapping.findForward("index");
	}
	
	/**
	 *       
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward addInput(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		return mapping.findForward("add_input");
	}

	//      
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		OrgActionForm oaf = (OrgActionForm)form;
		
		Organization org = new Organization();
		
		BeanUtils.copyProperties(org, oaf);
		
		orgManager.addOrg(org, oaf.getParentId());
		
		return mapping.findForward("pub_add_success");
	}
	
	public ActionForward del(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		OrgActionForm oaf = (OrgActionForm)form;
		int id = oaf.getId();

//		try{
			orgManager.delOrg(id);
//		}catch(Exception e){
			
//			ActionMessages msgs  = new ActionMessages();
//			
//			ActionMessage msg = new ActionMessage()
//			
//			msgs.add("m", msg);
			
			//        
//			request.setAttribute(Globals.MESSAGES_KEY, msgs);
//			saveMessages(request, msgs);
			
			//        
//			request.setAttribute(Globals.ERROR_KEY, msgs);
//			saveErrors(request, msgs);
//			
//			return mapping.findForward("org_exception");
//		}
		return mapping.findForward("pub_del_success");
	}	
	
	public ActionForward updateInput(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			return mapping.findForward("update_input");
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			return mapping.findForward("pub_update_success");
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}
}

public.js
/*
 *      
 * f:    
 * n:     
 * w:     
 * h:     
 * s:        ,1:    ;0:     
 */
function openWin(f,n,w,h,s){
	sb = s == "1" ? "1" : "0";
	l = (screen.width - w)/2;
	t = (screen.height - h)/2;
	sFeatures = "left="+ l +",top="+ t +",height="+ h +",width="+ w
			+ ",center=1,scrollbars=" + sb + ",status=0,directories=0,channelmode=0";
	openwin = window.open(f , n , sFeatures );
	if (!openwin.opener)
		openwin.opener = self;
	openwin.focus();
	return openwin;
}

/*
 *       
 */
function openDeleteDialog(url,confirmString){
	var c = confirmString;
	if(c == null || c == ''){
		c = "         ?";
	}
	if(confirm(c)){
		return window.showModalDialog(url,"window123","dialogHeight:234px;dialogWidth:271px;resizable:no;help:yes;status:no;scroll:no");
	}
	return false;
}

/*
 *     
 */
function del(url,info){
	if(openDeleteDialog(url,info)){
		window.location.reload(true);
	}
}

/*
 *   checkbox
 */
function checkAll( chkName, checkboxName, pageSize ) {
    var src = event.srcElement;
	var chkN=eval("document.all."+chkName);

    if (src.checked) {
		chkN[0].checked = true;
		chkN[1].checked = true;
		for(var i=0; i<pageSize; i++) {
			var chk = eval("document.all." + checkboxName + i);
			if (chk) {
				chk.checked=true;
			}
    	}
    } else {
		chkN[0].checked = false;
		chkN[1].checked = false;
    	for(var i=0; i<pageSize; i++) {
			var chk = eval("document.all." + checkboxName + i);
			if(chk) {
				chk.checked=false;
			}
    	}
    }
}

/*
 * 
 */
function makePages(maxPage, selectedPage, selectName) {
	var sel=eval("document.all."+selectName);
	sel.length=0;
	for(var i=1; i<=maxPage; i++) {
		sel.options[i]=new Option(i,i);
		if(sel.options[i]==selectedPage) {
			sel.options[i].selected=true;
		}
	}
}

/*
 *      
 */
function replaceStr( str ) {
    var re="/( )/gi";
    str = str.replace(re,"");
    re="/\</gi";
    str = str.replace(re,"&lt;");

    return str;
}

/*
 *       
 */
function LTrim(str) {
    var whitespace = new String(" \t
\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(0)) != -1) { var j=0, i = s.length; while (j < i && whitespace.indexOf(s.charAt(j)) != -1) { j++; } s = s.substring(j, i); } return s; } /* * */ function RTrim(str) { var whitespace = new String(" \t
\r"); var s = new String(str); if (whitespace.indexOf(s.charAt(s.length-1)) != -1) { var i = s.length - 1; while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) { i--; } s = s.substring(0, i+1); } return s; } /* * */ function Trim(str) { return RTrim(LTrim(str)); } /* * */ function exeOperation( exePath ){ var obj = new ActiveXObject("Microsoft.XMLHTTP"); obj.open("post",exePath,false); obj.send(); var res = obj.responseText; var rs = Trim(res); if (rs.indexOf('true',0) != -1) { return true; } else { return false; } } /* * */ function exeValidate( exePath ){ var obj = new ActiveXObject("Microsoft.XMLHTTP"); obj.open("post",exePath,false); obj.send(); var res = obj.responseText; var rs = Trim(res); if (rs.indexOf('validate_login_user',0) != -1) { return true; } else { return false; } } /* * */ function validate_date( exePath ) { var obj = new ActiveXObject("Microsoft.XMLHTTP"); obj.open("post",exePath,false); obj.send(); var res = obj.responseText; var rs = Trim(res); var begin_str = "<!--begin-->"; var beginIndex = rs.indexOf(begin_str) + begin_str.length; var endIndex = rs.indexOf("<!--end-->"); rs = ((beginIndex >= 0) && (endIndex >= 0)) ? rs.substring(beginIndex,endIndex) : ""; return Trim(rs); } /* * */ function checkNumber(name, TempS) { for(Count=0;Count<TempS.length;Count++) { TempChar=TempS.substring(Count,Count+1); RefString="0123456789"; if (RefString.indexOf(TempChar,0)==-1) { alert(" "); eval("document.all." + name).focus(); return false; } } } /* * */ function chksafe(a){ fibdn = new Array ("'" ,"\\"); i=fibdn.length; j=a.length; for (ii=0; ii<i; ii++) { for (jj=0; jj<j; jj++) { temp1=a.charAt(jj); temp2=fibdn[ii]; if (temp1==temp2){ return false; } } } return true; } /* * */ function fucCheckNUM(NUM){ var i,j,strTemp; strTemp="0123456789"; if ( NUM.length== 0) return false; for (i=0;i<NUM.length;i++) { j=strTemp.indexOf(NUM.charAt(i)); if (j==-1){ return false; } } return true; } /* * */ function fucCheckLength(strTemp) { var i,sum; sum=0; for(i=0;i<strTemp.length;i++) { if ((strTemp.charCodeAt(i)>=0) && (strTemp.charCodeAt(i)<=255)) { sum=sum+1; } else { sum=sum+2; } } return sum; } /* * */ function chkElements( name, errMsg, max_length, lengthMsg ) { var el_name = eval("document.all." + name); var v = el_name.value; if (!chksafe(v)) { el_name.focus(); alert(errMsg); return false; } else if (fucCheckLength(v) > max_length) { el_name.focus(); alert(lengthMsg); return false; } return true; } /* * */ function checkNullStr(name, msg) { var el_name = eval("document.all."+name); if (Trim(el_name.value).length==0) { alert(msg); el_name.focus(); return false; } return true; } /* * */ function GetDate(nText,para){ var v_url = para=="1"?"./common/data.html":"../../common/data.html"; var reVal = window.showModalDialog(v_url, 'data',"status:no;center:yes;scroll:no;resizable:no;dialogWidth:255px;dialogHeight:260px"); if (reVal != null) { var n = eval("document.all." + nText); n.value=reVal; } } /* * */ function DrawImage(ImgD,iwidth,iheight){ var flag=false; var image=new Image(); image.src=ImgD.src; if(image.width>0 && image.height>0){ flag=true; if(image.width/image.height>= iwidth/iheight){ if(image.width>iwidth){ ImgD.width=iwidth; ImgD.height=(image.height*iwidth)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } // ImgD.alt=image.width+"×"+image.height; }else{ if(image.height>iheight){ ImgD.height=iheight; ImgD.width=(image.width*iheight)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } // ImgD.alt=image.width+"×"+image.height; } } ImgD.style.visibility = "visible"; } /* * Tab */ function enterTab(){ if(event.keyCode==13){ oElement = document.activeElement; if(oElement.tagName != "TEXTAREA" && oElement.type != "button") event.keyCode=9; return ; } } /* * */ function objectEval(text) { text = text.replace(/
/g, " "); text = text.replace(/\r/g, " "); if (text.match(/^\s*\{.*\}\s*$/)) { text = "[" + text + "]"; } return eval(text)[0]; } /* * * action - Action * method - * title - message * name - name */ function openLeaderQuery(action,method,title,name){ openWin("../../common/selectStaff.jsp?action="+action+"&method="+method+"&title="+title+"&name="+name,"public_leader_find_page","400","150"); } /* * */ function chgColor(){ var v_table = document.all["PowerTable"]; var v_row = v_table.rows[1]; var len = v_row.cells.length; for(var i=0;i<len;i++){ var v_cell = v_row.cells[i]; v_cell.style.backgroundColor = "yellow"; } } /* * */ function chgColor2(){ var v_table = document.all["PowerTable"]; var rows_count=v_table.rows.length; var v_row,v_cell,temp_len,len; var rowspan=0; //get rowspan if (v_table.rows.length > 1) { len = v_table.rows[1].cells.length; for (var r=2; r < rows_count; r++) { v_row = v_table.rows[r]; temp_len = v_row.cells.length; if (temp_len==len) { rowspan=r-1; break; } } rowspan=(rowspan>0) ? (rowspan+1) : rows_count; for(var r=1; r < rowspan; r++) { v_row=v_table.rows[r]; for (var t=0; t < v_row.cells.length; t++) { v_cell = v_row.cells[t]; v_cell.style.backgroundColor = "yellow"; } } } } /* * */ function addLoadEvent(func) { var oldonload = window.onload; if (typeof(window.onload) != "function") { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } //adsName: ,adsUrl: ,sTime: ( ) add by wujie 2005.12.12 function PopAds(adsName,adsUrl,sTime,number,w,h,s) { if(document.cookie.indexOf(adsName)==-1) { window.open(adsUrl,adsName); self.focus(); var expireDate = new Date(); var lefttime = 1000 * (3600 * sTime); expireDate.setTime (expireDate.getTime() + lefttime); document.cookie = adsName +"=yes" + "; expires=" + expireDate.toGMTString() + ";"; } openWin(adsUrl,number,w,h,s); } document.onkeydown=enterTab;
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@include file="/common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<link href="style/oa.css" rel="stylesheet" type="text/css">
<script language="javascript" src="script/public.js"></script>
<title>      </title>
</head>
<body>
<center>
<form action="org.do" method="post">
<TABLE class="tableEdit" border="0" cellspacing="1" cellpadding="0" style="width:580px;">
	<TBODY>
		<TR>
			<!--      、        -->
			<td align="center" class="tdEditTitle">      </TD>
		</TR>
		<TR>
			<td>
			<!--        -->

<input type="hidden" name="method" value="add">
<input type="hidden" name="parentId" value="${orgForm.parentId }">
<table class="tableEdit" style="width:580px;" cellspacing="0" border="0" cellpadding="0">
	<tr>
		<td class="tdEditLabel" >    </td>			
		<td class="tdEditContent"><input type="text" name="name">
		</td>
		<td class="tdEditLabel" >    </td>			
		<td class="tdEditContent"><input type="text" name="description"></td>
	</tr>
</table>

			<!--        -->
			</td>
		</TR>
	</TBODY>
</TABLE>

<TABLE>
		<TR align="center">
			<TD colspan="3" bgcolor="#EFF3F7">
			<input type="submit" name="saveButton"
				class="MyButton" value="      "> 
			<input type="button" class="MyButton"
				value="    " onclick="window.close()">
			</TD>
		</TR>
</TABLE>
</form>
</center>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@include file="/common/common.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<link href="style/oa.css" rel="stylesheet" type="text/css">
<script language="javascript" src="script/public.js"></script>
<title>    </title>
</head>
<BODY bgColor=#dee7ff leftMargin=0 background="" topMargin=0 marginheight="0" marginwidth="0">
<center>
      <TABLE width="778" border=0 cellPadding=0 cellSpacing=0 borderColor=#ffffff bgColor=#dee7ff style="FONT-SIZE: 10pt">
        <TBODY>
          <TR height=35>
            <TD align=middle width=20 background=images/title_left.gif 
          bgColor=#dee7ff></TD>
            <TD align=middle width=120 background=images/title_left.gif 
          bgColor=#dee7ff><FONT color=#f7f7f7>     <font color="#FFFFFF">&nbsp;</font></FONT> </TD>
            <TD align=middle width=11 background=images/title_middle.gif 
          bgColor=#dee7ff><FONT color=#f7f7f7>&nbsp;</FONT> </TD>
            <TD align=middle background=images/title_right.gif 
          bgColor=#dee7ff><FONT color=#f7f7f7>&nbsp;</FONT> </TD>
          </TR>
        </TBODY>
      </TABLE>
      <TABLE width="778" border=0 align=center cellPadding=0 cellSpacing=0 borderColor=#ffffff style="FONT-SIZE: 10pt">
        <TBODY>
          <TR>
            <TD width="82%" height=14 align=right vAlign=center noWrap>
            </TD>
            <TD width="18%" align=right vAlign=center noWrap> </TD>
          </TR>
          <TR>
            <TD height=14 align=right vAlign=center noWrap>
            	<!--           -->
            </TD>
            <TD height=14 align="left" vAlign=center noWrap>
            <% 
            /**
            *      “  ”,“  ”   
            * <input type="image" name="find" value="find" src="images/cz.gif">
            * &nbsp;&nbsp;&nbsp;&nbsp; 
            * <a href="#" onClick="BeginOut('document.do?method=addInput','470')">
            * <img src="images/addpic.gif" border=0 align=absMiddle style="CURSOR: hand"></a>
            */
            %>
            <a href="#" onclick="openWin('org.do?method=addInput&parentId=${orgForm.parentId }','addperson',600,200);">      </a>
            <a href="org.do?parentId=${ppid }">  </a>
            </TD>
          </TR>
          <TR>
            <TD height=28 colspan="2" align=right vAlign=center noWrap background=images/list_middle.jpg>&nbsp;&nbsp;
            <!--              -->
            </TD>
          </TR>
        </TBODY>
      </TABLE>
      <table width="778" border="0" cellPadding="0" cellSpacing="1" bgcolor="#6386d6">
          <!--       -->
	      <tr bgcolor="#EFF3F7" class="TableBody1">
		      <td width="5%" height="37" align="center"><b>  </b></td>
		      <td width="18%" height="37" align="center"><B>    </B></td>
		      <td width="18%" height="37" align="center"><b>    </b></td>
		      <td width="18%" height="37" align="center"><b>     </b></td>
              <td width="5%" height="37" align="center"><b>  </b></td>
          </tr>
          <!--       -->
          <c:if test="${!empty orgs}">
          <c:forEach items="${orgs }" var="org">
	      <tr bgcolor="#EFF3F7" class="TableBody1" onmouseover="this.bgColor = '#DEE7FF';" onmouseout="this.bgColor='#EFF3F7';">
		      <td align="center" vAlign="center">${org.id }</td>
	          <td align="center" vAlign="center"><a href="org.do?parentId=${org.id }">${org.name }</a></td>
	          <td align="center" vAlign="center">${org.sn }</td>
	          <td align="center" vAlign="center">${org.parent.name }</td>
	          <td align="center" vAlign="center">
	          	<a href="#" onclick="del('org.do?method=del&id=${org.id }')">  </a>
	          </td>
        </tr>
        </c:forEach>
		</c:if>
        <!--           ,         -->
	    <c:if test="${empty orgs}">
	    <tr>
	    	<td colspan="7" align="center" bgcolor="#EFF3F7" class="TableBody1" onmouseover="this.bgColor = '#DEE7FF';" onmouseout="this.bgColor='#EFF3F7';">
	    	         
	    	</td>
	    </tr>
	    </c:if>
      </table>
      <TABLE width="778" border=0 align=center cellPadding=0 cellSpacing=0 borderColor=#ffffff style="FONT-SIZE: 10pt">
        <TBODY>
          <TR>
            <TD height=28 align=right vAlign=center noWrap background=images/list_middle.jpg>&nbsp;&nbsp;
            <!--              -->
    		</TD>
          </TR>
        </TBODY>
      </TABLE>
</center>

</body>

</html>