ajax与后台的交互demo

这个demo主要演示ajax与tomcat服务器的简单交互操作!

思路:在输入框中输入用户名,如用户名为空,则显示“请输入用户名”;如输入的用户名已存在,则显示“错号”图片;不存在相同的用户名,则显示“对号”图片

源码链接:https://github.com/longhaicheng/ajax-and-java(可以给我一个star就好了!)

  • 目录截图
    ajax与后台的交互demo_第1张图片

  • 前端界面(比较简单)
    前端界面

  • 未输入
    ajax与后台的交互demo_第2张图片

  • 随机输入用户名
    随机输入

  • 输入已存在的用户名
    输入已存在的用户名

  • 代码:
    前端界面:

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




ajax提交



	
	
	
	

服务器端:

package testservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
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 test
 */
@WebServlet("/test")
public class test extends HttpServlet {
	private String teacher = "张三";
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public test() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8"); // 设置编码
		response.setCharacterEncoding("utf-8"); // 设置编码
		String name = request.getParameter("username"); // 得到前面的值
		String username = URLDecoder.decode(name, "utf-8"); // 对URL进行编码
		String url = "";
		if (teacher.equals(username.trim())) {
			url = "image/false.png";
		} else {
			url = "image/true.png";
		}
		// 返回路径
		response.getWriter().println(url);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

你可能感兴趣的:(java)