JavaEE_ServletContext的简单应用
Posted Davis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaEE_ServletContext的简单应用相关的知识,希望对你有一定的参考价值。
ServletContext:Servlet上下文--这是今天测试做的简易聊天室的核心代码
<%@ 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>Insert title here</title> </head> <body> <form action="sss" method="post"> <input type="text" name = "sayMsg" style=" width:640px;height:20px;"> <input type="submit" value="发送"> </form> </body> </html>
import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/sss") public class FayanServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FayanServlet() { super(); // TODO Auto-generated constructor stub } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //获取发言人的名称 HttpSession session = request.getSession(); String name = (String)session.getAttribute("name"); //获取发言人说的话 String msg = request.getParameter("sayMsg"); //获取其他人说的话 ServletContext sc = getServletContext(); String talk = ""; if(sc.getAttribute("talk")!=null){ talk = (String)sc.getAttribute("talk"); } //获取发言的时间 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(); String time = format.format(date); //组合发言的内容 StringBuffer str = new StringBuffer(); str.append(talk); str.append("<br>"); str.append(name); str.append("说:["+time+"]<br>"); str.append(msg); //将发言内容保存到ServletContext中 sc.setAttribute("talk",str.toString()); response.sendRedirect("talk.jsp"); } }
最后的效果:
以上是关于JavaEE_ServletContext的简单应用的主要内容,如果未能解决你的问题,请参考以下文章