直接上代码
jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="css/css.css"> </head> <body onload="load()" > <br/><br/> <form action="" name=form1 method="post" > <div style="text-align:center; "><font size="4" face="黑体">用户名:</font> <input type="text" id='text1' name="username" value="" onchange="check1()" onmouseup="check1()" placeholder="Username"/> <br/> <input type="button" value="登录" onclick="go()" style= "height:30px;150px;background:#0066FF " onclick="show()"/> </div> </form> </body> <script> function go(){ var xmlhttp; name=document.getElementById("text1").value; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlhttp=new XMLHttpRequest(); } else { // IE6, IE5 浏览器执行代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { // alert(xmlhttp.responseText);//这里获取到的值为servlet反回的响应信息 take= xmlhttp.getResponseHeader('take');//获取指定Header中的值 alert(take); } } xmlhttp.open("GET","ttt?name="+name,true);//利用url传参 xmlhttp.send(); } </script> </html>
这种写法还是比较复杂的,如果结合JQury会简洁很多
servlet
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ttt */ @WebServlet("/ttt") public class ttt extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ttt() { 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.getWriter().append("Served at: ").append(request.getContextPath()); request.setCharacterEncoding("UTF-8"); String name; name=(String)request.getParameter("name"); PrintWriter out = response.getWriter(); response.setCharacterEncoding("utf-8"); response.resetBuffer();//清空原有返回信息 response.setHeader("take", "666");//添加自定义headler out.write(name);//将name写入响应信息 out.close(); } /** * @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); } }