JavaWeb———–Ajax页面局地刷新(二)

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

图片 1

出于要将数据库的值取出来,那么就供给采纳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">

</body>
</html>

 

操作演示

1.启动servlet服务器

2.打开jsp页面

图片 2

  3.输入检查和测试的用户名

  图片 3

要是输入admin则赶回用户名被登记了

 

 那样就完结了独具的校验功用了

 

相关文章