Ajax的基本用法前面已经提到过,并且在上文中我们已经封装好了ajax,上文http://www.cnblogs.com/a986771570/p/8053935.html
并且可以拿来调用,现在我们来做一个小案例。
案例一:检查用户名是否可用
首先我们来看需求,要检查用户名是否可用,也就是用户名是否存在数据库那么数据库是比不可少的了。
那么就先来写一个建库的sql语句吧
drop database if exists javaweb;
create database javaweb;
use javaweb;
create table t_users(
id bigint primary key auto_increment,#逻辑主键
account varchar(255) not null,
password varchar(255) not null,
isDeleted boolean default false
);
紧接着我们将t_user表中设置账号为admin,密码也为admin
由于要将数据库的值取出来,那么就需要使用Jdbc来操作数据库
Jdbc主要代码,注意设置数据库的账号密码,以及导入数据库驱动包放到lib文件里
mysql-connector-java-5.1.7-bin
JDBC主要部分
private final static String dbdriver = "com.mysql.jdbc.Driver";
private final static String dburl = "jdbc:mysql://localhost:3306/javaweb?seUnicode=true&characterEncoding=UTF8";
private final static String dbusername = "root";
private final static String dbpassword = "root";
static
{
try
{
Class.forName(dbdriver);
} catch (ClassNotFoundException e)
{
throw new ExceptionInInitializerError(e);
}
}
public static Connection createConnection() throws SQLException
{
return DriverManager.getConnection(dburl, dbusername, dbpassword);
}
public static ResultSet executeQuery(Connection conn, String sql,
Object... parameters) throws SQLException
{
PreparedStatement ps = null;
try
{
ResultSet rs = null;
ps = conn.prepareStatement(sql);
for (int i = 0; i < parameters.length; i++)
{
ps.setObject(i + 1, parameters[i]);
}
rs = ps.executeQuery();
return rs;
} catch (SQLException ex)
{
close(ps);
throw ex;
}
}
public static void closeAll(ResultSet rs)
{
if (rs == null)
{
return;
}
try
{
close(rs.getStatement().getConnection());
close(rs.getStatement());
close(rs);
} catch (SQLException e)
{
}
}
UserDTO
紧接着,我们定义一个实体类来接受数据库传来的数据
package com.xyf.web6;
/**
* @账号密码实体类
* @author Ray
*
*/
public class UserDTO {
private int id;
private String account;
private String password;
private boolean isDeleted;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
}
UserDAO
再然后就是在DAO层里执行相关的数据库的查询语句,存放到DTO实体类中
package com.xyf.web6;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAO {
public static UserDTO getByUserName(String account)
{
//接受JDBC查询出来的数据
ResultSet rs=null;
try {
//查询出账户的数据存放到rs
rs=JdbcUtils.executeQuery("select *from T_Users where account=?",account);
if(rs.next())
{
return toModel(rs);
}
else
{
return null;
}
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
JdbcUtils.closeAll(rs);
}
}
private static UserDTO toModel(ResultSet rs) throws SQLException
{
UserDTO userDto=new UserDTO();
userDto.setAccount(rs.getString("account"));
userDto.setAccount(rs.getString("password"));
System.out.println(rs.getString("account"));
return userDto;
}
}
Servlet端
最后就只剩下servlet和jsp端了,servlet需要获得jsp端传输的数据执行校验后返回。
package com.xyf.web6;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckUserNameServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String account =req.getParameter("account");
UserDTO userDTO=UserDAO.getUserByName(account);
resp.getWriter().print(userDTO==null?"ok":"error");
}
}
JSP端
JSP端用户来输入数据,导入上文配置好的ajax 并向服务器发送的请求,通过服务器处理后返回的值来获得是否存在此账户,如此一个ajax的登陆校验就完成了,通过msg来传输回到JSP端实现页面的刷新
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="ajax.js"></script>
<script>
window.onload=function(){
var txtUserName= document.getElementById("txtUserName");
//onblur:焦点离开触发onblur事件
txtUserName.onblur = function(){
//var username = txtUserName.value;
var username = this.value;
rpajax("checkUserName?username="+username,function(data){
var msg = document.getElementById("msg");
if(data=="ok")
{
msg.innerHTML = "用户名可用";
msg.style.color = "green";
}
else if(data=="error")
{
msg.innerHTML = "用户名已经被注册 ";
msg.style.color = "red";
}
});
}
}
</script>
<body>
用户名:<input type="text" id="txtUserName">
<span id="msg"></span>
</body>
</html>
操作演示
1.启动servlet服务器
2.打开jsp页面
3.输入检测的用户名
如果输入admin则返回用户名被注册了
这样就完成了所有的校验功能了