前言
这是一个使用jsp内置对象application存储数据后,遍历application中数据的案例(注意:application中的数据在服务器重启后会丢失!)
代码
1.添加书籍界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
request.setCharacterEncoding("utf-8");
%>
<html>
<head>
<title>添加书籍</title>
</head>
<body>
<form action="add" method="post">
<table>
<tr>
<td>书名:<input type="text" name="bookname"/></td>
</tr>
<tr>
<td>作者:<input type="text" name="author"/></td>
</tr>
<tr>
<td><input type="submit" value="添加"/></td>
</tr>
</table>
</form>
</body>
</html>
2.处理保存添加的数据对象,并展示所有书籍
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>展示书籍</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
//得到需要添加的书籍信息,并实例化
BookBean bookBean=(BookBean) request.getAttribute("book");
//存到application中
application.setAttribute(bookBean.getName(),bookBean);
Enumeration names = application.getAttributeNames();
while(names.hasMoreElements()){//注意捕获异常!
try{
Object objname=names.nextElement();
if(application.getAttribute(objname.toString()) instanceof BookBean)
{
%>
<!--展示书籍-->
<h1><%=application.getAttribute(objname.toString()).getName()%></h1>
<%
}
}
catch (Exception e)
{
continue;
}
}
%>
</body>
</html>
3.Servlet
package Myjava.Servlet;
import Myjava.Bean.BookBean;
import java.io.IOException;
public class addServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
request.setCharacterEncoding("utf-8");
String b=request.getParameter("bookname");
String a=request.getParameter("author");
BookBean bookBean=new BookBean(b,a);
request.setAttribute("book",bookBean);
//页面跳转
request.getRequestDispatcher("show.jsp").forward(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
}