`

ajax的操作步骤和代码实现

阅读更多


ajax操作步骤:

1.利用javascript创建ajax引擎,即XMLHttpRequest对象

2.在XMLHttpRequest中设置要发送的请求,利用的是open(first,second,third)方法 xmlHttp.open()

第一个参数代表:该次请求提交的方式:get/post

第二个参数代表:该次请求的路径url,如果是get,则需要在路径后加上传递的相应参数parama,该url为servlet对应的url

第三个参数代表:代表的是该次请求的模式,同步模式/异步模式(true),通常采用异步提交模式

3.发送请求,调用send方法

4.需要处理返回值,就要监听readyState,处理每次状态的改变,当状态为4时,将返回值进行真正处理



 * ajax详细步骤:

* 1.通过js创建ajax的引擎对象XMLHttpRequest对象

* 2.在该对象中设置要发送的请求及其参数 (请求是jsp或者是servlet对应的url-pattern)

* xmlHttp.open(first,second,third);

* @param first:提交的方式 get或者是post

* @param second:提交的请求 如果是get请求 则包含参数列表

* @param third:提交的模式是同步模式还是异步模式  true代表异步模式

* 3.发送请求给服务器  利用的是xmlHttp.send(null) 加上null代表火狐和ie都支持

* 4.利用xmlHttp的onreadystatechange的事件 来监视xmlHttp.readyState的状态  每次改变时都调用函数(回调函数)

* 5.在回调函数中处理返回值  利用dom模型写到页面的指定位置  实现局部刷新 

*



存在一个贯穿整个流程的readyState:分为0,1,2,3,4

0:创建但未调用

1:设置请求

2:发送,结果未知

3.请求成功发送

4.





status值:

200:请求成功

202:请求被接收,但未被完成

404:请求资源未找到

500:内部服务器错误






<%@ 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">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script type="text/javascript">

var xmlHttp;//用来存储ajax引擎对象 XMLHttpRequest

function createXmlHttp(){

if(window.XMLHttpRequest){

//针对firefox,mozillar,opera,safari,IE7,IE8

xmlHttp = new XMLHttpRequest();

//针对某些特定版本的mozillar浏览器的bug进行修正

if(xmlHttp.overrideMimeType){

xmlHttp.overrideMimeType("text/xml");

}

}else  if(window.ActiveXObject){

//针对IE6,IE5.5,IE5

try{

xmlHttp=new ActiveXObject("MSXML2.XMLHTTP");

}catch(e){

try{

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}catch(e){

alert("不能创建XmlHttpRequest");

}

}

}

}

/*

* ajax的步骤

* 通过事件触发javascript的函数

* 1.创建出ajax的引擎对象XMLHttpRequest对象

*  2.利用该对象设置要发送的请求及其参数(请求是jsp或者是servlet对应的url-pattern)

* 3.利用该对象进行发送请求给服务器

* 4.最后获取到服务器返回的结果 然后对其结果进行dom的操作 将其显示的页面中的某个部分 实现了局部刷新

*/

function checkEmail(obj){

createXmlHttp();//第一步

var url = "isOnly?value="+obj+"&k="+Math.random();//get方法地址和缓存

url = encodeURI(url);

xmlHttp.open('get', url,true);//第二步  设置要发送的请求及其参数

xmlHttp.send(null);//第三步 发送请求给服务器  null代表火狐ie都支持发送

xmlHttp.onreadystatechange = callback;//当readyState的状态发生改变时触发名字叫做callback的函数  注意该函数在这不能加()

}

function callback(){

//xmlHttp.readyState为4时  代表服务器已经将数据发送给浏览器端的xmlHttp对象

var message ="";

if(xmlHttp.readyState == 4){

if(xmlHttp.status==200){

message=xmlHttp.responseText;

}else if(xmlHttp.status==500){

message ="服务器内如错误";

}else if(xmlHttp.status==404){

message="路径错误";

}

document.getElementById("emailError").innerHTML = message;//返回值保存在xmlHttp.responseText

}

}

//相当于用ajax功能实现了提交的功能(将参数传给服务器到数据库验证)

</script>

  </head>

  

  <body>

   <form action="" method="get">

    邮箱:

    <input type="text" name="email" onblur="checkEmail(this.value)"><span id="emailError"></span><br>

    昵称:

    <input type="text" name="username"><br>

    <input type="submit" value="登陆">

   </form>

  </body>

</html>




package com.pk.ajax.web.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.pk.ajax.dao.UserDao;


public class IsOnlyServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// request.setCharacterEncoding("UTF-8");

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

String value = request.getParameter("value");

value = new String(value.getBytes("iso-8859-1"),"UTF-8");//解决get方法传递中文

boolean flag = UserDao.getInstance().isOnly(0, value);


if(flag){

out.println("<img src='images/right.jpg'>");

}else{

out.println("<img src='images/wrong.jpg'><b style='color:red'>该用户名已经被注册</b>");

}

out.flush();

out.close();

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}


}






/*

* ajax提交方式post与get方式的区别

* 1.设置请求时不同 即open()方法不一样

* a).提交方式不同 即第一个参数不同

* b).请求的url即第二个参数也不同  如果是get提交方式的话  url中包含要提交的参数列表  如果是post则不包含

* 2.在发送之前post应该加上一句话 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

* 3.在send()方法中发送要传递给服务器的参数列表

* 注意:ajax  get和post提交中文参数时 不同   注意 ajax get提交方式 传递中文参数的问题





post提交:



<%@ 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 'ajaxpost.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">

var xmlHttp;

function createXmlHttp(){

if(window.XMLHttpRequest){

//针对firefox,mozillar,opera,safari,IE7,IE8

xmlHttp = new XMLHttpRequest();

//针对某些特定版本的mozillar浏览器的bug进行修正

if(xmlHttp.overrideMimeType){

xmlHttp.overrideMimeType("text/xml");

}

}else  if(window.ActiveXObject){

//针对IE6,IE5.5,IE5

try{

xmlHttp=new ActiveXObject("MSXML2.XMLHTTP");

}catch(e){

try{

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}catch(e){

alert("不能创建XmlHttpRequest");

}

}

}

}

/*

* ajax提交方式post与get方式的区别

* 1.设置请求时不同 即open()方法不一样

* a).提交方式不同 即第一个参数不同

* b).请求的url即第二个参数也不同  如果是get提交方式的话  url中包含要提交的参数列表  如果是post则不包含

* 2.在发送之前post应该加上一句话 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

* 3.在send()方法中发送要传递给服务器的参数列表

* 注意:ajax  get和post提交中文参数时 不同   注意 ajax get提交方式 传递中文参数的问题

*/

function checkUserName(obj){

createXmlHttp();

xmlHttp.open('post','isOnly',true);

var param = "value="+obj+"&k="+Math.random();

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttp.send(param);

xmlHttp.onreadystatechange = function(){

if(xmlHttp.readyState == 4){

var message = "";

if(xmlHttp.status == 200){

message = xmlHttp.responseText;

}else{

message = "<b style='color:red'>服务器正忙</b>";

}

document.getElementById("usernameError").innerHTML = message;

}

};

}

</script>

  </head>

  

  <body>

  <form action="" method="post">

  用户名:

  <input type="text" name="username" id="username" onblur="checkUserName(this.value)"/>

  <span id="usernameError"></span>

  </form>

  </body>

</html>


*/














利用dom模型处理返回值





var xmlHttp;

var returnMessage;

function createXmlHttp() {

if (window.XMLHttpRequest) {

xmlHttp = new XMLHttpRequest();

if (xmlHttp.overrideMimeType) {

xmlHttp.overrideMimeType("text/xml");

}

} else if (window.ActiveXObject) {

try {

xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {

alert("不能创建XmlHttpRequest");

}

}

}

}



function sendAjaxRequest(method,url,flag,param,writeMessage) {//传递参数

createXmlHttp();//第一步:创建xmlHttp对象

if(method.toLowerCase()=="get"){ //第二步:在进行设置参数前需要判断method,若为get,需要解决中文问题

url = encodeURI(url);

}

xmlHttp.open(method, url, flag);//第三步:设置参数

if(method.toLowerCase()=="post"){//第四步:在进行发送参数前,判断method,若为post,需要在发送前加句话

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

}

xmlHttp.send(param);//第五步:进行发送

xmlHttp.onreadystatechange=function(){

if(xmlHttp.readyState==4){

if(xmlHttp.status==200){

returnMessage = xmlHttp.responseText;

}else{

returnMessage = "服务器正忙";

}

writeMessage();//最后利用dom模型处理返回值

}

}

}




<script type="text/javascript" src="js/ajaxUtil.js"></script>

<script type="text/javascript">

function checkEmail(obj){

var param = "value="+obj+"&k="+Math.random();

sendAjaxRequest('post',"isOnly",true,param,writeEmail);

}

function writeEmail(){//第五步:利用回调函数处理返回值,调用了js文件中的方法,而rerturnMessage在js中是全局变量,所以可为该方法使用

/*var username = document.getElementById("username");

var span = document.createElement("span");

span.innerHTML = returnMessage;

username.parentNode.appendChild(span);*/

document.getElementById("emailError").innerHTML = returnMessage;

}

</script>

  </head>

  

  <body>

  邮箱:

   <input type="text" name="email" onblur="checkEmail(this.value)"><span id="emailError"></span>

  </body>

</html>





public List<User> getUsers(){

List<User> list = new ArrayList<User>();

User user= null;

Connection conn = null;

Statement st = null;

ResultSet rs = null;

String sql = "select * from user order by id desc";

conn = DBConn.getConn();

try {

st = conn.createStatement();

rs = st.executeQuery(sql);

while(rs.next()){

user = new User();

user.setEmail(rs.getString("email"));

user.setUsername(rs.getString("username"));

user.setPasswd(rs.getString("passwd"));

user.setSex(rs.getInt("sex"));

user.setId(rs.getInt("id"));

list.add(user);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, st, rs);

}

return list;

}

public User getUserById(int id){

User user = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

String sql ="select * from user where id=?";

conn =DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

ps.setInt(1, id);

rs = ps.executeQuery();

while(rs.next()){

user = new User();

user.setEmail(rs.getString("email"));

user.setUsername(rs.getString("username"));

user.setPasswd(rs.getString("passwd"));

user.setSex(rs.getInt("sex"));

user.setId(rs.getInt("id"));

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return user;

}





<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>

<%

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 'showusers.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" src="js/ajaxUtil.js"></script>

<script type="text/javascript">

var divId;

function checkUsers(obj){

divId=obj;

var url = "userMessage?flag=3&id="+obj+"&k="+Math.random();

sendAjaxRequest("get",url,true,null,writeUsersMessage);

}

function writeUsersMessage(){

document.getElementById(divId).innerHTML=returnMessage;

}

</script>

  </head>

  

  <body> 

   <c:choose>

    <c:when test="${empty list}">

    <h1 style="color:red;font-size:20px">没有用户信息</h1>

    </c:when>

    <c:otherwise>

    <c:forEach items="${list}" var="str">

    <div style="color:red;font-size:20px">

    用户名是:<a href="userMessage?flag=2&id=${str.id}" target="_blank">${str.username}</a>

    <br>

    ajax实现--用户名是:<a href="javascript:void(0)" onclick="checkUsers(${str.id})">${str.username}</a>

    <div id="${str.id}" style="color:orange;font-size:15px">

   

    </div>

    </div>

    </c:forEach>

    </c:otherwise>

   </c:choose>

  </body>

</html>





package com.pk.ajax.web.servlet;


import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.pk.ajax.dao.UserDao;

import com.pk.ajax.po.User;


public class UserMessageServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


response.setContentType("text/html;charset=UTF-8");

String flag = request.getParameter("flag");

if("1".equals(flag)){

getAllUsers(request,response);

}

if("2".equals(flag)){

getAllUsersMessage(request,response);

}

if("3".equals(flag)){

getAllUsersMessageById(request,response);

}

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


doGet(request,response);

}


public void getAllUsers(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

List<User> list = UserDao.getInstance().getUsers();

request.setAttribute("list", list);

request.getRequestDispatcher("/showusers.jsp").forward(request, response);

return;

}


public void getAllUsersMessage(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String id = request.getParameter("id");

User user = UserDao.getInstance().getUserById(Integer.parseInt(id));

request.setAttribute("user", user);

request.getRequestDispatcher("/user.jsp").forward(request, response);

return;

}

public void getAllUsersMessageById(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String id = request.getParameter("id");

User user = UserDao.getInstance().getUserById(Integer.parseInt(id));

request.setAttribute("user", user);

request.getRequestDispatcher("/ajaxuser.jsp").forward(request, response);

return;

}


}





dwr实现从数据库获取用户信息


public List<User> getUsers(){

List<User> list = new ArrayList<User>();

User user= null;

Connection conn = null;

Statement st = null;

ResultSet rs = null;

String sql = "select * from user order by id desc";

conn = DBConn.getConn();

try {

st = conn.createStatement();

rs = st.executeQuery(sql);

while(rs.next()){

user = new User();

user.setEmail(rs.getString("email"));

user.setUsername(rs.getString("username"));

user.setPasswd(rs.getString("passwd"));

user.setSex(rs.getInt("sex"));

user.setId(rs.getInt("id"));

list.add(user);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, st, rs);

}

return list;

}

public User getUserById(int id){

User user = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

String sql ="select * from user where id=?";

conn =DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

ps.setInt(1, id);

rs = ps.executeQuery();

while(rs.next()){

user = new User();

user.setEmail(rs.getString("email"));

user.setUsername(rs.getString("username"));

user.setPasswd(rs.getString("passwd"));

user.setSex(rs.getInt("sex"));

user.setId(rs.getInt("id"));

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return user;

}




package com.pk.dwrstudy.web.servlet;


import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.pk.dwrstudy.dao.UserDao;

import com.pk.dwrstudy.po.User;


public class UserManagerServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

UserDao dao = new UserDao();

List<User> list = dao.getAllUser();

request.setAttribute("list", list);

request.getRequestDispatcher("/showalluser.jsp").forward(request, response);

return;

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}




<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

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 'showalluser.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' src='/dwrstudy102/dwr/util.js'></script>

<script type='text/javascript' src='/dwrstudy102/dwr/interface/userDao.js'></script>

  <script type='text/javascript' src='/dwrstudy102/dwr/engine.js'></script>

<script type="text/javascript">

function showUserMessage(obj){

var divID = "div"+obj;

userDao.getUserByID(obj,function(data){

$(divID).innerHTML = "昵称为:"+data.username+ " 邮箱为:"+data.email +" 密码为:"+data.passwd;

});

}

</script>

</head>

  <body>

  <c:choose>

  <c:when test="${empty list}">

  <h2 style="color: red">没有用户信息</h2>

  </c:when>

  <c:otherwise>

  <c:forEach items="${list}" var="str">

<div>

昵称<a href="javascript:void(0)" onclick="showUserMessage(${str.id})">${str.username }</a>

<div id="div${str.id }" style="color: green;"></div>

<hr/>

</div>

  </c:forEach>

  </c:otherwise>

  </c:choose>

  </body>

</html>





<allow>

<!-- 注意:相当于UserDao userDao = new UserDao() 暂时不要单例模式-->

<create creator="new" javascript="userDao">

<param name="class" value="com.pk.dwrstudy.dao.UserDao" />

</create>

</allow>




DWR包含2个主要部分:

1.一个运行在服务器端的javaServlet,它处理请求并且向浏览器发回相应。

2.运行在浏览器端的JacaScript,它发送请求而且还能动态更新网页


DWR工作原理是童工动态把Java类生成为Javascript.它的代码就像Ajax魔法一样,你感觉调用就像是发生在浏览器端,但实际上代码调用发生在服务器端,DWR负责数据的传递和转换。这种从Java到JavaScript的远程调用功能的方式使DWR用起来有种非常像RMI或者SOAP的常规RPC机制,而且DWR的优点在于不需要任何网页浏览器插件就能运行在网页上



注:js中触发事件 自动发送ajax请求,请求名就是配置的实例名first(HellowWorld first = new HellowWorld()),会自动触发web.xml文件中的配置的dwr的servlet,该servlet作用会根据请求名first(HellowWorld first = new HellowWorld())去dwr.xml文件中进行查找javascript属性对应的值是否存在first的,找到就在该servlet种进行创建进行该类的实例化,然后通过页面中的方法名,直接调用该类中的对应的方法(所以要求js中调用的方法名和类中的方法名保持一致)



最原始的ajax

创建一个servlet 然后通过ajax的请求发送给服务器

在servlet中创建该类的实例化 即(HellowWorld first = new HellowWorld())

然后在该servlet中调用对应的方法



1.将dwr相应的jar包导入到工程中

2.在web.xml文件中进行dwr的servlet的配置

<servlet>

<servlet-name>dwr-invoker</servlet-name>

<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>

<init-param>

<param-name>debug</param-name>

<param-value>true</param-value>

</init-param>

</servlet>




<servlet-mapping>

<servlet-name>dwr-invoker</servlet-name>

<url-pattern>/dwr/*</url-pattern>

</servlet-mapping>


3.在web.xml文件的同一目录创建dwr.xml文件(创建的是new file:dwr.xml) 该文件是为了配置需要调用的类的配置文件


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">

<dwr>

<allow>

<create creator="new" javascript="first">

<param name="class" value="com.pk.dwrstudy.dwr.HellowWorld" />

</create>

</allow>

</dwr>



4.在dwr文件中配置需要在js中调用的普通的java类的信息






dwr运行原理:没有返回值和有返回值:




<servlet>

<servlet-name>dwr-invoker</servlet-name>

<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>

<init-param>

<param-name>debug</param-name>

<param-value>true</param-value>

</init-param>

</servlet>




<servlet-mapping>

<servlet-name>dwr-invoker</servlet-name>

<url-pattern>/dwr/*</url-pattern>

</servlet-mapping>




<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">

<dwr>

<allow>

<create creator="new" javascript="first">

<param name="class" value="com.pk.dwrstudy.dwr.SecondGet" />

</create>

</allow>

</dwr>





package com.pk.dwrstudy.dwr;


public class SecondGet {

public String secondGet(String username,String passwd){

System.out.println("用户名是:"+username+"密码是:"+passwd);

return "用户名是:"+username+"密码是:"+passwd;

}

}






<%@ 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 'seconddwr.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' src='/dwrstudy101/dwr/util.js'></script>

<script type='text/javascript' src='/dwrstudy101/dwr/interface/first.js'></script>

  <script type='text/javascript' src='/dwrstudy101/dwr/engine.js'></script>

<script type="text/javascript">

function testMethod(){

var username = document.getElementById("username").value;

var passwd = document.getElementById("passwd").value;

first.secondGet(username,passwd,function(data){

alert(data);

});

}

</script>

  

  <body>

    <form action="" method="get">

    Username:

    <input type="text" name="username"><br>

    Passwd:

    <input type="password" name="passwd"><br>

    <input type="submit" value="login">

    <hr>

    <input type="button" value="测试" onclick="testMethod()">

    </form>

  </body>

</html>






ajax和dwr实现新闻的局部刷新:


package com.pk.dwrstudy.dao;


import java.net.ConnectException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


import com.pk.dwrstudy.po.News;

import com.pk.dwrstudy.util.DBConn;


public class NewsDao {

//private NewsDao(){

//}

//private static NewsDao newsdao=null;

//public static NewsDao getInstance(){

// if(newsdao==null){

// newsdao=new NewsDao();

// }

// return newsdao;

//}

public List<News> getNews(int type,int startRow,int size){

List<News> list = new ArrayList<News>();

News news = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

String sql = "select * from news where type=? order by id desc limit ?,?";

conn = DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

ps.setInt(1,type );

ps.setInt(2, startRow);

ps.setInt(3, size);

rs = ps.executeQuery();

while(rs.next()){

news = new News();

news.setAddtime(rs.getDate("addtime"));

news.setAuthor(rs.getString("author"));

news.setContent(rs.getString("content"));

news.setId(rs.getInt("id"));

news.setIsdel(rs.getInt("isdel"));

news.setTitle(rs.getString("title"));

news.setType(rs.getInt("type"));

list.add(news);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return list;

}

}





package com.pk.dwrstudy.servlet;


import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.pk.dwrstudy.dao.NewsDao;

import com.pk.dwrstudy.po.News;


public class NewsManagerServlet extends HttpServlet {



public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String flag = request.getParameter("flag");

if("1".equals(flag)){

//获取主页面需要的数据 进行显示

showMainPage(request,response);

}

if("2".equals(flag)){

//获取主页面需要的数据 进行显示

showNewsByAjax(request,response);

}

}


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}


/*

* 获取主页面需要的数据 进行显示

*/

public void showMainPage(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

NewsDao dao = new NewsDao();

List<News> sportsList = dao.getNews(1, 0, 5);

List<News> moneyList = dao.getNews(3, 0, 5);

request.setAttribute("sportsList", sportsList);

request.setAttribute("moneyList", moneyList);

request.getRequestDispatcher("/shownews.jsp").forward(request, response);

return;

}


public void showNewsByAjax(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//PrintWriter out = response.getWriter();

//response.setContentType("text/html;charset=UTF-8");

//response.setCharacterEncoding("UTF-8");

String type = request.getParameter("type");

//out.println(type);

List<News> list = new NewsDao().getNews(Integer.parseInt(type), 0, 5);

//用printwriter去打印和用转发的jsp页面显示 

request.setAttribute("list", list);

//int i = 5/0;

request.getRequestDispatcher("/showallnews.jsp").forward(request, response);

return;

}


}






<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>

<%

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 'shownews.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" src="js/ajaxUtil.js"></script>

<script type="text/javascript">

function changeNews(obj){

var url = "newsManager?flag=2&type="+obj+"&k="+Math.random();

sendAjaxRequest('get',url,true,null,writeNews);

}

function writeNews(){

document.getElementById("first").innerHTML=returnMessage;

}

</script>

<%--   <script type='text/javascript' src='/dwrstudy101/dwr/util.js'></script>

<script type='text/javascript' src='/dwrstudy101/dwr/interface/newsdao.js'></script>

  <script type='text/javascript' src='/dwrstudy101/dwr/engine.js'></script>



<script type="text/javascript">

function changeNews(obj){

newsdao.getNews(obj,0,5,function(data){

var message = "";

for ( var i = 0; i < data.length; i++) {

message += "<a href='' style='color: green;font-size: 20px'>"+data[i].title+"</a><br/>"

}

$("first").innerHTML = message;

});

}

</script>

--%>

  </head>

  

  <body>

  <a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="changeNews(3)">财经</a>&nbsp;&nbsp;&nbsp;&nbsp;

  <a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="changeNews(4)">军事</a>&nbsp;&nbsp;&nbsp;&nbsp;

  <div id="first">

  <c:choose>

  <c:when test="${empty moneyList}">

  <h2 style="color: red">没有新闻信息</h2>

  </c:when>

  <c:otherwise>

  <c:forEach items="${moneyList}" var="str">

  <a href="" style="color: green;font-size: 20px">${str.title }</a><br/>

  </c:forEach>

  </c:otherwise>

  </c:choose>

  </div>

 

  <hr>

 

  <a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="changeNews(1)">体育</a>&nbsp;&nbsp;&nbsp;&nbsp;

  <a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="changeNews(2)">娱乐</a>&nbsp;&nbsp;&nbsp;&nbsp;

  <div>

  <c:choose>

  <c:when test="${empty sportsList}">

  <h2 style="color: red">没有新闻信息</h2>

  </c:when>

  <c:otherwise>

  <c:forEach items="${sportsList}" var="str">

  <a href="" style="color: green;font-size: 20px">${str.title }</a><br/>

  </c:forEach>

  </c:otherwise>

  </c:choose>

  </div>

  </body>

 


</html>








<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>

<%

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 'showallnews.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">

-->


  </head>

  

  <body>


  <c:choose>

<c:when test="${empty list}">

<h2 style="color: red">没有新闻信息</h2>

</c:when>

<c:otherwise>

<c:forEach items="${list}" var="str">

<a href="" style="color: red;font-size: 20px">${str.title }</a><br/>

</c:forEach>

</c:otherwise>

</c:choose>

 

  

  </body>

</html>






<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">

<dwr>

<allow>

<create creator="new" javascript="first">

<param name="class" value="com.pk.dwrstudy.dao.SecondGet" />

</create>

<create creator="new" javascript="newsdao">

<param name="class" value="com.pk.dwrstudy.dao.NewsDao" />

</create>

<convert match="com.pk.dwrstudy.po.News" converter="bean"></convert>

</allow>

</dwr>







省:

select * from chinacity where citypostcode like '__0000';


select * from chinacity where substr(citypostcode,3,4)='0000';


市:

select * from chinacity where citypostcode like '41__00' and citypostcode <>'410000'




级联菜单:省,市,区:例


package com.pk.dwrstudy.dao;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;


import com.pk.dwrstudy.po.ChinaCity;

import com.pk.dwrstudy.util.DBConn;


public class ChinaCityDao {

public List<ChinaCity> getProvince(){

List<ChinaCity> list = new ArrayList<ChinaCity>();//因为是要查询多个chinacity的信息,所以放在List中

ChinaCity chinacity = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

String sql = "select * from chinacity where citypostcode like '__0000'";

conn = DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

rs = ps.executeQuery();

while(rs.next()){

chinacity = new ChinaCity();

chinacity.setCityid(rs.getInt("cityid"));

chinacity.setCityname(rs.getString("cityname"));

chinacity.setCitypostcode(rs.getString("citypostcode"));

list.add(chinacity);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return list;

}

public List<ChinaCity> getCity(String citypostcode){

List<ChinaCity> list = new ArrayList<ChinaCity>();

ChinaCity chinacity = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

String sql = "select * from chinacity where citypostcode like ? and citypostcode <>?";

conn = DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

ps.setString(1, citypostcode.substring(0,2)+"__00");

ps.setString(2, citypostcode);

rs = ps.executeQuery();

while(rs.next()){

chinacity = new ChinaCity();

chinacity.setCityid(rs.getInt("cityid"));

chinacity.setCityname(rs.getString("cityname"));

chinacity.setCitypostcode(rs.getString("citypostcode"));

list.add(chinacity);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return list;

}

public List<ChinaCity> getArea(String citypostcode){

List<ChinaCity> list = new ArrayList<ChinaCity>();

ChinaCity chinacity = null;

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

//String sql = "select * from chinacity where citypostcode like ? and citypostcode <>?";

String sql = "select * from chinacity where substr(citypostcode,1,4)=? and citypostcode<>?";

conn = DBConn.getConn();

try {

ps = conn.prepareStatement(sql);

//ps.setString(1, citypostcode.substring(0,4)+"__");//从第0个位置上开始截取,截取到第4-1个位置上

ps.setString(1, citypostcode.substring(0,4));

ps.setString(2, citypostcode);

rs = ps.executeQuery();

while(rs.next()){

chinacity = new ChinaCity();

chinacity.setCityid(rs.getInt("cityid"));

chinacity.setCityname(rs.getString("cityname"));

chinacity.setCitypostcode(rs.getString("citypostcode"));

list.add(chinacity);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

DBConn.closeAll(conn, ps, rs);

}

return list;

}

}





<%@ 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 'testcity.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' src='/dwrstudy101/dwr/util.js'></script><%-- 只有导入该文件才可以使用$("city");--%>

 <script type='text/javascript' src='/dwrstudy101/dwr/interface/chinacity.js'></script>

   <script type='text/javascript' src='/dwrstudy101/dwr/engine.js'></script>

 <script type="text/javascript">

function createFirst(){

chinacity.getProvince(function(data){

var province = $("province"); //第一步:获取结点

for(var i=0; i<data.length;i++){//第二步:进行遍历

var option = new Option(data[i].cityname,data[i].citypostcode); //第三步:创建结点,并将值输入

province.options.add(option);//第四步:添加结点

}

});

}

function createSecond(obj){

chinacity.getCity(obj,function(data){

var city = $("city");

city.options.length = 1;

for(var i=0; i<data.length;i++){

var option = new Option(data[i].cityname,data[i].citypostcode);

city.options.add(option);

}

});

}

function createThird(obj){

chinacity.getArea(obj,function(data){

var area = $("area");

area.options.length=1;

for(var i =0;i<data.length;i++){

var option = new Option(data[i].cityname,data[i].citypostcode);

area.options.add(option);

}

});

}

</script>

  </head>

  

  <body onload="createFirst()">

    <select name="province" id="province" onchange="createSecond(this.value)">//要通过value值的改变选择相应的省对应的市

    <option value="00">请选择省</option>

    </select>

    <select name="city" id="city" onchange="createThird(this.value)">

    <option value="00">请选择市</option>

    </select>

    <select name="area" id="area">

    <option value="00">请选择区</option>

    </select>

  </body>

</html>






<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">

<dwr>

<allow>

<create creator="new" javascript="first">

<param name="class" value="com.pk.dwrstudy.dao.SecondGet" />

</create>

<create creator="new" javascript="newsdao">

<param name="class" value="com.pk.dwrstudy.dao.NewsDao" />

</create>

<create creator="new" javascript="chinacity">

<param name="class" value="com.pk.dwrstudy.dao.ChinaCityDao" />

</create>

<convert match="com.pk.dwrstudy.po.News" converter="bean"></convert>

<convert match="com.pk.dwrstudy.po.ChinaCity" converter="bean"></convert>

</allow>

</dwr>

分享到:
评论

相关推荐

    Ajax实现自动补全和搜索功能(jsp)

    Ajax实现自动补全和搜索功能,含有使用到的所有工具,以及实现的步骤文档和详细的代码说明

    表格制作软件中实现ajax跨域异步单点登录的方法

    finereport是一款企业级的表格制作软件,此文档讲述了在此表格制作软件中实现ajax跨域异步单点登录的具体方法,包括操作步骤和实现代码等。

    Ajax实现自动补全和搜索功能

    Ajax实现自动补全和搜索功能,含有使用到的所有工具,以及实现的步骤文档和详细的代码说明

    【JavaScript源代码】jQuery+ajax实现文件上传功能.docx

     jQuery+ajax实现文件上传功能(显示文件上传进度),供大家参考,具体内容如下 具体实现步骤 1、定义UI结构,引入bootstrap的CSS文件和jQuery文件 2、给上传按钮绑定点击事件 3、验证是否选择了文件 4、向FormData...

    C# Asp.Net Ajax简单聊天室源码和设计文档

    自已整理的资源:项目由Web网站转换为Web项目,然后将聊天室主界面的后台...来实现的局部刷新,用它来做Ajax的步骤是...本聊天室的灵魂就是这个消息循环图... 全文:http://www.our-code.com/news/2010726/n570762.html

    Sy5_AjAx.rar

    1. 熟悉Ajax开发步骤,能够使用Ajax进行数据请求; 2. 掌握XMLHttpRequest对象的常用方法和属性; 3. 学会使用Ajax同步/异步请求文本数据(字符串); 4. 掌握XML的编写规范,能够编写XML文件; 5. 学会使用Ajax同步...

    jQuery下的Ajax调试步骤

    具体实现方法和步骤请看下文: 第一步:在同一目录下创建ajax.html和ajax.php 第二步:编写ajax.html,注意修改文件编码为utf-8,代码如下: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Ajax&lt...

    [原创]帝国cms7.0无刷新Ajax登录退出、ajax注册信息验证插件

    只需3个步骤即可实现无刷新登录、退出、无刷新注册验证! 1.将e文件夹直接放到网站根目录,把css文本复制到网站的样式文件中! 2.在合适的位置加上这段代码:&lt;span id="show_userinfo"&gt;&lt;/span&gt; 3.先在head之间...

    java+mysql实现的代码分享网(所有源码已开源,效果可看网址:www.admintwo.com)

    6、运行步骤:首先将代码导入到eclipse或者其他IDE,然后利用mysql数据库建一个名为admintwo的库,将admintwo.sql执行一遍。修改jdbc.properties和img.properties,其中jdbc.properties是数据库连接信息,img....

    js实现对ajax请求面向对象的封装

    在js中使用ajax请求一般包含三个步骤: 1、创建XMLHttp对象 2、发送请求:包括打开链接、发送请求 3、处理响应 在不使用任何的js框架的情况下,要想使用ajax,可能需要向下面一样进行代码的编写 ...

    Jquery使用Firefox FireBug插件调试Ajax步骤讲解

    首先,我们用一个示例来说明JQuery的Ajax调用过程, 实现的一个功能是:点击确认支付按钮之后,实现余额支付的功能: ... 代码如下:&lt;input type=”submit” name=...如果使用$.post方式实现: 代码如下:var ABC = {  

    Ajax简单的异步交互及Ajax原生编写

    首先我们创建ajax的核心对象,由于浏览器的兼容问题我们在创建ajax核心对象的时候不得考虑其兼容问题,因为要想实现异步交互的后面步骤都基于第一步是否成功的创建了ajax核心对象. function getXhr(){ // 声明...

    Struts2+Jquery实现ajax并返回json类型数据

    主要实现步骤如下: 1、JSP页面使用脚本代码执行ajax请求 2、Action中查询出需要返回的数据,并转换为json类型模式数据 3、配置struts.xml文件 4、页面脚本接受并处理数据!

    基于ASP的网络聊天室的设计和实现(源代码+lw).rar

    在聊天室页面中,使用AJAX(Asynchronous JavaScript and XML)技术实现实时聊天功能。通过定时向服务器发送请求,获取最新的聊天记录并显示在聊天窗口中。 当用户发送消息时,通过AJAX将消息内容发送到服务器。...

    大学生智能消费记账系统-大学生智能消费记账系统的设计与实现代码-java-springboot-管理系统-代码-源码-项目-系统

    大学生智能消费记账系统-大学生智能消费记账系统的设计与实现代码-java-springboot-管理系统-基于springboot的大学生智能消费记账系统项目-代码-源码-项目-系统-毕设-网站 1、技术栈:java,springboot,vue,ajax,...

    thinkPHP5框架实现基于ajax的分页功能示例

    主要介绍了thinkPHP5框架实现基于ajax的分页功能,结合实例形式分析了thinkPHP5框架上进行ajax分页操作的具体步骤、实现代码与相关操作方法,需要的朋友可以参考下

    JAVA上百实例源码以及开源项目

    Java源代码实现部分,比较有意思,也具参考性。像坐标控制、旋转矩阵、定时器、生成图像、数据初始化、矩阵乘法、坐标旋转、判断是否是顺时针方向排列、鼠标按下、放开时的动作等,都可在本源码中得以体现。 Java...

    Ext3.2的Ext.data.Store类和Ext.Ajax类的实际运用

    使用步骤: 1、下载解压缩之后,使用IDE导入工程 2、在MyEclipse中启动服务器 3、打开IE在地址栏输入:http://localhost:8080/ExtAjax/TestAjax.html 如果一切正常,那么你可以看到Ext与Web服务器交互。 其中,我们...

    Ajax上传实现根据服务器端返回数据进行js处理的方法

    以前也做过上传,基本是是使用commons-fileupload组件,基本的步骤是使用servlet处理完上传之后,使用PrintWrite的对象实例输出显示内容,可以是直接输出内容,也可以是输出script进行操作如 代码如下:response....

    基于 jQuery 的 Web 源程序在线评测系统的设计与实现

    所以现在使用AJAX技术开发源代码在线评测系统的时机已经成熟了。 将 AJAX 技术用于源代码在线评测系统除了界面的漂亮,同时还大量减少了客户端和 服务器端传输的数据量,节约了带宽,提高了相应速度。这样也就提高了...

Global site tag (gtag.js) - Google Analytics