概述
Ajax:一种不用刷新整个页面便可与服务器通讯的办法
Ajax的场景:百度搜索框、地图、弹幕等等
Ajax优点:可以便捷的反馈信息,用户体验良好,降低服务器的压力
jQuery实现ajax
EasyMall添加Ajax校验
在regist.jsp页面中添加用户名是否存在的ajax校验。当鼠标离焦时可以提示用户名是否存在。
创建新的servlet来进行ajax校验
package cn.tedu.servlet;
import cn.tedu.util.C3P0Utiles;
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 java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet("/servlet/AjaxcheckUsernameServlet")
public class AjaxcheckUsernameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.乱码问题
request.setCharacterEncoding("utf8");
response.setContentType("text/html;charset=utf8");
//2.获取ajax发送的参数---username
String username = request.getParameter("username");
//3.JDBC---查询数据库用户名是否存在
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = C3P0Utiles.getConnection();
ps = conn.prepareStatement("select * from user where username=?");
ps.setString(1,username);
rs = ps.executeQuery();
if(rs.next()){
//用户名存在
response.getWriter().write("用户名已存在!!!");
}else {
response.getWriter().write("用户名可以使用!!!");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
C3P0Utiles.close(conn,ps,rs);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
AjaxTextServlet: