本篇文章介绍如何实现留言板,一共需要三个jsp页面,没有连接数据库。
NewFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>留言板</title>
</head>
<body>
<form action="process.jsp" method=post>
请输入您的姓名:<input type="text" name="name"><br><br>
请输入标题:<input type="text" name="title"><br><br>
请输入留言内容:<br>
    
<textarea rows="10" cols="30" name="content"></textarea><br><br>
<input type="submit" value="submit">
</form>
<br>
<form action="show.jsp">
<input type="submit" value="查看留言板">
</form>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*,java.text.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%//获取到用户输入得信息,并且将用户得信息处理成一个字符串
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
String title=request.getParameter("title");
String content=request.getParameter("content");
//out.println(name+"<br>");
//out.println(title+"<br>");
//out.println(content+"<br>");
if(name=="")
{
name="游客"+(int)(Math.random()*1000);
}
if(title=="")
{
title="无标题";
}
if(content==""){
content="无内容";
}
Date time=new Date();
DateFormat bf = new SimpleDateFormat("MM.dd HH:mm");
String format = bf.format(time);
out.println(format);
String s=name+"#"+title+"#"+format+"#"+content+"#";
addMessage(s);
%>
<%!
//定义向量vector装入用户输入得信息
Vector v=new Vector();
ServletContext application;
synchronized void addMessage(String s){
application=getServletContext();
v.add(s);
application.setAttribute("Message", v);
}
%>
<a href="NewFile.jsp"> 返回首页</a>
</body>
</html>
show.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%//从application获取输入得内容
Vector v=(Vector)application.getAttribute("Message");
//out.println(v);
%>
<h1>这是一个留言板</h1>
<%
for(int i=0;i<v.size();i++)
{
String a=(String)v.elementAt(i);
//out.println(a+"<br>");
String[] a1=a.split("#");//切割分离出信息
%>
姓名:<%=a1[0] %><br>
主题:<%=a1[1] %><br>
留言时间:<%=a1[2] %><br>
留言内容:<%=a1[3] %><br>
<hr>
<%
}
%>
</table>
</body>
</html>
运行NewFile.jsp
如果已经生成了web.xml文件就不用再建了,把其他的建好,代码放进去。运行失败的话,再改web.xml的代码。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Experiments</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行截图: