package com.lk.action; public class LoginJson { private String un; public String getUn() { return un; } public void setUn(String un) { this.un = un; } public String execute() throws Exception { /** * 连接数据库的代码 * 我这里用到的sql语句 * executeQuery("select * from admin where admId='"+un+"'") */ if(查询结果存在){ un="用户名存在"; }else{ un="用户名不存在"; } return "success"; } }@H_404_0@
Struts.xml配置
<package name="Struts2_AJAX_DEMO" extends="json-default"> <action name="JsonPlugin2" class="com.lk.action.LoginJson"> <result type="json" /> </action> </package>@H_404_0@注意package后面的extends @H_404_0@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 'MyJsp.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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function isExists(str) { var xmlhttp; if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+,Firefox,Chrome,Opera,Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6,IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var result = eval('(' + xmlhttp.responseText + ')'); var isexists = result.un; document.getElementById("txtHint").innerHTML=isexists; } } xmlhttp.open("GET","JsonPlugin2?un="+str+"&random=" + new Date().getMilliseconds(),true); xmlhttp.send(); } </script> </head> <body> <input type="text" name="un" onblur="isExists(this.value)"/> <div id="txtHint">判断输入的是否存在</div> </body> </html>@H_404_0@大家不要被上面的JS吓住了,其实重点也就是下面的一部分,其他的无非就是判断浏览器啦生成相应的对象(xmlhttp)啦,不用多在意,基本是死的 @H_404_0@做到这里就ok了,发布部署,输入http://localhost:8080/AjaxDemo/MyJsp3.jsp就哦了 @H_404_0@输入用户名 焦点移开后台就进行判断用户是否存在啦~
@H_404_0@大家自由发挥吧。。。有问题可以邮箱我 或者留言~ 原文链接:https://www.f2er.com/ajax/166795.html