默认情况下返回HTML格式,所以不必设置,直接输出即可,案例:实时显示聊天内容
2、返回XML格式:
XML中常用attr()返回节点属性,应用find()方法获取XML文档文本节点
index.jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src ="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function getContent(){
$.get("ChatServlet?action=get&nocache"+new Date().getTime(),function(data){
var msg = "";
$(data).find("massage").each(function(){
msg += "<br>" + $(this).text();
});
$("#div1").html(msg);
},"XML");
}
$(document).ready(function(){
getContent();
setInterval("getContent()",1000); //必须加引号
});
$(document).ready(function(){
$("#btn").click(function(){
if($("#user").val() != ""){
if($("#speak").val() != ""){
$.post("ChatServlet?action=send",{ //$.post(url,data,success())方法
user:$("#user").val(),
speak:$("#speak").val()});
$("#speak").val("") ; //清空说话文本内容
$("#speak").focus();
}else {
alert("说话内容不能为空");
}
}else {
alert("用户名不能为空");
}
});
});
</script>
</head>
<body>
<div id = "div1" style = "height: 135px;background:red ;overflow:hidden"> 欢迎光临阿文聊天室</div>
<form action="" method = "post" name = "form1">
<input name = "user" type = "text" size = "20" id = "user">说:
<input name = "speak" type = "text" size = "50" id = "speak">
<input name = "btn" type = "button" id = "btn" value ="发送">
</form>
</body>
</html>
仅在getContext()中做了一点点改动,并在$.get()方法中设置返回类型。
ChatServlet:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Vector;
import javassist.expr.Instanceof;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ChatServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String args = request.getParameter("action");
if(args.equals("get")){
get(request, response);
}
else if(args.equals("send")){
send(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void get(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.println("<?xml version = '1.0'?>");
out.println("<chat>");
ServletContext application = getServletContext();
if(null != application.getAttribute("massage")){
//@SuppressWarnings("unchecked")
Vector<String> vec = (Vector<String>)application.getAttribute("massage");
for (int i = vec.size() -1; i >= 0; i--) {
out.println("<massage>"+vec.get(i) + "</massage>");
}
}else{
out.println("<massage>欢迎光临阿文聊天室</massage>");
}
out.println("</chat>");
out.flush();
out.close();
}
@SuppressWarnings("unchecked")
public void send(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
ServletContext application = getServletContext();
String user = request.getParameter("user");
String speak = request.getParameter("speak");
String msg = "["+user+"]说:"+speak;
Vector<String> vec = (Vector<String>)application.getAttribute("massage");
if(vec == null){
vec = new Vector<String>();
}
vec.add(msg);
application.setAttribute("massage", vec);
//request.getRequestDispatcher("ChatServlet?action=get&nocache"+new Date().getTime()).forward(request, response);
}
}
仅在get方法中作出修改。
XML数据格式特点:可移植性和可重用性强,但是XML文档占据空间大,与其他文档格式相比,解析和操纵相对慢些。
3、返回JSON格式:JSON数组的使用
修改之处:1)、index.jsp页面
function getContent(){
$.get("ChatServlet?action=get&nocache"+new Date().getTime(),function(data){
var msg = "";
var chats = eval(data); //eval()将字符串内容解析成js处理
$.each(chats,function(i){
msg += "<br>"+chats[i].massage;
});
$("#div1").html(msg);
},"JSON");
}
2)、ChatServlet中的get()函数
public void get(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.println("[");
ServletContext application = getServletContext();
String msg = "";
if(null != application.getAttribute("massage")){
//@SuppressWarnings("unchecked")
Vector<String> vec = (Vector<String>)application.getAttribute("massage");
for (int i = vec.size() -1; i >= 0; i--) {
msg += "{\"massage\":\"" + vec.get(i) + "\"},";
}
out.println(msg.substring(0,msg.length()-1));
}else{
out.println("{\"massage\":"+"\"欢迎光临阿文聊天室!\"}");
}
out.println("]");
out.flush();
out.close();
}