码迷,mamicode.com
首页 > 编程语言 > 详细

JavaEE_ServletContext的简单应用

时间:2017-03-13 23:34:51      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:mit   import   request   protected   row   odi   value   serial   html 4.01   

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

标签:mit   import   request   protected   row   odi   value   serial   html 4.01   

原文地址:http://www.cnblogs.com/qihangzj/p/6545325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!