您的位置:首页 > 其它

ServletContext练习

2015-09-26 15:25 260 查看
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendMsgServlet extends HttpServlet{
private ServletContext application;
public void init(){
System.out.println("init");
//获取上下文
application = this.getServletContext();
List<String> msglist = new ArrayList<String>();
application.setAttribute("MsgList", msglist);
}
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
System.out.println("doGet");
String ip = req.getRemoteAddr();//获取ip
String msg = req.getParameter("msg");//发送的消息
String face = req.getParameter("face");//表情图片
String context = ip+" say:"+msg+"<img src='faces/"+face+".gif'>";
List<String> msgs = (List<String>)application.getAttribute("MsgList");
msgs.add(context);

PrintWriter pw = resp.getWriter();
pw.write("<html>");
pw.write("<body>");
pw.write(context);
pw.write("<div class=\"send\">"+"		<form action=\"sendMsg\" method=\"post\">"+"			<input type=\"text\"  id=\"sendText\" name=\"msg\"/>"+"			<select name=\"face\" class=\"face\">"+"				<option value=\"1\">suprise</option>"+"				<option value=\"2\">embarase</option>"+"				<option value=\"3\">sex</option>"+"			</select>"+"			<input type=\"submit\" value=\"submit\" id=\"submit\"/>"+"		</form>"+"	</div>");
pw.write("</body>");
pw.write("</html>");
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
System.out.println("doPost");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: