首页 > 代码库 > JavaEE_ServletContext的简单应用

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的简单应用