项目结构
前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>局部刷新</title>
<script type="text/javascript">
function doAjax(){
// 1.使用内存中的异步对象
var xmlHttp=new XMLHttpRequest();
// 2.绑定事件
xmlHttp.onreadystatechange=function (){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var data=xmlHttp.responseText;
document.getElementById("data").innerText=data;
}
}
// 3.初始化请求数据,获取dom对象的value属性值
var name=document.getElementById("name").value;
var weight=document.getElementById("weight").value;
var height=document.getElementById("height").value;
var param="name="+name+"&weight="+weight+"&height="+height;
xmlHttp.open("get","bmiAjax?"+param,true);
// 4.发送请求
xmlHttp.send();
}
</script>
</head>
<body>
<div>
姓名<input type="text" id="name"><br>
身高<input type="text" id="height">米<br>
体重<input type="text" id="weight">千克<br>
<input type="button" value="提交" onclick="doAjax()"><br>
<div id="data"></div>
</div>
</body>
</html>
请求映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>BmiServlet</servlet-name>
<servlet-class>com.bjpowernode.controller.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BmiServlet</servlet-name>
<url-pattern>/bmiAjax</url-pattern>
</servlet-mapping>
</web-app>
服务器处理,AjaxServlet
package com.bjpowernode.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String weight = request.getParameter("weight");
String height = request.getParameter("height");
Float h = Float.valueOf(height);
Float w = Float.valueOf(weight);
float bmi = w / (h * h);
String msg = "";
if (bmi <= 18.5) {
msg = "偏瘦!";
} else if (bmi > 18.5 && bmi <= 23.9) {
msg = "正常!";
} else if (bmi > 24 && bmi <= 27) {
msg = "偏胖!";
} else {
msg = "肥胖!!";
}
String ms="你好,"+name+"先生/女士,你的bmi为"+bmi+",你的身体状况为"+msg+"";
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.print(ms);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}