一、Ajax实现步骤
使用Ajax技术实现异步交互:
- 创建XMLHttpRequest对象(根据浏览器的不同创建方式可能不同,特别是低版本的IE浏览器)
- 创建一个回调函数(可以简单理解为回来的时候再调用的函数,callback)
- 通过XMLHttpRequest对象设置请求信息(方式和路径,open操作)
- 向服务器发送请求(send操作)
- 创建回调函数,根据响应状态动态更新页面
- 编写服务器端处理客户端请求
二、原生请求
示例代码:
hello.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 'hello.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">
-->
</head>
<body>
<input type="submit" value="点我" name="" onclick="btnClick()">
</body>
<script type="text/javascript">
function btnClick() {
xmlhttp = null;
// 1、创建核心对象
if (window.XMLHttpRequest) {//返回值为true时说明是新版本IE或其他浏览器
xmlhttp = new XMLHttpRequest();
} else {//返回值为false时说明是老版本IE浏览器(IE5和IE6)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2、编写回调函数
xmlhttp.onreadystatechange = function() {
alert(xmlhttp.readyState);
}
//3、open,设置请求方式和路径
xmlhttp.open("get", "${pageContext.request.contextPath}/ajax1", true);
//4、send,发送请求
xmlhttp.send();
}
</script>
</html>
Servlet代码:
package com.itheima.ajax;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 入门
*/
public class Ajax1Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("请求来了~~");
response.getWriter().print("success~~");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
web配置信息:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Ajax1Servlet</servlet-name>
<servlet-class>Ajax1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajax1Servlet</servlet-name>
<url-pattern>/ajax1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三、get方式
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 'get.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">
-->
</head>
<body>
<input type="submit" value="点我" name="" onclick="btnClick()">
</body>
<script>
function btnClick(){
// 1、创建核心对象
if (window.XMLHttpRequest) {//返回值为true时说明是新版本IE或其他浏览器
xmlhttp = new XMLHttpRequest();
} else {//返回值为false时说明是老版本IE浏览器(IE5和IE6)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2、编写回调函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 接受服务器回送过来的数据
alert(xmlhttp.responseText);
};
}
// 3、open
xmlhttp.open("get", "${pageContext.request.contextPath}/ajax2?username=tom", true);
// 4、send
xmlhttp.send();
}
</script>
</html>
servlet代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ajax2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接受参数
String username = request.getParameter("username");
username = new String(username.getBytes("iso8859-1"),"utf-8") ;
System.out.println(username);
// 响应数据
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("姓名:" + username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
web代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Ajax1Servlet</servlet-name>
<servlet-class>Ajax1Servlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ajax2</servlet-name>
<servlet-class>ajax2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajax1Servlet</servlet-name>
<url-pattern>/ajax1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ajax2</servlet-name>
<url-pattern>/ajax2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
四、post方式
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 'get.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">
-->
</head>
<body>
<input type="submit" value="点我" name="" onclick="btnClick()">
</body>
<script>
function btnClick(){
// 1、创建核心对象
if (window.XMLHttpRequest) {//返回值为true时说明是新版本IE或其他浏览器
xmlhttp = new XMLHttpRequest();
} else {//返回值为false时说明是老版本IE浏览器(IE5和IE6)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2、编写回调函数
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 接受服务器回送过来的数据
alert(xmlhttp.responseText);
};
}
// 3、open
xmlhttp.open("post", "${pageContext.request.contextPath}/ajax2", true);
// 4、send
// 设置请求头
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=tom");
}
</script>
<form enctype></form>
</html>
servlet代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ajax2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接受参数
String username = request.getParameter("username");
username = new String(username.getBytes("iso8859-1"),"utf-8") ;
System.out.println(username);
// 响应数据
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("姓名:" + username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
注:这个地方在使用post发送请求的时候,可以通过url传递数据,但是要是不使用url而使用send的方式传递数据的话,必须首先设置表头,否则拿不到数据。这个地方可能就是我之前的那个bug的原因了。