用JSP实现简单的留言板
作者:GGG166
在实现简单留言板时,本人用三个JSP页面来实现,分别是:输入页面(input)、处理页面(show)和显示页面(pane)。
输入页面有简单三部分组成:姓名、标题和评论,代码如下:
<%--
作者:GGG166
--%>
<%@page contentType="text/html;charset=gb2312" %>
<html>
<body>
<form action="show.jsp" method="post" name="form">
输入名字:<input type="text" name="name" value=""><br>
留言标题:<input type="text" name="title" value=""><br>
留言:<br>
<textarea name="message" rows="10" cols="40" wrap="physical">
</textarea>
<br><input type="submit" name="submit" value="提交">
</form>
<a href="pane.jsp">查看留言板</a>
</body>
</html>
处理页面就是接受从input页面的内容,加以处理。代码如下:
<%--
作者:GGG166
--%>
<%@page contentType="text/html;charset=gb2312" %>
<%@page import="java.util.*"%>
<html>
<body>
<%!
Vector v=new Vector();//动态数组
int i=0;
ServletContext application;
synchronized void leaveWord(String s){//方法声明,用于在添加评论
application=getServletContext();
i++;
v.add("No"+i+","+s);
application.setAttribute("Mess",v);
}
%>
<%
request.setCharacterEncoding("gb2312");//乱码处理
String name=request.getParameter("name");//接收姓名
String title=request.getParameter("title");//接收标题
String message=request.getParameter("message");//接收评论
if(name==null){
name="guest"+(int)(Math.random()*10000);
}
if(title==null){
title="无标题";
}
if(message==null){
message="无信息";
}
String s=name+"#"+title+"#"+message;
leaveWord(s);
out.print("你的评论已提交!");
%>
<a href="input.jsp">返回留言页面</a>
</body>
</html>
显示页面,就把所用评论显示出来,代码如下:
<%--
作者:GGG166
--%>
<%@page contentType="text/html;charset=gb2312" %>
<%@page import="java.util.*"%>
<html>
<body>
<%
request.setCharacterEncoding("gb2312");
Vector v=(Vector)application.getAttribute("Mess");
for(int i=0;i<v.size();i++){
String message=(String)v.elementAt(i);
String []a=message.split("#");
out.print("留言人:"+a[0]+",");
out.print("标题:"+a[1]+"<br>");
out.print("留言内容:"+a[2]+"<br>");
}
%>
</body>
</html>