之前在jsp中写js或者引入js,有不少引入了没什么效果,和用HBuilder写的效果差了很多,花了不少时间弄,没有搞定,应该是自己的底子太差劲了,对jsp和js的理解不够深;今天学了Ajax发现不少的东西用Ajax写起来更方便些。我就简单的写一个小功能实现一下登录。
//这是登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
//form表单
<form action="">
姓名:<input type="text" id="myinput" name="name" />
<span id="myspan"></span>
<br />
密码:<input type="password" id="mypwd" name="pwd" />
<br />
<input type="button" id="mybt" onclick="jump()" value="提交">
</form>
</body>
<script type="text/javascript">
//定义一个全局的ajax变量
var ajax;
//getAjax()方法用来获取一个Ajax对象
function getAjax() {
try {
//现代的浏览器获取Ajax的方法
ajax = new XMLHttpRequest();
} catch (e) {
//try中无法执行,得到错误,catch抓取错误,ie7以下的版本获取Ajax的方法
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
//返回一个Ajax对象
return ajax;
}
function jump() {
//得到Ajax的对象
ajax = getAjax();
//使用open方法与服务器建立连接
ajax.open("POST", "/java-9-19day/logins", true);
//监听ajax的状态,每当状态改变时,就会调用该函数
ajax.onreadystatechange = function() {
//当Ajax满足以下条件时就会进入下一步
if (ajax.readyState == 4 && ajax.status == 200) {
//获取服务器返回的数据
var result = ajax.responseText;
if (result == "true") {
//满足条件就转到welcome.jsp
location.href = "/java-9-19day/welcome.jsp";
document.getElementById("mybt").disabled = false;
} else {
//不满足条件进行提示,并将按钮变成不可用状态
document.getElementById("myspan").innerHTML = "error";
document.getElementById("mybt").disabled = true;
}
}
}
//Ajax时post提交,必须写这个请求头,就这么写,都是一样的
ajax.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
//获得form表单的数据
var name = document.getElementById("myinput").value;
var pwd = document.getElementById("mypwd").value;
//将其拼接成一个,发送到servlet中
var param = "name=" + name + "&password=" + pwd;
ajax.send(param);
}
</script>
</html>
package com.coding.ajaxpost;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/logins")
public class MyLoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf8");
System.out.println("come in");
//得到拼接的数据
String name = req.getParameter("name");
String pwd = req.getParameter("password");
System.out.println(name+"--"+pwd);
//进行判断
if (name.equals("admin") && pwd.equals("123")) {
//进行响应,返回数据
resp.getWriter().print(true);
}else {
resp.getWriter().print(false);
}
}
}
继续加油,程序员的道路才刚刚开始!!!