首页 > 代码库 > jsp 用application对象制作留言板

jsp 用application对象制作留言板

 1 <%@ page contentType="text/html; charset=gb2312"%>
 2 <html>
 3 <body>
 4     <form action="show.jsp" method="post">
 5         输入名字:<input type="text" name="name"><br> 留言标题:<input
 6             type="text" name="title"><br> 留言:<br>
 7         <textarea rows="10" cols="30" name="text" wrap="physical"></textarea>
 8         <br> <input type="submit" value=http://www.mamicode.com/"提交"><br>
 9     </form>
10     <form action="chuli.jsp" method="get">
11         <input type="submit" name="look" value=http://www.mamicode.com/"查看留言板"><br>
12     </form>
13 
14 
15 </body>
16 </html>


<%@ page contentType="text/html; charset=gb2312"%>
<%@page import="java.util.Vector"%>
<%@ page import="java.util. *"%>
<%
    request.setCharacterEncoding("gb2312");
    String name = request.getParameter("name");
    String title = request.getParameter("title");
    String text = request.getParameter("text");
    if (name == null || name.length() == 0)
        name = "";
    if (title == null || title.length() == 0)
        title = "";
    if (text == null || text.length() == 0)
        text = "";
    String s = name + "#" + title + "#" + text;
    add(s);
%>
<%!Vector vector = new Vector();
    ServletContext application;
    //有些服务器不直接支持application对象,
    //必须用ServletContext 类类声明这个对象,
    //再使用getServletContext方法
    //对application对象初始化
    int i = 0;

    synchronized void add(String s) {

        application = getServletContext();
        i++;
        vector.add("NO." + i + "," + s);
        application.setAttribute("mess", vector);
//如果添加的2个对象的关键字相同,则先前的关键字被清除,mess叫索引关键字
    }%>
<a href=http://www.mamicode.com/"chuli.jsp">返回留言界面</a>

 

 

<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="java.util.Vector"%>
<%!public String handString(String s) {
        try {
            byte b[] = s.getBytes("gb2312");
            s = new String(b);
        } catch (Exception exp) {
        }
        return s;
    }%>
<%
    Vector vector = (Vector) application.getAttribute("mess");
    //因为任何对象都可以添加到application中,取回对象时,
    //所以要强制转回原来的类型。
    for (int i = 0; i < vector.size(); i++) {
        //vector的长度就是vector.size();
        String message = (String) vector.elementAt(i);
        //Vector就是一个放数据的地方啊。elementat(i)就是取出数据的作用
        String str[] = message.split("#");
        out.print("留言人:" + handString(str[0]) + ";");
        out.print("标题:" + handString(str[1]) + "<br>");
        out.print("留言内容:" + "<br>" + handString(str[2]));

    }
%>
<a href=http://www.mamicode.com/"input.jsp">返回主界面</a>

 

jsp 用application对象制作留言板