1.新建一个Dynamic Web Project项目,里面新建两个jsp文件,整体的框架如下所示:
2.one.jsp里面的代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example</title>
</head>
<body>
<h2>四字成语接龙</h2>
<%
StringBuffer s = (StringBuffer) application.getAttribute("message");
if (s != null) {
out.print(s.toString());
} else {
out.print("还没有词语,请您龙头开始!<br>");
}
%>
<form action="two.jsp" method="post">
四字成语输入:<input type="text" name="mes"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
3.two.jsp文件里面的代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example</title>
</head>
<body>
<%
StringBuffer message=new StringBuffer("");
ServletContext application;
synchronized void sendMessage(String s) {
application=getServletContext();
message.append(s+"->");
application.setAttribute("message", message);
}
%>
<%
String content=request.getParameter("mes");
byte b[]=content.getBytes("UTF-8");
content=new String(b);
sendMessage(content);
out.print("您的四字成语已提交!3秒钟后回到成语页面,继续接龙!");
response.setHeader("refresh", "3;url=one.jsp");
%>
</body>
</html>
4. 在浏览器里面输入http://localhost:8080/meme/one.jsp运行之后得到的结果如下所示:
5.我的代码是按照书上的代码敲的,但是我的代码在application的地方报错了,我还没解决出来,希望大神帮忙解决一下,直接在下方留言就行。