ajax

[size=small][color=blue]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" οnblur="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" οnblur="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" οnblur="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)" οnclick="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)" οnclick="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="测试" οnclick="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="" οnmοuseοver="changeNews(3)">财经</a>    

<a style="color: blue;font-size: 30px;font-weight: bold;" href="" οnmοuseοver="changeNews(4)">军事</a>    

<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="" οnmοuseοver="changeNews(1)">体育</a>    

<a style="color: blue;font-size: 30px;font-weight: bold;" href="" οnmοuseοver="changeNews(2)">娱乐</a>    

<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 οnlοad="createFirst()">

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

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

</select>

<select name="city" id="city" οnchange="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>[/color][/size]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值