ajax入门

AJAX    A  synchronous  J A vaScript and  X  ML 异步刷新

传统方式如果校验用户名的话,需要提交验证,用户名存储在数据库中,只有提交才可与服务器交互。ajax是局部刷新的功能,下边的例子,就是可以直接和servlet交互,从而达到校验的目的。

get方式jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




??




	
	
	
	

get方式servlet

package cn.dzz.web.servlet;

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;

/**
 * Servlet implementation class Aservlet
 */
@WebServlet("/Aservlet")
public class Aservlet extends HttpServlet {
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("Hello Ajax!");
		
		response.getWriter().print("Hello Ajax!!!");
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");//从servlet中响应回ajax的数据编码问题
		
		request.setCharacterEncoding("UTF-8");//请求体参数数据中解决中文乱码,编码问题
		//获取请求参数
		String username = request.getParameter("username");
		System.out.println("(post章)Hello Ajax!"+username);
		
		response.getWriter().print("(post章)Hello Ajax!!!"+username);
	}
}

post方式jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




??




	
	
	
	

post方式servlet

package cn.dzz.web.servlet;

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;

/**
 * Servlet implementation class Aservlet
 */
@WebServlet("/Aservlet")
public class Aservlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");//从servlet中响应回ajax的数据编码问题
		
		request.setCharacterEncoding("UTF-8");//请求体参数数据中解决中文乱码,编码问题
		//获取请求参数
		String username = request.getParameter("username");
		System.out.println("(post章)Hello Ajax!"+username);
		
		response.getWriter().print("(post章)Hello Ajax!!!"+username);
	}
}

你可能感兴趣的:(前端)