2018.6.27 Ajax实现异步刷新

Servlet获取URL地址。在HttpServletRequest类里,有以下六个取URL的函数:

getContextPath 取得项目名 
getServletPath 取得Servlet名 
getPathInfo 取得Servlet后的URL名,不包括URL参数 
getRequestURL 取得不包括参数的URL 
getRequestURI 取得不包括参数的URI,即去掉协议和服务器名的URL 

相对应的函数的值如下:

getContextPath:/ServletTest 
getServletPath:/main 
getPathInfo:/index/testpage/test 
getRequestURL:http://localhost:8080/ServletTest/main/index/testpage/test 
getRequestURI:/ServletTest/main/index/testpage/test 

验证用户名

package com.glut.demo;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ValidateUserName extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("aa");
		List<String> usernames = Arrays.asList("AAA","BBB","CCC");
		String username = request.getParameter("username");
		System.out.println("aa");
		String result = null;
		if(usernames.contains(username)){
			result = "<font color='red'>该用户名已经被使用</font>";
		}else{
			result = "<font color='green'>该用户名可以使用</font>";
		}
		response.setContentType("text/html");
		response.getWriter().print(result);
	}
}

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Ajax请求demo</title>
	<!--
		1.导入jQurery库
		2.获取name="username" 的节点:username
		3.为username 添加change响应函数
		   3.1 获取username的value属性值,去除前后空格,准备发送Ajax请求
		   3.2 发送Ajax请求检验username是否可用
		   3.3 在服务端直接返回一个html片段 :<font color='red'>该用户名已经被使用</font>
		   3.4在客户端浏览器把其直接添加到#message的html中
	-->
	
	<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
  
  	<script type="text/javascript" >
  		$(function(){
  		 	$(":input[name='username']").change(function(){
  				var val = $(this).val();
  				val = $.trim(val);
  				if(val != " "){
  					var url = "${pageContext.request.contextPath} servlet/ValidateUserName";
  					var args = {"username":val,"time":new Date()};
  					$.post(url,args,function(data){
  						$("#message").html(data);
  					});
  				}
  			});
  		});
  	</script>
  </head>
  
  <body>
   <form action="" method="post">
   	Username:<input type="text" name="username"/>
   	<br>
   	<div id="message"></div>
   	<br>
   	<input type="submit" value="Submit"/>
   </form>
  </body>
</html>
原文地址:https://www.cnblogs.com/qichunlin/p/9231972.html