- 浏览: 208423 次
- 来自: 深圳
文章分类
- 全部博客 (161)
- java (15)
- JSTL (3)
- 分页 (4)
- JDK (1)
- 正则表达式 (1)
- struts (2)
- JS (11)
- Tomcat (7)
- XML (1)
- JSP (7)
- MD5加密 (1)
- log4j (1)
- SVN (11)
- Jquery (2)
- myeclipse (3)
- 聚生网管2011 (1)
- 验证码 (2)
- Hibernate (2)
- Andriod (1)
- 网站测试 (2)
- ajax (1)
- linux (2)
- Spring (4)
- oracle (1)
- 个人所得 (4)
- Html (1)
- CSS (1)
- mysql (15)
- 省市区(县)联动 (2)
- 网页背景音乐 (3)
- FTP服务器搭建 (1)
- FTP (3)
- 404 500错误 (2)
- 网站域名绑定 (1)
- 遇到比较纠结的问题 (1)
- 记住密码 (1)
- QQ在线交谈功能 (1)
- Mail (1)
- java邮件 (1)
- java高并发 (1)
- 注册码 (0)
- HTTP状态码 (1)
- PHP (11)
- DZ论坛 (9)
- dz (1)
- ISAPI_Rewrite3 (1)
- asp (3)
- SEO (1)
- dedecms (2)
最新评论
-
shaode2012:
一个个网上都是宁愿写那么多的代码,文字,也没见到几个愿意用数据 ...
省市区(县)联动代码 -
lqfACCP:
...
Pager标签库(分页显示)详解
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>
<a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="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="" onmouseover="changeNews(1)">体育</a>
<a style="color: blue;font-size: 30px;font-weight: bold;" href="" onmouseover="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 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(Asynchronous JavaScript and XML)是一种用于创建交互式网页应用的技术,由Jesse James Gaitett提出。它允许在不刷新整个页面的情况下,通过...理解并掌握AJAX的开发步骤和核心原理,对于现代Web开发至关重要。
### Ajax的实现步骤详解 #### 一、引言 Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。它通过在后台与服务器进行少量数据交换来实现这一点,从而使网页...
Ajax的原理主要包含以下几个步骤: 1. **创建 XMLHttpRequest 对象**:这是Ajax的基础,现代浏览器通常都内置了XMLHttpRequest对象。 2. **开启一个HTTP请求**:使用XMLHttpRequest对象的`open()`方法指定请求类型...
另外,压缩包内的文件“天气.html”可能是展示如何使用Ajax获取和执行JS代码的一个实例,而“jquery-1.3.js”是jQuery库的旧版本,jQuery提供了简化Ajax操作的API,如`$.ajax()`、`$.get()`、`$.post()`等,使得处理...
本教程将深入讲解如何使用AJAX实现用户登录和注册功能,这对于初学者来说是一个很好的起点。 首先,我们需要理解AJAX的基本结构。一个基本的AJAX调用通常涉及以下步骤: 1. 创建XMLHttpRequest对象:这是AJAX的...
AJAX 主要有以下几个步骤: 1. **创建 XMLHttpRequest 对象**:这是 AJAX 的核心,用于在客户端和服务器之间传输数据。 2. **定义请求类型和 URL**:设置请求方式(GET 或 POST),并指定要请求的 URL。 3. **设置...
**总结:**Ajax实例演示源代码为我们提供了学习和理解Ajax工作原理的实用资源。通过分析和实践这个例子,开发者能更好地掌握如何在实际项目中利用Ajax提升用户体验,同时也应关注其带来的挑战和限制。在不断发展的...
总结,Ajax 的实现原理主要包括使用 XMLHttpRequest 对象进行异步请求,通过 JavaScript 处理请求的发送和响应的接收,以此实现页面的局部更新,提升用户体验和性能。在实际开发中,通常还会结合 jQuery 或其他库...
**Ajax技术实现自动补全功能** Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。在Web开发中,它极大地提升了用户体验,尤其是在实现搜索框的自动补全功能...
综上所述,Ajax是提升Web应用程序性能和用户体验的关键技术,熟练掌握Ajax的使用和手写代码能力,对于开发高质量的Web应用至关重要。在实际项目中,开发者应根据需求选择适合的Ajax实现方式,并注意兼容性和性能优化...
Ajax封装则是将常见的Ajax操作进行模块化处理,方便开发者在项目中快速、高效地实现数据交互。本篇文章将深入探讨Ajax封装实例代码及其相关知识点。 首先,我们来看Ajax的核心原理:通过JavaScript创建...
本文将详细讲解在MOSS中使用Ajax的步骤,并提供相关资料,帮助开发者实现更加流畅的交互体验。 首先,理解Ajax在MOSS中的应用基础至关重要。MOSS自身并不直接支持Ajax,但可以通过扩展和利用JavaScript库,如jQuery...
请注意,实际的实现可能还会涉及其他技术,如使用现代的Fetch API替换XMLHttpRequest,或者使用库如jQuery简化DOM操作和AJAX请求。此外,为了提高用户体验,可以考虑添加加载指示器,以及在请求失败时提供友好的反馈...
"使用Ajax实现页面表格添删改查的异步刷新操作"是一个实用的技术实现,它允许用户在不刷新整个页面的情况下更新表格内容,从而提高页面响应速度和用户体验。 首先,我们需要理解AJAX的基本原理。AJAX通过JavaScript...
实现ASP和Ajax的结合,主要涉及以下几个关键步骤: 1. **创建Ajax请求**:在客户端JavaScript中,使用XMLHttpRequest对象创建一个新的HTTP请求。例如,可以创建一个函数,接收URL、方法(GET或POST)、数据等参数,...
总的来说,这个源代码示例旨在教授开发者如何使用AJAX和Prototype库创建一个用户友好的文件上传功能,同时展示如何实时更新文件上传进度,提升用户体验。理解和实践这个示例将有助于提高Web开发技能,特别是涉及到...
通过DWR,我们可以使用JavaScript直接调用服务器端的Java方法,实现Ajax(Asynchronous JavaScript and XML)的功能,即在后台与服务器交互数据并局部更新网页。 **Ajax**的核心是利用JavaScript进行异步数据请求,...
【标题】"源代码-AJAX 无刷新评论提交实现代码.zip" 提供的是一种使用 AJAX 技术在网页上实现实时、无刷新提交评论的功能。AJAX(Asynchronous JavaScript and XML)是一种在无需刷新整个页面的情况下,能够更新部分...
在IT行业中,前端开发...总的来说,结合jQuery和AJAX可以轻松实现动态的用户名验证功能,为用户提供即时的反馈,同时也提高了网站的交互性和响应速度。这种技术在现代Web应用中广泛应用,是前端开发者的必备技能之一。
通过以上步骤,我们可以实现一个在.NET环境下利用Ajax获取JSON数据,并用AMCharts创建饼图报表的功能。这样的图表不仅美观,而且能够实时展示和更新数据,对于数据分析和展示非常有用。在实际项目中,还可以根据需求...