遍歷輸出所有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 {

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章