• 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=" 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");
        }
    
    }
    最后的效果:
    文章未经版主同意不可任意转载,如有需要请标明文章出处。
  • 相关阅读:
    C#动态显示时间
    死锁问题
    TCP_NODELAY算法使用事项
    二叉搜索树的后序遍历
    从上到下打印二叉树
    栈的压入、弹出序列
    包含min函数的栈
    顺时针打印矩阵
    树的子结构
    合并两个排序链表
  • 原文地址:https://www.cnblogs.com/qihangzj/p/6545325.html
Copyright © 2020-2023  润新知