You need to use melee troops to fight melee troops when defending. Make sure you change the percentages so that you have the right type and quantity of soldier facing a certain type and quantity of enemy.
For example if you have 20 melee coming at your front and 12 bowman and 8 melee coming at your right flank you should set your defences as follows:
*50% right flank, 50 front gate and 0% left flank (because there are 40 in total with 20 as a subtotal of the two flanks being attacked)
*100% melee soldiers on the front gate (melee against melee when DEFENDING, opposite when attacking) and 60% bowman and 40% melee on the right flank
*on both flanks you want general defensive tools such as moat, wall and gate tools. But on the front gate you want no tools boosting the effect of bowman and you instead want these tools on the right flank(as you have no bowman on the front gate and this would be a waste). Obviously ruby tools, preferably from the armourer, are better than ones you use resources to make.
JUST TO CLARIFY. When attacking use bowman against melee and melee against bowman but, if this is the best way to attack, then obviously the best way to defend an attack would be the opposite and so when DEFENDING: Use MELEE AGAINST MELEE and BOWMAN GAINST BOWMAN.
PLEASE NOTE that the above advice is for 'green defenders' such as spearmen, halberdiers, longbowman and bowman. When defending with macemen and crossbowmen (not recommended as their defence stats are awful) the best defence you can get from these two unit types is REVERSED. If you have archers and swordsman then it doesn't matter whether you use these against melee or ranged attackers although archers are stronger in defence. Once you become level 20, or 25 upgrade your barracks as a priority to get longbowmen and halberdiers. When you become level 39 get a research tower do the necessary research and get veteran spearman and bowman!