jsp的内置对象有9个,其中比较重要的有Out, request, response, session, application, exception.
cookie的例子
cookie1.jsp
<body>
<% //定义一个变量
String str="6";
int number=Integer.parseInt(str);
%>
<p>该数字位:<%=number %></p>
<%
//将str存入cookie
Cookie cookie=new Cookie("number",str);
//设置cookie的存活期为600秒
cookie.setMaxAge(600);
//将cookie保存到客户端
response.addCookie(cookie);
%>
<p><a href="../cookietest2.jsp">到达页面</a></p>
</body>
cookie2.jsp
<body>
<%
//从cookie中获取number
String str=null;
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("number")){
str=cookies[i].getValue();
break;
}
}
int number=Integer.parseInt(str);
%>
<p>该数字的平方为:<%=number*number %></p>
</body>
session的例子
<body>
<%
Date creatTime=new Date(session.getCreationTime());
Date lastAccessTime=new Date(session.getLastAccessedTime());
String title="欢迎返回我的页面";
int count=0;
String countKey="visitCount";
String userIDKey="userID";
String userID="sa";
//第一次访问应用程序界面
if(session.isNew()){
title="欢迎来到我的页面";
session.setAttribute(userIDKey, userID);
}else{
//设置访问页面计数
if(null==session.getAttribute(countKey)){
session.setAttribute(countKey, count);
}else{
count=(Integer)session.getAttribute(countKey);
}
count=count+1;
userID=(String)session.getAttribute(userIDKey);
session.setAttribute(countKey, count);
}
%>
<table border="1" align="center" cellpadding="0" cellspacing="0" width="400">
<tr>
<th width="30%">Session跟踪</th>
<th width="70%">值</th>
</tr>
<tr>
<td>Session id</td>
<td><% out.print(session.getId()); %></td>
</tr>
<tr>
<td>创建时间</td>
<td><% out.print(creatTime); %></td>
</tr>
<tr>
<td>上次访问时间</td>
<td><%out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>用户ID</td>
<td><%out.print(userID); %></td>
</tr>
<tr>
<td>页面访问次数</td>
<td><%out.print(count); %></td>
</tr>
<tr>
<td>页面访问次数</td>
<td><%out.print(userIDKey); %></td>
</tr>
</table>
</body>
usebean的例子
<body>
<form action="" name="form1" method="post">
请输入圆的半径:
<input type="text" name="radius" />
<input type="submit" name="submit" value="提交">
</form>
<!-- 加载javabean -->
<jsp:useBean id="cicle" class="ch07.CircleBean"></jsp:useBean>
<!-- 使用setproperty属性设置javabean属性 -->
<jsp:setProperty property="*" name="cicle"/>
<!-- 使用getproperty属性获取javabean属性 -->
<p>圆的半径:<jsp:getProperty property="radius" name="cicle"/></p>
<p>圆的面积:<jsp:getProperty property="area" name="cicle"/></p>
<p>圆的周长:<jsp:getProperty property="perimeter" name="cicle"/></p>
</body>