Ajax可以使网页实现异步更新,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。所以我通过Ajax的原理完成了聊天机器人。以下是代码部分。
我通过jsp完成了简单的网页界面 ,通过一个text框和一个button按钮,按下按钮触发响应事情,在“ul”标签生成一个“li”标签将text框的文本内容显示,同时构建请求报文(请求行,请求头,请求主体)之前创建回调函数接受响应报文。在回调函数中,同时也需要在“ul”标签里面创建“li”作为响应主体数据内容的显示
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
ul {
background: aqua;
width:300px;
border:0px solid red;
margin: 0px auto;
}
li {
list-style: none;
}
</style>
<title>Insert title here</title>
</head>
<body>
<h1></h1>
<input type="text" placeholder="输入内容">
<input type="button" value="发送">
<ul></ul>
<script type="text/javascript">
document.querySelector("input[type=button]").onclick=function(){
var lis=document.createElement("li");
lis.innerHTML=document.querySelector("input").value;
lis.style.background="pink";
document.querySelector("ul").appendChild(lis);
var xhr=new XMLHttpRequest();
xhr.open("get","ChatGame");
xhr.onload=function(){
var list=document.createElement("li");
list.style.background="red"
list.innerHTML=xhr.responseText;
document.querySelector("ul").appendChild(list);
}
xhr.send();
}
</script>
</body>
</html>
下面是我的servlet代码,通过一个字符串数组随机选取字符串作为响应主体返回到前端
package Check;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ChatGame
*/
public class ChatGame extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ChatGame() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String[]strings= {"aa","bb","cc","dd"};
Random random=new Random();
int i=random.nextInt(4);
response.getWriter().write(strings[i]);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}