Thong Ke Cac Loi Dev Thuong Gap

download Thong Ke Cac Loi Dev Thuong Gap

of 14

Transcript of Thong Ke Cac Loi Dev Thuong Gap

  • ST

    TLoi li M t li Cch x l Code v d x l Priority

    1

    Li

    common

    Khng focus vo trng li onFocus = function(componentId){

    dojo.byId(componentId).focus();

    }

    high

    2

    Li

    common

    Khng validate maxlength cc control input Thm thuc tnh

    maxlength ti tng

    control hoc vit hm

    javascript validate

    ti client.

    Validate thm

    maxlength ti server.

    client :

    Thm maxlength='10' :

    TextArea trong framework 1 : Thm vo hm validate

    var abc = document.getElementById("abc");

    if (abc != undefined && abc!= null){

    if (abc.length >10){

    alert("Trng abc khng c vt qu 10 k t")

    abc.focus();

    }

    }

    server :

    +Nu truyn theo form :

    String abc = frm.getAbc();

    if (abc != null && !abc.trim().isEmpty() &&

    abc.trim().length()>10){

    request.setAttribute("errorCode","abcxyz");

    return "errorPage"

    }

    high

    3

    Li

    common

    Khng validate cc trng bt buc nhp (required) Vit hm javascript

    validate nhng

    trng no bt buc

    nhp m khng nhp

    th thng bo cho

    ngi dng bit v

    setFocus vo trng

    var target=dojo.byId("badKpiCfgFormOnDialog.target").value;

    if(target.toString().trim()==""){

    msg.error('notFill

    key.target',onFocus("badKpiCfgForm

    OnDialog.target"));

    return false;

    }

    high

  • 4Li

    common

    Khng ct (trim) khong trng trong d liu nhp vo - client: Thm thuc

    tnh trim="true" cho

    cc control.

    - server: Trim d liu

    trc khi thao tc

    Ex: Trng name kiu String cn trim d liu

    - Client :

    Jsp thm :

    Hoc s dng hm trimFormById(Id) trim ton b form theo

    Id:

    function trimFormById(formId){

    var formObject = document.getElementById(formId);

    var formElements = formObject.elements;

    for (var i = 0; i < formElements.length; i++) {

    var e = formElements[i];

    if (e.type != undefined) {

    var fieldType = e.type.toLowerCase();

    switch (fieldType) {

    case "text":

    case "textarea":

    e.value = e.value.trim();

    break;

    default:

    break;

    }

    }

    }

    }

    - Server :

    String name= ;

    If(form.getName() != null){

    name = form.getName().trim();

    }

    high

    5

    Li

    common

    Khng validate d liu nhp vo kiu number Thm validate kiu

    number ti client v

    server

    Client :

    Framework 3: thm mask="digit"(mask="0-9" ..)

    ex :

    Server :

    S dng hm :

    public static boolean isNumber(String s) {

    return s == null ? true: s.matches("\\d*");

    }

    high

  • 6Li

    common

    - Li v b cc, font ch, chnh t, mu ch

    - Li v trng bt buc phi c du * hoc tam gic

    mu

    Fix trang code hin

    th giao din:

    1. Cc label, textbox,

    combo c di,

    rng v khong cch

    bng nhau, khng x

    lch

    2. Cc label s dng

    cng 1 loi font, c

    ch, cn l

    3. Cc trng hp

    bt buc nhp phi

    c du * hoc tam

    gic : t thuc

    tnh required="true"

    high

    7

    Li

    common

    Hin th sai nh dng thi gian control DatePicker t li format cho

    control theo nh

    dng mong mun:

    dd/MM/yyyy hoc

    dd/MM/yyyy

    hh:mm:ss

    high

    8

    Li

    common

    Code khng h tr multi language Phi khai bo key

    trong file Language

    Trong jsp : dng th

    key

    Trong java : dng

    hm

    LanguageBundleUtils.

    getString(key) hoc

    vit hm tng t ...

    high

  • 9Li

    common

    Khng tm kim c vi cc k t c bit nh %,

    _ , !

    Ex:

    String name = formSearch.getName();

    String sql = "select price from abc where 1=1 ";

    SQLQuery q = getSession().createSQLQuery(sql);

    if (name != null && !name.trim().isEmpty()){

    q.app("and lower(name) like :name");

    q.setParameter("name", "%"+name+"%");

    }

    q.addScalar("name",Hibernate.STRING);

    q.setResultTransformer(Transformer.aliasToBean(A

    bcBO.class));

    List resultList = (List)query.list();

    => Khng search c khi truyn % , _ ....

    S dng t kha

    Escape trong SQL String name = formSearch.getName();

    String sql = "select price from abc where 1=1 ";

    SQLQuery q = getSession().createSQLQuery(sql);

    if (name != null && !name.trim().isEmpty()){

    q.app("and lower(name) like :name escape '\\'");

    q.setParameter("name", "%" +

    name.trim().toLowerCase().replace("\\", "\\\\").replaceAll("%",

    "\\\\%").replaceAll("_", "\\\\_").replaceAll("!", "\\\\!") + "%");

    }

    q.addScalar("name",Hibernate.STRING);

    q.setResultTransformer(Transformer.aliasToBean(AbcBO.class));

    List resultList = (List)query.list();

    high

    10

    Li

    common

    Qun khng break sau lnh switch-case

    switch (temp){

    case 1 :

    System.out.print("1");

    case 2 :

    System.out.print("2");

    switch (temp){

    case 1 :

    System.out.print("1");

    break;

    case 2 :

    System.out.print("2");

    break;

    Medium

    11

    Li

    common

    Code tm kim ngay sau code insert -> khng th

    select bn ghi va save do cha commit

    EX:

    code java :

    // Dung hibernate

    save(abcBO);

    //Dung sql thuan

    SQLQuery query =

    getSession().createSQLQuery("select * from abc");

    List temp = query.list();

    -> khng ly c kt qu va thay i

    Thm on code cp

    nht gi tr va thay

    i t Hibernate

    xung DB:

    session.flush()

    Gii php :

    code java :

    // Dung hibernate

    save(abcBO);

    sess.flush();

    //Dung sql thuan

    SQLQuery query = getSession().createSQLQuery("select * from

    abc");

    List temp = query.list();

    Medium

  • 12

    Li

    common

    Hin th sai nh dng thi gian datagrid Vit thm hm

    formatter cho column

    page.getTimeBegin = function(inRow) {

    try{

    var row = dijit.byId("gridId").getItem(inRow-1);

    var timeBegin = row.timeBegin + "";

    var split1 = timeBegin.split("-");

    var split2 = split1[2].split("T",2);

    return split2[0] + "/" + split1[1] + "/" + split1[0] + " " +

    split2[1];

    } catch(err){

    return "";

    };

    }

    Medium

    13

    Li

    common

    Trong DB2 khi to view bo li: The specification

    ORDER BY or FETCH FIRST n ROWS ONLY is

    invalid. SQLCODE=-20211, SQLSTATE=428FJ

    DB2 khng chp

    nhn lnh ORDER

    BY trong view --> B

    lnh order by trong

    view i v s dng

    order by trong cu

    lnh select t view

    Medium

    14

    Li

    common

    Cc form giao din b v mc d cn chnh trong

    cc th div hoc table

    Thm thuc tnh

    theme="simple" vo

    th s:form bao trn

    vng giao din

    Medium

    15

    Li

    common

    Khng post c gi tr trn cc control b set thuc

    tnh disable=true, v d:

    --> Khi submit form gi tr stockModelForm.code

    post gi tr = null ln server.

    Thm th hidden

    lu thng tin b

    disable

    Medium

  • 16

    Li

    common

    Li map sai kiu d liu Sa li kiu d liu

    cho ph hp

    1. Trn Form l Text :

    Nhng trong form java :

    class FormSearch{

    Long abc;

    ........

    }

    2. Hoc khi get list trng abc kiu String -> add scalar kiu Date

    addScalar("abc", Hibernate.DATE);

    3. Hoc statement gi hm

    CallableStatement cs = conn.prepareCall("{ call proc_test(?) }");

    String abc = "ss";

    cs.setString(1, abc);

    cs.execute();

    Trong khi trong proc_test : bin cn truyn l Long -> Li

    Medium

  • 17

    Li

    common

    Khng Validate trng d liu trong file excel V d bn cnh l 1

    phng php gii

    quyt :

    1. a tt c cc

    cell u tin khng b

    trng lp vo

    HashMap + Km

    thng tin cell nh

    row, column

    2. Duyt li d liu

    ct pht hin cc

    bn ghi tn ti

    trong HashMap

    Ex: Validate trng ct ISDN trong file Excel ---- ng vi trng

    vipId trong bng Vip

    public List validateDuplicateVIPInExcel(List

    exportError, List isdnList) {

    HashMap base = new HashMap();

    VipBO temp;

    int isdnListSize = isdnList == null ? 0 : isdnList.size();

    for (int i = isdnListSize - 1; i > -1; i--) {

    temp = isdnList.get(i);

    base.put(temp.getVipId(), temp.getRowIndex());

    }

    List result = new ArrayList();

    ErrorImport errImport = null;

    Long index = null;

    int row = 0;

    for (VipBO isdn : isdnList) {

    row = isdn.getRowIndex().intValue();

    index = base.get(isdn.getVipId());

    if (index != null && index != row) {

    errImport = new ErrorImport(isdn.getVipId(),

    Constants.IMPORT.DUPLICATE_ISDN + (index.intValue() + 1),

    row, isdn.getColumnIndex().intValue());

    exportError.add(errImport);

    } else {

    result.add(isdn);

    }

    }

    return result;

    }

    Medium

    18Li

    common

    i vi cc hm b ng, trong khi lnh catch

    khng thc hin throw exception ln

    Thm throw

    exception vo trong

    cc hm b ng hoc

    khai bo hm b ng

    lun throws Exception

    Code chun :

    try{

    // Do something here

    }catch(Exception ex){

    throw ex;

    }

    Medium

    19Li

    common

    Khng th dng gotoaction trn popup submit

    trn FW2

    Dng tag submit hoc

    dng

    setaction("formID",

    "contextpath + url

    submit");

    Low

  • 20Li

    common

    Khi s dng hibernate save object mc d trn

    java set gi tr ID cho object l A nhng gi tr ID lu

    vo trong DB li khng phi l A

    V d:

    StockTransSerial stock = new

    StockStockTransSerial();

    stock.setID(100L);

    stock.setName("abc");

    stock.save();

    --> Kim tra Database gi tr stock_id khng phi l

    100.

    Kim tra file mapping

    hibernate (xml) trong

    th c on set

    sequence th b on

    set sequence i

    STOCK_TRANS_SERIAL_SEQ

    --> X l bng cch b on generator (bi ) i

    Low

    21

    Li khng

    xc thc

    i

    tng/

    d liu

    trc khi

    s dng

    Khng check null i tng trc khi gi method

    hoc truy cp thuc tnh ca i tng.VD:

    public void setVariable(String name, Object value) {

    ...

    logger.debug("add variable (" + name + "="

    + value.toString() + ")");

    ...

    }

    Phi check null trc

    khi gi method hoc

    truy cp vo thuc

    tnh ca i tng

    public void setVariable(String name, Object value) {

    if(value != null)

    logger.debug("add variable (" + name + "=" + value.toString()

    + ")");

    ...

    }

    high

    22

    Li khng

    xc thc

    i

    tng/

    d liu

    trc khi

    s dng

    Li khng kim tra kch thc ca Danh sch hoc

    Mng. VD:

    deptToken = vsaUserToken.getDeptTokens().get(0);

    Trc khi truy cp

    n phn t ca

    Mng hoc Danh

    sch, cn check kch

    thc trc

    if (vsaUserToken.getDeptTokens().isEmpty()) {

    return null;

    } else {

    deptToken = vsaUserToken.getDeptTokens().get(0);

    }

    high

    23

    Li khng

    xc thc

    i

    tng/

    d liu

    trc khi

    s dng

    Khng kim tra mu s (khc 0) khi thc hin php

    chia V d

    public int A (int x, int y) {

    int z = x/y;

    ...

    }

    on code ny b li runtime nu y =0

    Kim tra mu s

    trc khi thc hin

    php chia

    public int A (int x, int y) {

    int z =0;

    if (y ==0 ){

    // Thng bo li

    } else {

    z = x/y;

    }

    ...

    }

    Medium

  • 24

    Li qun

    l kt ni

    M nhng khng ng kt ni trong trng hp

    exception. VD:

    try {

    logout();

    disconnect();

    } catch (IOException ex) {

    logger.error(hlr + " close transport error: " + ex);

    } finally {

    logged = false;

    connected = false;

    }

    - logout fail s vng exception v nhy qua

    disconnect

    Kim tra y cc

    trng hp sao cho

    vi bt k iu kin

    no on code ng

    kt ni lun lun

    c thc hin, nh

    VD y l t trong

    khi finally.

    try {

    logout();

    } catch (IOException ex) {

    logger.error(hlr + " close transport error: " + ex);

    }

    //dong socket

    try {

    disconnect();

    } catch (IOException ex) {

    logger.error(hlr + " close transport error: " + ex);

    }

    //set cac bien trang thai

    logged = false;

    connected = false;

    high

    25

    Li qun

    l ti

    nguyn

    S dng Statement, PrepareStatement, resultset

    nhng khng ng. VD:

    try {

    String strSQL = "Update ......";

    stmt = conn.prepareStatement(strSQL);

    //execute query

    stmt.executeUpdate();

    } catch (Exception e) {

    logger.error(e, e);

    }

    Tin hnh ng ti

    khi lnh finally

    try {

    String strSQL = "Update ......";

    stmt = conn.prepareStatement(strSQL);

    //execute query

    stmt.executeUpdate();

    } catch (Exception e) {

    logger.error(e, e);

    } finally {

    if(stmt != null && !stmt.isClosed()){

    this.closeResource(stmt);

    }

    }

    high

    26

    Li qun

    l ti

    nguyn

    Giao tip gia cc h thng qua webservices, lib

    khng set thi gian timeout. VD:

    String serverIp = resource.getString("ip");

    int serverPort =

    Integer.parseInt(resource.getString("port"));

    String userName = resource.getString("username");

    String password = resource.getString("password");

    Client client = new ObjectClientChannel(serverIp,

    serverPort, userName, password, true);

    client.connect();

    ViettelMsg response = client.send(request);

    on code ny c th chim ti nguyn gy treo ng

    dng nu pha server khng phn hi response

    Set timeout khi h

    thng thc hin giao

    tip vi cc h thng

    bn ngoi.

    String serverIp = resource.getString("ip");

    int serverPort = Integer.parseInt(resource.getString("port"));

    String userName = resource.getString("username");

    String password = resource.getString("password");

    Client client = new ObjectClientChannel(serverIp, serverPort,

    userName, password, true);

    client.setReceiverTimeout(ReportConstant.REPORT_MESSAGE_

    TIME_OUT);

    client.connect();

    ViettelMsg response = client.send(request);

    high

  • 27

    Li qun

    l ti

    nguyn

    Li khng ng li file khi dng ng file sau khi thao

    tc ti khi lnh

    Finally

    V d: try {

    byte[] bFile = new byte[(int) fileUpload.length()];

    fileInputStream = new FileInputStream(fileUpload);

    fileInputStream.read(bFile);

    String fileOutput =

    getRequest().getRealPath(Constant.EXPORT.TEMPLATE_SOUR

    CE_LOCATION + "/checklistNSS/") + File.separator +

    fileUploadName;

    fos = new FileOutputStream(fileOutput);

    fos.write(bFile);

    fos.flush();

    getRequest().setAttribute("message", "Upload file

    success");

    getRequest().setAttribute("reload", "true");

    } catch (Exception ex) {

    ex.printStackTrace();

    getRequest().setAttribute("message", "Upload file fail");

    } finally {

    if (fileInputStream != null) {

    fileInputStream.close();

    }

    if (fos != null) {

    fos.close();

    }

    }

    high

  • 28

    Li qun

    l ti

    nguyn

    Khng ng cursor khi gp li exception

    VD: on PLSQL

    declare

    cursor c_data

    is

    select * from table_a;

    v_data c_data%rowtype;

    begin

    open c_data;

    fetch c_data into v_task;

    if c_data%NOTFOUND then

    insert into table_a values (1);

    end if;

    close c_data;

    commit;

    exception when others

    then

    rollback;

    end;

    - on code ny khi cu lnh insert chy ok th s

    ng cursor c_data, tuy nhin nu cu lnh insert b

    li exception, cursor s ko c ng.

    - B sung thm code

    ng cursor trong

    on exception:

    exception when others

    then

    rollback;

    if c_data%ISOPEN then

    close c_data;

    end if;

    end;

    high

    29

    Li qun

    l ti

    nguyn

    NioSocketConnector ch cn to mt ln lc u,

    nu to lin tc s tht thot ti nguyn --> sau mt

    thi gian chy gy li.

    public void connect() throws IOException {

    ...

    connector = new NioSocketConnector();

    ...

    }

    Ch to 1 ln, check

    truc khi s dng

    to cha - nu cha

    th to mi nu ri th

    ly i tng to

    ra s dng

    public void connect() throws IOException {

    //neu chua tao connector thi tao lai

    if (connector == null) {

    connector = new NioSocketConnector();

    }

    }

    Low

    30

    Li cu

    hnh

    Li xy ra khi cha add action Authentication.do v

    error.do vo allowurl dn n b redirect lin tc

    (Viettel Web Framework + Viettel Passport)

    Cu hinh gi tr

    allowURL trong file

    cu hnh

    cas.properties

    AllowUrl=${contextPath}/Authentication.do,${contextPath}/error.do

    .

    Medium

    31

    Li cu

    hnh

    Khi cu hnh wrapper phn cu hnh load th vin

    wrapper.java.classpath.1 thng l *.jar. Khi

    upcode mi backup th vin c li ch i tn file c

    thnh file bk (v d abc_bk.jar) --> li vn dng th

    vin c khi trin khai

    C 2 hng khc

    phc:

    1/ Khi cu hnh

    classpath th ch

    tng minh tng th

    vin s dng

    2/ Khi upcode mi th

    xa hn th vin c

    i hoc i ui file

    c (v d abc.jar_bk)

    Medium

  • 32

    Li trin

    khai

    ng dng b trn b nh, xy ra li

    java.lang.OutOfMemoryError: heap space

    Ch yu xut pht t

    2 nguyn nhn:

    - Cu hnh b nh

    JVM khng cho

    nhu cu ca ng

    dng. Thng

    thng khi khng cu

    hnh th b nh JVM

    ly mc nh

    thp(64m)

    - Qun l b nh

    khng tt , xy ra

    memory leak, gc

    khng gii phng

    c b nh. Cn

    qun l tt nhng

    bin static hay shared

    c s dng vi

    mc ch lu tr d

    liu cho nhiu thread

    -Cu hnh li file catalina.sh trong tomcat:

    JAVA_OPTS="-Xmx1024m"

    - Cu hnh li file wrapper.sh trong tin trnh(JSW):

    wrapper.java.maxmemory=3000

    high

    33

    Li trin

    khai

    ng dng tomcat xy ra li

    java.lang.OutOfMemoryError: PermGen space

    B nh PermGen

    mc nh(64m) ca

    JVM thp hn so vi

    nhu cu ca ng

    dng.Tng b nh

    permGen bng cch

    cu hnh tng b nh

    PermGen cho JVM.

    -

    XX:MaxPermSize=12

    8m

    -Cu hnh li file catalina.sh trong tomcat:

    JAVA_OPTS="-XX:MaxPermSize=128m"

    - Cu hnh li file wrapper.sh trong tin trnh(JSW):

    wrapper.java.command=java --XX:MaxPermSize=128m

    high

  • 34

    Li trin

    khai

    - Khi trin khai 1 yu cu mi cho h thng c, i

    vi cc h thng ln a s dng cch up class. Vic

    ny thng gy li do khi up class, nhiu class dev

    ngh l ko thay i nn ko up nhng thc cht li gy

    li cho chng trnh:

    V d 1:

    '- Trong class Constant.java khai bo 1 bin:

    public static Integer TEST_1 = 1;

    - Trong class ABC.java s dng bin TEST_1 ny:

    int TEST = Constant.TEST_1;

    - Khi trin khai mi 1 yu cu cn sa gi tr

    TEST_1 = 2, dev build li project v ch up li file

    Constant.java ln server

    - Kt qu: bin TEST trong file ABC.java vn c gi

    tr = 1.

    V d 2:

    - C class A1 extends class A

    - Class B.java c method:

    public static int TEST(A1 a1)

    - Class C.java c on code gi hm TEST:

    int C1 = B.TEST(a1);

    - Khi trin khai mi 1 yu cu cn sa method

    TEST, sa thnh:

    public static int TEST(A a);

    - Build project success.

    - Dev upcode ch up li file B.java ln server

    - Kt qu: khi gi n hm TEST, h thng tr v li

    NoSuchMethodError

    Khi trin khai cn up

    li tt c cc class c

    gi n hm b thay

    i, c th s dng

    tool find usage ca

    netbean tm kim.

    VD1: Do java bin

    dch on int TEST =

    Constant.TEST_1

    thnh int TEST = 1.

    V vy khi thay i gi

    tr file Constant cn

    up li cc class s

    dng gi tr b thay i

    high

    35

    Li trin

    khai

    y file code ln server test nhng b file b cache ->

    khng apply c thay i

    Dng SSH kt ni

    n server cn

    deploy -> browse n

    th mc ci tomcat ->

    work -> catalina ->

    localhost -> tn ng

    dng y ln ->

    browse n th mc

    tng ng vi file

    y ln -> xa ht

    cc file c ui

    _jsp.class , _jsp.java

    ng vi file y ln

    high

  • 36Li trin

    khai

    - Khi trin khai 1 yu cu mi cho h thng c, i

    vi cc h thng ln a s dng cch up class. Vic

    ny thng gy li do khi up class, nhiu class dev

    ngh l ko thay i nn ko up nhng thc cht li gy

    li cho chng trnh:

    V d 1:

    '- Trong class Constant.java khai bo 1 bin:

    public static Integer TEST_1 = 1;

    - Trong class ABC.java s dng bin TEST_1 ny:

    int TEST = Constant.TEST_1;

    - Khi trin khai mi 1 yu cu cn sa gi tr

    TEST_1 = 2, dev build li project v ch up li file

    Constant.java ln server

    - Kt qu: bin TEST trong file ABC.java vn c gi

    tr = 1.

    V d 2:

    - C class A1 extends class A

    - Class B.java c method:

    public static int TEST(A1 a1)

    - Class C.java c on code gi hm TEST:

    int C1 = B.TEST(a1);

    - Khi trin khai mi 1 yu cu cn sa method

    TEST, sa thnh:

    public static int TEST(A a);

    - Build project success.

    - Dev upcode ch up li file B.java ln server

    - Kt qu: khi gi n hm TEST, h thng tr v li

    NoSuchMethodError

    Khi trin khai cn up

    li tt c cc class c

    gi n hm b thay

    i, c th s dng

    tool find usage ca

    netbean tm kim.

    VD1: Do java bin

    dch on int TEST =

    Constant.TEST_1

    thnh int TEST = 1.

    V vy khi thay i gi

    tr file Constant cn

    up li cc class s

    dng gi tr b thay i

    Medium