控制器Servlet则提供了简单的改变:
对于Ajax系统而言,服务器响应无须是整个页面内容,可以仅是
必需的数据,控制器不能将数据请求转发到jsp页面。
此时控制器有两个选择:
1、直接生成简单的响应数据。
在这种模式下,Servlet直接通过response获取页面输出流,通过
输出流生成字符响应。
package pers.zkr.chat.web;import java.io.IOException;import java.io.PrintWriter;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 pers.zkr.chat.service.ChatService;@WebServlet(urlPatterns={"/chat.do"})public class ChatServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String msg=request.getParameter("chatMsg"); System.out.println(msg); if(msg!=null&&!msg.equals("")){ String user=(String)request.getSession().getAttribute("user"); System.out.println(user+"user"); ChatService.instance().addMsg(user, msg); } //设置响应内容的类型 <strong>response.setContentType("text/html;charset=utf-8"); // 获取页面输出流 PrintWriter out = response.getWriter(); //直接生成响应 out.println(ChatService.instance().getMsg());</strong> request.setAttribute("msg",ChatService.instance().getMsg()); forward("/chat.jsp", request , response); } private void forward(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.getRequestDispatcher(url) .forward(request , response); } }
2、转向一个简单的jsp使用JSP页面生成简单的响应。
控制器将请求转发到另外的JSP页面,而JSP页面仅仅负责输出聊天信息
在这里需要一个jsp页面来接收控制器发来的数据,也是服务器的响应文本,而在
原来的页面,只需:
1)创建XMLHttpRequest对象
2) 发送请求
3)接收服务器的响应
package org.crazyit.chat.web;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.*;import org.crazyit.chat.service.*;/** * Description: * <br/>网站: <a href=//www.Vevb.com>错新站长站</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @version 1.0 */@WebServlet(urlPatterns={"/chat.do"})public class ChatServlet extends HttpServlet{ public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException { // 设置使用GBK字符集来解析请求参数 request.setCharacterEncoding("utf-8"); String msg = request.getParameter("chatMsg"); if ( msg != null && !msg.equals("")) { // 取得当前用户 String user = (String)request.getSession(true) .getAttribute("user"); // 调用ChatService的addMsg来添加聊天消息 ChatService.instance().addMsg(user , msg); } // 将全部聊天信息设置成request属性 <strong>request.setAttribute("chatList" , ChatService.instance().getMsg());</strong> // 转发到chatreply.jsp页面 forward("/chatreply.jsp" , request , response); } // 执行转发请求的方法 private void forward(String url , HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException { // 执行转发 request.getRequestDispatcher(url) .forward(request,response); }}
新闻热点
疑难解答
图片精选