现在的位置: 首页 > 综合 > 正文

JSP应用总结

2014年01月22日 ⁄ 综合 ⁄ 共 7052字 ⁄ 字号 评论关闭

1:查找页面的代码错误犹如医生给病人看病,不能头痛医头,脚痛医脚,就是说一个地方的“错误”往往是由别的地方有问题而引发的。

2:如果数据放在request中(可能包括url参数),那么要在后续的页面(或是刷新后)中看到以前的数据可以使用${param.yourdate},不过放在ActionForm(Struts1)中可能更好一些。

3:在JSP页面中使用日期Bean,可以使用以下标签格式化日期数据(数字,日期格式化)
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:formatNumber value="${now.rates}" pattern="#,##0.00#" />//数字格式化
<jsp:useBean id="now" class="java.util.Date" />
起始时间
<input type="text" name="startTime" value="<fmt:formatDate value="${now }" pattern="yyyy-MM"/>-01" //日期格式化
onFocus="calendar()" />
结束时间
<input type="text" name="endTime" value="<fmt:formatDate value="${now }" pattern="yyyy-MM-dd"/>"

readonly onFocus="calendar()" />

4:DAO中的方法写法:方法应继承extends JdbcDaoSupport(需要:import org.springframework.jdbc.core.support.JdbcDaoSupport 该类中封装了

很多有用的方法,
执行sql语句是使用:this.getJdbcTemplate() 在调用相关的方法)
public Map findByProperty(String id, String startTime, String endTime) {
//logger.debug("finding WRONG_SMS_INFO instance with property: " + id);

String noUseSql = " select count(*) "
+ " from WRONG_SMS_INFO a,customer_info_getcnt b"
+ " where a.WORKER_ID=b.WORKER_ID"
+ " and a.receive_time>=to_date(?,'yyyy-MM-dd') and a.receive_time<to_date(?,'yyyy-MM-dd')+1"
+ " and b.DEPARTMENT_TREE like ? and a.OPERATION_CODE='05'";
Object[] totalParams = { startTime, endTime, depart };

Map map = null;
int total = 0;
try {
int noUse = this.getJdbcTemplate().queryForInt(noUseSql,
totalParams);
total = total + noUse + quitc + fail + succ;
map.put("noUse", noUse);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}

5:JSP页面中的默认值设置时一般要求当用户更改后系统应记住用户的数据,而不应刷新后变成默认值
实现方法:让系统进入JSP之前先执行Action设置好默认值后再转向JSP
6:在页面中实现鼠标掠过提示文本内容:在<div src="全部/提示内容">部分内容</div>
7:动态更新下拉框:实现把数据放在list中存入request中,(requestScope.gift_type是用户上一次选择的项)
礼品类别
<c:if test="${requestScope.gift_type!=null}">
<select name="gift_type">
<option value="-1"></option>
<c:forEach var="gift" items="${Typelist}">
<option value="${gift.type_code}"
${gift.type_code==requestScope.gift_type?"selected":""}>
${gift.type_name}
</option>
</c:forEach>
</select>
</c:if>

<c:if test="${requestScope.gift_type==null}">
<select name="gift_type">
<option value="-1"></option>
<c:forEach var="gift" items="${Typelist}">

<option value="${gift.type_code}" >
${gift.type_name}
</option>
</c:forEach>
</select>
</c:if>
8:JS中文验证函数

父窗口中:
<script language=javascript>
var i=0;
function winFlesh()
{//提交表单
document.topForm.submit();
}
</script>

子窗口中:
function checkChn()
{
var str=document.form1.gift_name.value;
if(isChn(str)){
var parentwin = dialogArguments;
parentwin.i=1;
document.form1.submit();
}else{
alert('名称只能是中文');
return false;
}
}

function isChn(str)
{
var reg=/^[\u0391-\uFFE5]+$/;
if(!reg.test(str)){
return false;
}
return true;
}
function doflesh()
{//调用父窗口中的刷新方法
var parentwin = dialogArguments;
if(parentwin.i==1){
parentwin.winFlesh();
window.close();
} else{
window.close();
}
}

9:jsp中的列表序号标示方法:${(requestScope.pageNo-1)*10+(status.index+1)}
页面中尽量使用完整的JS函数调用方法,如:onclick="javaSript:isChn();" 简写方式可能出错
10:返回同一个JSP页面时防止新建页面,而是返回原来的:
<head>
<base target="_self">
</head>
11:在Action中获取jsp页面中的同名参数(可能只有一个,也可能是一个数组)
String[] gcodes = request.getParameterValues("gift_codes");
if (gcodes == null) {
gcodes = new String[] { request.getParameter("gift_codes") };
} else {
gcodes = request.getParameterValues("gift_codes");

}

12:一种变相给操作加锁的方法(并没有真正对资源加锁,而是变通实现):
private static final Object lockedObj = new Object();//必须是静态,最终的
synchronized (lockedObj) {
需要加锁的操作,
}

注释:synchronized可以修饰方法、代码段。

13:一种有点怪的Sql:
insert into gift_out_info(out_vouch_no,gift_code,group_id,vouch_no,dept_code_old,dept_code_new,out_num,"
+ "stock_num,out_time,workno) select ?,?,?,NVL2(max(vouch_no),max(vouch_no)+1,1),?,?,?,?,?,? from gift_out_info "

+" where group_id=? and dept_code_new=? ";

14:在jsp页面中设置变量,临时存储数据的jstl实现方法:
<c:set var="sendInfoPK"
value="${map.gcode}^${map.groupId}^${map.out_vouch_no}^${map.send_vouch_no}">
</c:set>
<input type="text" size="10" name="giftBackNum"
value="${sessionScope.gift_back[sendInfoPK]}">//在c:set中间可以引用

<c:remove var="sendInfoPK" />

15:sql注入攻击的写法:(本来要传入 4532,但传入的字符串是:"4532';select * from dual;--")(select * from dual;可以是其他任何危险操作)
select * from gift_in_info t
where t.group_id='4532';

select * from dual;-- ' and t.dept_code='1000'

16:当数据为0时不提供链接功能:
方法一:
<td align="center">
<c:if test="${map.back_num!=0}">
<a style="cursor: hand"
onclick="selectdetails('listOpenSucc')"> <font
color="blue">
</c:if>
${map.back_num}
<c:if test="${map.back_num!=0}">
</font>
</a>
</c:if>
</td>

17: BigDecimal 到 String 的转换异常处理办法:

int stock = ((java.math.BigDecimal) map.get("stock")).intValue();

18:LazyValidatorForm的使用(html:multibox 多项选择复选框的状态保存)(完全使用Struts来保持状态更简单)
(1)JSP中的代码
费用项目:
<c:forEach var="list" items="${requestScope.itemList}"
varStatus="status">
<html:multibox property="itemsArray" value="${list.code}" />
${list.content}
</c:forEach>
(2)Struts Form的定义
<form-bean name="FinanceQueryForm"
type="org.apache.struts.validator.LazyValidatorForm" >
<form-property name="itemsArray" type="java.lang.String[]" /> //对某一个特殊的使用,可以加上特殊的声明
</form-bean>
(3)在Action中使用
LazyValidatorForm lazyForm = (LazyValidatorForm) form;
String[] item=(String [])lazyForm.get("itemsArray");
for(int i=0;i<item.length;i++)
{
logger.debug("项目是:"+item[i]+" ");
}
List itemList = financeManageDAO.getItems();
if (itemList != null) {
List<String> cbxValue = new ArrayList<String>();
for (Object obj : itemList)
{//设置默认值,让每一个复选框都打上勾
Map map = (Map) obj;
cbxValue.add("" + map.get("code"));
}

dynaForm.set("itemsArray", cbxValue.toArray(new String[] {}));

19:为了使程序在Linux上能运行,尽量不使用那些与本地环境相关的方法(localTime),如日期的初始化可以这样:
方法一:在 Action中添加如下代码:
Calendar cal =Calendar.getInstance();// 方法 getInstance,获得此类型的一个通用的对象(与语言环境无关)
String startDate=new SimpleDateFormat("yyyy-MM").format(cal.getTime())+"-01";//当月的第一天
String endDate=new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());//当天
request.setAttribute("startDate", startDate);
request.setAttribute("endDate", endDate);
方法二:(直接进入JSP时设置默认值)

20:另一种for循环的写法(foreach语句):
try {
List itemList = financeManageDAO.getItems();
if (itemList != null) {
List<String> cbxValue = new ArrayList<String>();
for (Object obj : itemList) {//类似于JS中的写法
Map map = (Map) obj;
cbxValue.add("" + map.get("code"));
}
dynaForm.set("itemsArray", cbxValue.toArray(new String[] {}));//注意List到数组的转换方法
request.setAttribute("itemList", itemList);
} else {
logger.debug("itemList是空的");
}
} catch (Exception e) {
logger.error("错误:查询下来框出错:" + e.getMessage() + "]");

}

21:页面列表的条文显示:
<script language=javascript>
function overbgcolor(n)
{
m=n*2;
table1.rows(m).className="listrowover";
}
function outbgcolor(n)
{
m=n*2
table1.rows(m).className="";
}
<tr onMouseOver="overbgcolor(${status.count});"
onmouseout="outbgcolor(${status.count});">
<td align="center">
${(requestScope.pageNo-1)*10+(status.index)}
</td>
<td align="center">
${map.gift_code}
</td>
</tr>

</script>

22:鼠标经过提示完整内容
<td align="center" >
<div title='<%=map.get("SMS_CONTENT")%>'>
<font color='red'><%=(String) map.get("SMS_CONTENT").toString().substring(0, 15) + "..."%>
</font>
</div>

</td>

23: JSP中body在页面中的位置设置<body topmargin='20' leftmargin='20' bgcolor="#B1CCEA" >
24:Spring中的一个字符串工具类:StringUtils
import org.apache.commons.lang.StringUtils;
25:在Action中从jsp获得数组参数较可靠的写法:
String[] tempClientStatus = request.getParameterValues("tempClientStatus");
if (tempClientStatus == null) {
if( request.getParameter("tempClientStatus")!=null){
tempClientStatus = new String[] { request.getParameter("tempClientStatus") };
}else{
tempClientStatus = new String[]{ };
}

}

26:url前面的图标:
在<head>中加入:<link REL="SHORTCUT ICON" href="images/emo-9.ico">

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hanyankai/archive/2009/11/27/4891241.aspx

抱歉!评论已关闭.