`
xuxing
  • 浏览: 6845 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
  • lIO01: 字太多了乱,而且代码也不好看 啊
    ajax
  • lIO01: [size=x-small][size=xx-large][c ...
    ajax
  • lian819: 楼主的分享精神值得赞赏,但这些主要的代码,确实有点乱,建议整理 ...
    ajax
  • sangshuye: 好东西。打个可以运行的包扔上来吧
    ajax
  • dongxiaolei: LZ,这些代码看起来太乱了,能不能把你工程的代码打个war包放 ...
    ajax

ajax

    博客分类:
  • js
阅读更多

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>

分享到:
评论
5 楼 lIO01 2016-02-22  
字太多了乱,而且代码也不好看 啊
4 楼 lIO01 2016-02-22  
[size=x-small][size=xx-large][color=cyan][/color][/size][/size]
字太多了乱,而且代码也不好看 啊
3 楼 lian819 2013-08-02  
楼主的分享精神值得赞赏,但这些主要的代码,确实有点乱,建议整理一下,打包吧.
2 楼 sangshuye 2012-02-23  
好东西。打个可以运行的包扔上来吧
1 楼 dongxiaolei 2012-01-06  
LZ,这些代码看起来太乱了,能不能把你工程的代码打个war包放上来啊,那样会明朗一些,谢谢哈

相关推荐

    ajax面试题ajax面试题

    关于Ajax的常见面试题 1,Ajax和javascript的区别? javascript是一种在浏览器端执行的脚本语言,Ajax是一种创建交互式网页应用的开发技术 ,它是利用了一系列相关的技术其中就包括javascript。 Javascript是由...

    ASP.NET AJAX程序设计——第I卷:服务器端ASP.NET 2.0 AJAX Extensions与ASP.NET AJAX Control Toolkit 源代码

    本卷从最易于理解和使用的那部分入手,介绍ASP.NET AJAX框架中能够与传统ASP.NET无缝对接的服务器端部分,包括服务器端ASP.NET AJAX Extensions与ASP.NET AJAX Control Toolkit。这部分内容不需要读者有任何的客户端...

    实例详解Android Webview拦截ajax请求

    Android Webview虽然提供了页面加载及资源请求的钩子,但是对于h5的ajax请求并没有提供干涉的接口,这意味着我们不能在webview中干涉javascript发起的http请求,而有时候我们确实需要能够截获ajax请求并实现一些功能...

    ajax快速解决参数过长无法提交成功的问题

    在ajax中使用post方法,用常规的参数格式:param1=a1&param2=a2 ,当参数长度过长时,依然提交不成功。比如我们经常这样写一个ajax的post请求: $.ajax({ type: "post", // post or get contentType:"application...

    ajax控件ajax控件ajax控件ajax控件

    ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件

    ajax ajax原理 ajax代码 ajax编程 ajax学习

    ajax ajax原理 ajax代码 ajax编程 ajax学习

    ajax特效ajax特效ajax特效

    ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效ajax特效

    Ajax(Ajax使用js包)

    使用Ajax实现从服务器读取数据,包括Ajax实现的详细步骤

    ajax 基础教程源代码

    ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础教程源代码ajax 基础...

    asp版ajax用户注册 ajax 注册程序 asp版 ajax

    学习的网上的一个ajax版注册程序,对界面进行了改变!是适合学习ajax的朋友的一个好的例子!

    掌握Ajax 学习资料pdf

    掌握 Ajax第 1 部分-Ajax 简介 掌握 Ajax第 2 部分-使用 JavaScript 和 Ajax 发出异步请求 掌握 Ajax第 3 部分-Ajax 中的高级请求和响应 掌握 Ajax第 4 部分-利用 DOM 进行 Web 响应 掌握 Ajax第 5 部分-操纵 DOM ...

    ajax控件ajax控件

    ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件ajax控件...

    完全手册ASP.NET AJAX实用开发详解 源码

    并应用上述知识开发了8个基于AJAX的Web应用系统,如基于AJAX的文件和图像处理、AJAX祝福墙、AJAX留言簿、AJAX聊天室、AJAX RSS阅读器、AJAX相册、基于AJAX的电子邮件处理等。最后以两个大型的AJAX Web应用系统(基于...

    Java Ajax分页,jsp ajax分页

    Ajax + JavaScript + MySQL 实现的Ajax分页功能

    Ajax Ajax本质 Ajax本质源码

    Ajax Ajax本质 Ajax本质源码 Ajax Ajax本质 Ajax本质源码 Ajax Ajax本质 Ajax本质源码

    AJax详解.chm

    第 1 部分:Ajax 简介 第 2 部分:: 使用 JavaScript 和 Ajax 发出异步请求 第 3 部分: Ajax 中的高级请求和响应 第 4 部分: 利用 DOM 进行 Web 响应 第 5 部分: 操纵 DOM 第 6 部分: 建立基于 DOM 的 Web 应用程序 第...

    ajax例子ajax例子

    ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子ajax例子

    ajax 分页ajax 分页ajax 分页

    ajax 分页ajax 分页ajax 分页

    支持AJAX的TreeView树例子,使用省市县三级xml作演示

    看到网上很多想用ajax的树的例子,很奇怪,明明TreeView自带AJAX功能,取非要自己去写一大堆代码, 工作量增加了,而性能又没有提高多少 正好自己这次用到了,就做了一个例子,供大家一起研究参考 注:顺便下载了一...

    ajax详解ajax详解ajax详解ajax详解ajax详解ajax详解ajax详解ajax详解ajax详解

    ajax详解ajax详解ajax详解 ajax详解ajax详解ajax详解 ajax详解ajax详解ajax详解 ajax详解ajax详解ajax详解

Global site tag (gtag.js) - Google Analytics