在java Web中如何用Ajax实现用户名已存在
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在java Web中如何用Ajax实现用户名已存在相关的知识,希望对你有一定的参考价值。
我是初学者,请高手提供代码,包括java类,和jsp页面的代码,急啊~~~~!!
我给你做一个例子:希望能帮到你。实现的功能:注册页面上当输入“lixin”时,显示该用户已被注册。其他的名称无所谓。希望能帮到你。欢迎追问。
一个简单的jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" language="javascript">
//根据浏览器的不同创建不同的XMLHttpRequest
function createXmlHttpRequest()
var xmlreq=false;
if(window.XMLHttpRequest)
xmlreq=new XMLHttpRequest();
else if(window.ActiveXobject)
try
xmlreq = new ActiveXobject("Msxm12.XMLHTTP");
catch(e1)
try
xmlreq = new ActiveXobject("Miscoft.XMLHTTP");
catch(e2)
return xmlreq;
//
function usernameCheck()
var username = document.all.username.value;//获得text的值
var request = createXmlHttpRequest();//创建request的对象
request.open("post","servlet/ValidationServlet?username="+username);
request.send();
request.onreadystatechange = function()
if(request.readyState==4&request.status==200)
var value = request.responseText;
if(value=="true")
document.all.unc.innerHTML="该用户名已经被注册";
else
document.all.unc.innerHTML="该用户可以注册";
</script>
</head>
<body>
用户姓名:<input type ="text" name="username" onblur="usernameCheck()" /><font color="red" size="-1" id="unc"></font>
<br>
用户密码:<input type ="password" name= "userpw" />
</body>
</html>
用到的Servlet:
package sample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationServlet extends HttpServlet
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
this.doPost(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html");
String username = request.getParameter("username");
if(username.equals("lixin"))
response.getWriter().print("true");
else
response.getWriter().print("false");
参考技术A 初学者??这些是我学java一年才开始学的东西,这些东西太多了,都只能说一下思路,写代码,太长,要写好几百行,你写一个dao方法,按照用户名从数据库查询,如果不为空则就是用户名存在,反之不存在,既然你是初学者,我用其他快捷的方式完成了你也看不懂,最基础的太长,我不想写,所以你还是在网上找些例子看着学习吧,别人完成的毕竟没有自己完成的理解深刻 参考技术B 数据库操作类(mysql数据库)1.import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class BaseDao
protected Connection conn;
protected Statement sta;
protected ResultSet rs;
protected PreparedStatement ps;
public void setConnection()
try
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/dianlv";
conn = DriverManager.getConnection(url,"root","root");
catch (ClassNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
public void closeAll()
try
if(rs!=null)
rs.close();
if(ps!=null)
ps.close();
if(sta!=null)
sta.close();
if(conn!=null)
conn.close();
catch(SQLException e)
e.printStackTrace();
2.UserDao类集成baseDao类,实现对数据库中的数据名字超找:import java.sql.SQLException;public class UserDao extends BaseDao
/**
* 验证用户名是否成功;如果成功了返回true;
*
* **/
public boolean checkUserName(String userName)
boolean flag = false;
this.setConnection();
String sql ="select * from users where userName = ?";
try
ps = conn.prepareStatement(sql);
ps.setString(1,userName);
rs = ps.executeQuery();
if(rs.next())
flag = true;
catch (SQLException e)
// TODO Auto-generated catch block
e.printStackTrace();
return flag;
3.上面代码实现应该有一个user实体:创建user实体类:public class User
private String userName;
private int id;
private String password;
public String getUserName()
return userName;
public void setUserName(String userName)
this.userName = userName;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
4.写一个servlet用户验证用户名是否重复;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.fz.dao.UserDao;public class CheckUserNameServlet extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException doPost(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
5:jsp页面用于用户的操作,上面用到ajax技术用户验证用户名是否重复<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function checkUnique()
var content = $('#userName').val(); //获取文本框中输入的内容
var url = 'servlet/CheckUserNameServlet';
$.post(
url, //处理请求的url
'name':content, //传递的参数
function(data) //请求处理完毕之后的回调函数
if(data == 'true')//返回的是字符串不能用data = false这样比较
$("#s1").text("用户名不唯一");```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
else if(data == 'false')
$("#s1").text("用户名可用");
);
</script> </head>
<body>
<% request.setCharacterEncoding("utf-8");
%>
<form action="">
用户名:<input type="text" name="uerName" onblur="checkUnique();" id = "userName"/> <span id="s1"></span><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
String userName = request.getParameter("userName");
if(userName!=null && !userName.isEmpty())
UserDao dao = new UserDao();
boolean b = dao.checkUserName(userName);
PrintWriter out = response.getWriter();
out.print(b);
out.flush();
out.close();
注意把jquery的jar报引到项目下,使用jquery方式实现ajax。 参考技术C 你这不是不会。是一点都不会?
在Java中如何用interrupt优雅的结束线程
一般来说线程执行完run()之后就自动结束了,不过有些时候我们需要线程不停的做一些事情,也就是使用while循环,那么这时候该如何停止线程呢?
这个问题需要分情况来讨论,如果线程做的事情不是耗时的,那么只需要使用一个标志即可,具体的代码如下:
class MyThread extends Thread
private volatile boolean isStop = false;
public void run()
while (!isStop)
System.out.println("do something");
public void setStop()
isStop = true;
如果需要退出时,调用setStop()即可。这里使用了一个Java关键字volatile,这个关键字的目的是如果修改了isStop的值,那么在while循环中可以立即读取到修改后的值,关于volatile的详细介绍可以参考我的另一篇博文 java线程同步volatile与synchronized
如果线程做的事情是耗时或者说阻塞的(如调用了sleep,同步锁的wait,socket的receiver,accept等方法),那么就需要用到interrupt()了,调用该函数时会把线程设置为中断状态。如果是sleep,wait则会抛出InterruptedException异常,代码中通过捕获该异常,然后break出循环,就可以了。代码如下:
public static void main(String[] args)
Thread t1 = new Thread(new Runnable()
@Override
public void run()
System.out.println("t1 run...");
int i = 0;
//location 2
while (Thread.currentThread().isInterrupted() == false)
System.out.println("i is " + i);
i++;
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println("this is InterruptedException");
break; //location 1
boolean isInterrupted = Thread.currentThread().isInterrupted();
System.out.println("thread is interrupt ? " + isInterrupted);
);
t1.start();
System.out.println("main run...");
try
Thread.sleep(10);
catch (InterruptedException e)
e.printStackTrace();
t1.interrupt();
程序很简单,运行后,启动t1线程,然后主线程sleep 10毫秒,接着执行interrupt,让t1处于中断状态。结果打印如下:
main run...
t1 run...
i is 0
this is InterruptedException
thread is interrupt ? false
因为执行了interrupt,而t1正处于sleep状态,所以会抛出 InterruptedException 异常,捕获异常后执行break就可以跳出while循环,这样线程就可以结束了。这里需要注意的是,捕获异常的同时,程序会把线程的中断状态重置,所以下面判断的结果为false。如果这里(location 1)不执行break,那么while循环会一直执行下去。
下面来看看 isInterrupted()和 interrupted()的区别,代码如下:
public static void main(String[] args)
Thread t1 = new Thread(new Runnable()
@Override
public void run()
System.out.println("t1 run...");
int i = 0;
//location 2
while (Thread.currentThread().isInterrupted() == false)
System.out.println("i is " + i);
i++;
boolean isInterrupted = Thread.currentThread().isInterrupted();
System.out.println("thread is interrupt ? " + isInterrupted);
);
t1.start();
System.out.println("main run...");
try
Thread.sleep(10);
catch (InterruptedException e)
e.printStackTrace();
t1.interrupt();
这里,先启动线程t1,然后主线程sleep 10毫秒,接着执行t1的interrupt函数。结果打印如下:
main run...
t1 run...
i is 0
i is 1
。。。
i is 305
i is 306
thread is interrupt ? true
这很容易理解,一开始t1会一直打印,直到执行了interrupt,线程就会处于中断状态,那么while的条件就不满足了,所以会跳出循环。这种情况可以用在程序不抛出 InterruptedException 异常时结束线程。
如果把location 2处的判断条件改为 Thread.interrupted() == false ,那么会出现什么情况呢?看看打印吧!
main run...
t1 run...
i is 0
。。。
i is 372
i is 373
thread is interrupt ? false
前面的打印都一样,只是在打印线程的状态时,出现了差别。这是什么原因呢? 原来isInterrupted()和interrupted()都可以判断线程的状态,所不同的是,interrupted()在判断完之后会把线程的状态重置,所以后面再次判断时,线程就不处于中断状态了。
其实还有一个办法那就是使用thread.stop()来强行终止线程,不过由于该方法不安全已经废弃掉了,因为他有下面两个缺陷:
1. 立即抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath异常,包括在catch或finally语句中。
2. 释放该线程所持有的所有的锁。
好了,关于线程如何停止的问题到这里就圆满收官了,大家有什么问题欢迎留言讨论哈
以上是关于在java Web中如何用Ajax实现用户名已存在的主要内容,如果未能解决你的问题,请参考以下文章
SpringSecurity解决跨域问题,在SpringBoot整合SprinSecurity中如何用前后端分离Ajax登录,Ajax登录返回状态200还是近error