CSDN博客

img youlin

开发心得

发表于2004/9/17 21:54:00  927人阅读

分类:

终于交出那该死的ts项目第一期,开发这样的“三边工程”真tm痛苦,下面就将痛苦的过程给罗列一下吧

查询条件:

子/项目名称?
____________________________

/**
         * 从数据库中得到预警级别参数设置
         */
        if (request.getAttribute("alarmClassCollection") == null) {
            log.info(
                "=============== Try to get alarm class ===============");
            ParameterDelegate pd = new ParameterDelegate();
            List alarmClassForm = pd.findParameterByName("ALARM_CLASS");

            List alarmClass = new ArrayList();
            alarmClass.add(new LabelValueBean("全部", "all"));
            Iterator it = alarmClassForm.iterator();
            while (it.hasNext()) {
                ParameterForm paramForm = (ParameterForm) it.next();
                alarmClass.add(new LabelValueBean(paramForm.getParaContent(),
                                                  new Integer(paramForm.
                    getParaCode()).toString()));
            }
            request.setAttribute("alarmClassCollection", alarmClass);
        }

        request.setAttribute("reportList", reports);
        return mapping.findForward("listReport");
_____________________________________________________________________

AuditAlarmDelegate aad = new AuditAlarmDelegate();

        String strPageNum = request.getParameter("pageNum");
        int pageNum = 0;
        if (strPageNum == null || "".equals(strPageNum)) {
            pageNum = 1;
        }
        else {
            pageNum = Integer.parseInt(strPageNum);
        }

        List list = aad.listAuditAlarm(pageNum);
        Iterator it = list.iterator();
        while (it.hasNext()) {
            AuditAlarmForm alarm = (AuditAlarmForm) it.next();
            log.debug(">>>>the alarm name in listAction is:" +
                     alarm.getAuditAlarmName());
        }
        request.setAttribute("alarmList", list);
        return mapping.findForward("listAlarm");
______________________________________________________________________________
int pageSize = 2;
        Pagination result = new Pagination(pageNum, pageSize);

        List reports = service.SearchReport(form, pageNum, pageSize, result);
        log.debug("========== SearchAlarmReport: SearchReport: " + reports);

        //List result = new ArrayList();
        ParameterDelegate pd = new ParameterDelegate();
        List alarmClassForm = pd.findParameterByName("ALARM_CLASS");
        Hashtable alarmClassTable = new Hashtable();
        Iterator itClass = alarmClassForm.iterator();

        while (itClass.hasNext()) {
            /**
             * 保存参数映射表
             */
            ParameterForm paramForm = (ParameterForm) itClass.next();
            alarmClassTable.put(new Short(paramForm.getParaCode()),
                paramForm.getParaContent());
        }

        // 多表查询,组装显示form
        Iterator it = reports.iterator();

        while (it.hasNext()) {
            AlarmReport report = (AlarmReport) it.next();
            AlarmReportForm reportForm = new AlarmReportForm();
            CommonUtil.copyProperties(reportForm, report);

            String classDescp = (String) alarmClassTable.get(new Short(
                        reportForm.getAlarmClass()));
            reportForm.setAlarmClassDescp(classDescp);
            reportForm.setAlarmName(report.getAuditAlarm().getAuditAlarmName());
            log.debug("============auditAlarmid: " +
                report.getAuditAlarm().getId());
            reportForm.setAuditAlarmId(report.getAuditAlarm().getId());
            result.add(reportForm);
        }

        return result;
_____________________________________________________________________________
else {
                hql = "select report from AlarmReport as report where " + hql;
            }

            log.debug("=========== Query: " + hql);
            Query query = sess.createQuery(hql);
            pagination.setTotalRecord(query.list().size());
            query.setFirstResult( (pageNum - 1) * pageSize);
            query.setMaxResults(pageSize);
            result = query.list();
            log.debug("Search result: " + result);
_________________________________________________________________________________
if(request.getAttribute("jobPhaseCollection") == null){
         List jobPhaseList = new ArrayList();
            List jobPhases = pd.findParameterByName("jobPhase");
            Iterator itJobPhases = jobPhases.iterator();
           
            while(itJobPhases.hasNext()){
             ParameterForm parameterForm = (ParameterForm)itJobPhases.next();
             jobPhaseList.add(new LabelValueBean(parameterForm.getParaContent(),
                        new Integer(parameterForm.
                                getParaCode()).toString()));
            }
            log.info(">>>>the jobPhaseList in list action is:"+ jobPhaseList.size());
            request.setAttribute("jobPhaseCollection",jobPhaseList);
        }
________________________________________________________________________________

select head from Head as head inner join head.user as ur inner join head.detail as detail

where ur.name=? and (head.date between a and b)

heads  Collection

reportForm
new result();

Iterator it = head.iterator();
while(it.hasNext()){
    Head head = it.next();
    Collection details = head.getDetail();
    Iterator it2 = details.iterator();
    while(it2.hasNext())
   {
    new reportForm();
    CopyProperty(form,head);
    copyProperty(from,detail);
    result.add(form)
   
   }

}
return result;
__________________________________________________________________________
 try {
            sess = HibernateHelper.currentSession();

            String hql = "";
            boolean first = true;

            // 根据预警名称查询
            if (null != form.getAlarmName() && !"".equals(form.getAlarmName())) {
                if (!first) {
                    hql += " and ";
                }
                hql += " report.auditAlarm.auditAlarmName like '%" +
                    form.getAlarmName() + "%' ";
                first = false;
            }

            // 根据预警单位查询
            if (null != form.getAlarmCompany() &&
                !"".equals(form.getAlarmCompany())) {
                if (!first) {
                    hql += " and ";
                }
                hql += " report.alarmCompany like '%" + form.getAlarmCompany() +
                    "%' ";
                first = false;
            }

            // 根据预警等级查询
            if (null != form.getAlarmClass() &&
                !"".equals(form.getAlarmClass()) &&
                !"all".equals(form.getAlarmClass())) {
                if (!first) {
                    hql += " and ";
                }
                hql += " report.alarmClass=" + form.getAlarmClass();
                first = false;
            }

            // 根据预警日期查询
            if (null != form.getBeginDate() && !"".equals(form.getBeginDate()) &&
                null != form.getEndDate() && !"".equals(form.getEndDate())) {
                if (!first) {
                    hql += " and ";
                }
                hql += " report.reportDate between '" + form.getBeginDate() +
                    "' and '" + form.getEndDate() + "'";
                first = false;

            }
            else if (null != form.getBeginDate() &&
                     !"".equals(form.getBeginDate())) {
                hql += " report.reportDate >= '" + form.getBeginDate() + "'";
            }
            else if (null != form.getEndDate() && !"".equals(form.getEndDate())) {
                hql += " report.reportDate <= '" + form.getEndDate() + "'";
            }

            if ("".equals(hql)) {
                hql = "from AlarmReport";
            }
            else {
                hql = "select report from AlarmReport as report where " + hql;
            }

            log.debug("=========== Query: " + hql);
            Query query = sess.createQuery(hql);
            pagination.setTotalRecord(query.list().size());
            query.setFirstResult( (pageNum - 1) * pageSize);
            query.setMaxResults(pageSize);
            result = query.list();
            log.debug("Search result: " + result);
     ______________________
_______________________________________________________________________________________
select head from Head as head inner join head.user as ur inner join head.detail as detail
where ur.name=? and (head.date between a and b)

heads  Collection

reportForm
new result();

Iterator it = head.iterator();
while(it.hasNext()){
    Head head = it.next();
    Collection details = head.getDetail();
    Iterator it2 = details.iterator();
    while(it2.hasNext())
   {
    new reportForm();
    CopyProperty(form,head);
    copyProperty(from,detail);
    result.add(form)
   
   }

}
return result;
______________________________________________________________________________________________
//分页需要在delegate里面新建一个,pageNum为当前第几页,pageSize为一页一共显示多少条
Pagination result = new Pagination(pageNum,pageSize);
//得到总数
int totalRecord = service.getCategoriesSize();
//把总数设置到Pagination当中
result.setTotalRecord(totalRecord);
//把Entity转成的Form添加到pagination当中
for(int i=0;i{
  convert();
  result.add(form);
}
在页面添加一个

即可


分页提供的功能,该分页组件能够把request里面的 parameter, attribute里面的数据自动地加到相应的连接当中
目前支持的类型有

所有基本的数据类型,比如 int, float, double,short,char
支持的类型对象有 Integer,Short,Double,Float,String

该组件内置了filter,如果你的参数是以java开发的,将会被过滤掉
__________________________________________________________________________________
wReportForm = this.changeFromEntityToForm(project,wReportForm);

private WeeklyReportForm changeFromEntityToForm(BaseEntity entity,WeeklyReportForm form){
  if("WeeklyReportHead".equals(entity.getClass().getName())){ //应该用com....WeeklyReportHead。用整个包,因为getClass().getName()打印出来的是整个包加类名 ,所以这里应该使用instanceof
   WeeklyReportHead head = (WeeklyReportHead)entity;
   
   form.setPeriod(String.valueOf(head.getPeriod()));
   log.info("++++the period of the head is: "+head.getPeriod());
   form.setSumActualSpendTime(String.valueOf(head.getSumActualSpendTime()));
   form.setSumPlanSpendTime(String.valueOf(head.getSumPlanSpendTime()));
   form.setSummary(head.getSummary());
  }
  if("WeeklyReportDetail".equals(entity.getClass().getName())){
   WeeklyReportDetail detail = (WeeklyReportDetail)entity;
   
   form.setReportNumber(detail.getReportNumber());
   log.info("++++the the reportNumber is:"+detail.getReportNumber());
   form.setJobCategory(detail.getJobCategory());
   form.setJobPhase(detail.getJobPhase());
   form.setJobTask(detail.getJobTask());
   form.setJobContent(detail.getJobContent());
   form.setPlanSpendTime(detail.getPlanSpendTime());
   form.setActualSpendTime(detail.getActualSpendTime());
   form.setOutput(detail.getOutput());
   form.setReportDate(String.valueOf(detail.getReportDate()));
   form.setStartTime(String.valueOf(detail.getStartTime()));
   form.setFinishedTime(String.valueOf(detail.getFinishedTime()));
  }
  if("Project".equals(entity.getClass().getName())){
   Project project = (Project)entity;
   form.setProjectName(String.valueOf(project.getProjectName()));
   form.setProjectId(project.getId());
  }
  if("User".equals(entity.getClass().getName())){
   User user = (User)entity;
   form.setUser_id(user.getId());
   form.setUserName(user.getName());
  }
  return form;
 }
}

________________________________________________
 fwj(方伟坚) 18:57:19
 

______________________________________________________________
String hql = "select distinct head from "+WeeklyReportHead.class.getName() + " as head inner join head.user as ur inner join head.weeklyReportDetails as detail where 1=1 ";
数据库中的查询往往会出现重复查询了多条记录,这时可以用关键字distinct类解决。

____________________________________________________
form里面text框的默认值是空字符 ""
——————————————————————————————————————————————————
javascript中的string比较,直接用 <>就行
var v1 = "1";
 var v2 = "2";
 if(v1 < v2){
  alert("v1 < v2");
 }
 if(v1 > v2){
  alert("v1 > v2");
 }
______________________________________________________________
package com.suntekis.util;

import org.apache.commons.validator.*;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.validator.Resources;
import org.apache.struts.action.ActionErrors;
import javax.servlet.http.HttpServletRequest;

import java.util.StringTokenizer;


public class ValidationUitl {

//  private Logger log = new Logger();

  public ValidationUitl() {
  }

  /**验证以13开头的11位电话号码;例如13XXXXXXXXX,可以输入多个,中间用逗号,分号,空格都可以;
   * 正则表达式为  tel = ^(13)(/d{9})$
   * validator-rules.xml中的配置为:
                          classname="com.suntekis.util.ValidationUitl"
                    method=                        methodParams="java.lang.Object,
                            org.apache.commons.validator.ValidatorAction,
                            org.apache.commons.validator.Field,
                            org.apache.struts.action.ActionErrors,
                            javax.servlet.http.HttpServletRequest"
                           msg="errors.message">
        
 *validator.xml中的配置为:
 *         
                     
                    
                       mask
                       ${tel}
                    

        

 * @param bean Object
 * @param va ValidatorAction
 * @param field Field
 * @param errors ActionErrors
 * @param request HttpServletRequest
 * @return boolean
 */
public static boolean validateMessageList(Object bean,
                                   ValidatorAction va,
                                   Field field,
                                   ActionErrors errors,
                                   HttpServletRequest request) {

    String mask = field.getVarValue("mask");
    String value = ValidatorUtil.getValueAsString(bean, field.getProperty());

    value = value.trim();
    value = value.replaceAll(" ",";");
    value = value.replaceAll(",",";");
    StringTokenizer sTokenizer = new StringTokenizer(value,";");

    boolean maskFlag = true;
    while(sTokenizer.hasMoreTokens()&&maskFlag){
      String str = sTokenizer.nextToken().trim();
      try {
          if (!GenericValidator.isBlankOrNull(str)
              && !GenericValidator.matchRegexp(str, mask)) {

              errors.add(
                  field.getKey(),
                  Resources.getActionError(request, va, field));

              maskFlag = false;
          }
      } catch (Exception e) {
          //log.error(e.getMessage(), e);
      }

    }
    return maskFlag;
}

 

}
________________________________________________________________________
比较两个输入框的值
package com.xanada.helper;

import org.apache.struts.validator.*;
import org.apache.struts.action.*;
import org.apache.commons.validator.*;
import javax.servlet.http.*;
public class VlidationUtil {
  public static boolean validateTwoFields(Object bean, ValidatorAction va,
                                         Field field, ActionErrors errors,
                                         HttpServletRequest request) {
     String value =
         ValidatorUtil.getValueAsString(bean,field.getProperty());//取得配置文件中要被验证属性的值
     String sProperty2 = field.getVarValue("secondProperty");//取得属性里指定变量名的值.这里为secondProperty
     String value2 = ValidatorUtil.getValueAsString(bean, sProperty2);//取得要比较的属性的值
 
     if (!GenericValidator.isBlankOrNull(value)) {
         try {
             if (!value.equals(value2)) {
                 errors.add(field.getKey(),
                            Resources.getActionError(request, va, field));
 
                 return false;
             }
         } catch (Exception e) {
             errors.add(field.getKey(),
                        Resources.getActionError(request, va, field));
 
             return false;
         }
     }
 
     return true;
 }

配置struts-rules.xml
     classname="com.xanada.helper.ValidationUtil" method="validateTwoFields"
    methodParams="java.lang.Object,
                  org.apache.commons.validator.ValidatorAction,
                  org.apache.commons.validator.Field,
                  org.apache.struts.action.ActionErrors,
                  javax.servlet.http.HttpServletRequest"
   depends="required" msg="errors.twofields">
            function validateTwoFields(form) {
            var bValid = true;
            var focusField = null;
            var i = 0;
            var fields = new Array();
            oTwoFields = new twofields();
            for (x in oTwoFields) {
                var field = form[oTwoFields[x][0]];
                var secondField = form[oTwoFields[x][2]("secondProperty")];
           
                if (field.type == 'text' ||
                    field.type == 'textarea' ||
                    field.type == 'select-one' ||
                    field.type == 'radio' ||
                    field.type == 'password') {
           
                    var value;
                    var secondValue;
                    // get field's value
                    if (field.type == "select-one") {
                        var si = field.selectedIndex;
                        value = field.options[si].value;
                        secondValue = secondField.options[si].value;
                    } else {
                        value = field.value;
                        secondValue = secondField.value;
                    }
               
                    if (value != secondValue) {
                   
                        if (i == 0) {
                            focusField = field;
                        }
                        fields[i++] = oTwoFields[x][1];
                        bValid = false;
                    }
                }
            }
           
            if (fields.length > 0) {
                focusField.focus();
                alert(fields.join('/n'));
            }
           
            return bValid;
        }]]>


配置validate.xml文件


              depends="required,twofields">
         name="required"
      key="errors.required"/>
         name="twofields"
      key="errors.twofields"/>

       
         key="userForm.confirmPassword" />
      
          secondProperty
     password2
     

 
     
配置资源文件:
errors.required = must enter
errors.twofields = {0} is not equal {1}
userForm.password = password1
userForm.confirmPassword = password2
______________________________________________________
form[i].element取得所有form下面的对象。
————————————————————————————————————————————————
document.domain可以取得窗口的url中的域名
document.URL可以取得窗口的url
所以document.URL.subString("http://".length + document.domain.length)
document.location 跟document.URL一样的?
——————————————————————————————————————————————————————
当前Calendar
java.util.GregorianCalendar[time=1094712690908,areFieldsSet=true,areAllFieldsSet
=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=288
00000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWee
k=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2004,MONTH=8,WEEK_OF_YEAR=37,WEEK_OF_MON
TH=2,DAY_OF_MONTH=9,DAY_OF_YEAR=253,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1
,HOUR=2,HOUR_OF_DAY=14,MINUTE=51,SECOND=30,MILLISECOND=908,ZONE_OFFSET=28800000,
DST_OFFSET=0]
__________________________________________________________________________________
对form用get方法会容易导致中文乱蚂。
___________________________________________________________________________
记录编辑时间 和 创建时间应该在编程自己插到表里。
_____________________________________________________________________________________
设计原则:
增加新功能时,怎样设计改动最少就这怎么样做。
______________________________________________________________________________
出现没有进入action的程序,往往是因为validate出错。这些要调试其他程序时应该将struts-config.xml的validate=true改为false
_____________________________________________________
在不同的action里使用同一个actionForm的值,注意将配置文件里scope改为request,否则这个actionForm在一个action里的状态将会作为下一个form的初始值
____________________________________________________________________________
数据库的日期比较应该用yyyy-MM-dd
_________________________________________
如果在初始化hibernate的配置文件时提示找不到相应的类可能有如下原因:
1.类的名字没写对
2.要应用的那个类没配置文件没配好(在一个类的配置文件下引用另一个类)
3。包的路径没写

0 0

相关博文

我的热门文章

img
取 消
img