![](https://img-blog.csdnimg.cn/3e56d18d21f34321b0fa95d7b842884d.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiN5piv5L2g55qE6Iqd5aOrLg==,size_20,color_FFFFFF,t_70,g_se,x_16)
package com.symc.con_wall.service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Con_Wall")
public class Con_Wall extends HttpServlet{
private static final long serialVersionUID=1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response){
try {
request.setCharacterEncoding("utf-8"); //设置请求字符编码格式为utf-8
response.setContentType("text/html;charset=utf-8");//设置响应内容类型为text/html(文本/超文本标记语言),文本编码为utf-8
response.setHeader("refresh","1;Con_Wall");//设置一秒钟刷新页面一次
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ServletContext context=this.getServletConfig().getServletContext();//一个web应用中所有Servlet对象共享一个ServletContext,从而实现数据共享
//ServletContext域: 是一个容器,作用范围是应用程序范围内,服务器启动时它会为每一个web应用创建一个ServletContext对象,代表当前的web应用,关掉服务器时,ServletContext也会消失
String person=request.getParameter("person"); //获取请求传递的参数值
String content=request.getParameter("content"); //获取请求传递的内容
// System.out.println(person+content);
try {
Writer writer=response.getWriter(); //返回响应给客户端
if("".equals(person)||"".equals(content)||person==null||content==null){
if(context.getAttribute("name")==null||context.getAttribute("content")==null){
person="没有人";
content="没内容";
}
else{
person=context.getAttribute("name").toString();//取数据
content=context.getAttribute("content").toString();
}
writer.write("<h1>表白墙</h1><hr><h3>"+person+":"+content+"</h3>");//<h1>文章标题</h1>,<hr>水平线
}else{
context.setAttribute("name",person);//设置数据
context.setAttribute("content",content);
writer.write("<h1>表白墙</h1><hr><h3>"+person+":"+content+"</h3>");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response){
doGet(request,response);
}
}
<%@ 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>mypage</title>
</head>
<body>
<form action="Con_Wall" method="post">
请输入你要说悄悄话的对象:<input type="text" name="person" />
<br />
请输入你要对他(她)说的话:<textarea rows=3 cols=30 name="content"></textarea>
<br />
<input type="reset" /><input type="submit"/>
</form>
</body>
</html>