ServletContext是伴随着整个Web服务器运行阶段的:
对于所有的浏览器请求,都是可以通过requset获取ServletContext的
可以通过设置set/getAttribute()来获取保存留言
代码:
public class MyConTextServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>访问量及留言</TITLE></HEAD>");
out.println(" <BODY>");
ServletContext context=getServletContext();
Object o=context.getAttribute("count");
int count=0;
if(o==null){
}else{
count=(Integer)o;
}
count++;
out.print("网页访问量:"+count+"<br/>");
context.setAttribute("count", count);
o=context.getAttribute("msgs");
Map<String,String> map=null;
if(o==null){
map=new TreeMap<String,String>(new MyComp<String>());
}else{
map=(Map<String, String>)o;
String ip=request.getRemoteAddr();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String userMsg=format.format(new Date())+" "+ip;
String msg=request.getParameter("text");
if(msg!=null){
out.println(userMsg+":");
out.println("<br/>");
out.println(msg);
out.println("<br/>");
}
Set<Entry<String, String>> set=map.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Entry<String, String> en=it.next();
out.println(en.getKey());
out.println("<br/>");
out.println(en.getValue());
out.println("<br/>");
}
if(msg!=null)
map.put(userMsg, msg);
}
context.setAttribute("msgs", map);
out.print("<form action='MyConTextServlet' method='post'>");
out.print("留言:<input type='text' name='text'/>");
out.print("<input type='submit' value='提交'></form>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
class MyComp<E> implements Comparator<E>{
//比较器o1为后加对象
@Override
public int compare(E o1, E o2) {
if(o1 instanceof String&&o2 instanceof String){
String str1=((String)o1).split(" ")[0];
String str2=((String)o2).split(" ")[0];
DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date d1=format.parse(str1);
Date d2=format.parse(str2);
if(d1.after(d2)){
return -1;
}else{
return 1;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return -1;
}
}