遍历输出所有application中的数据

前言

这是一个使用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 {

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值