- 浏览: 125348 次
文章分类
- 全部博客 (65)
- web验证码 (0)
- 工具类 (4)
- android基础 (17)
- android通信 (1)
- JFreeChart (1)
- java基础 (5)
- android控件 (4)
- FusionCharts (1)
- android Layout (1)
- json (2)
- HTTP协议 (1)
- cmd (1)
- struts (3)
- Spring (1)
- java网络编程 (3)
- Linux (1)
- DB (5)
- Open Source (1)
- css (0)
- javascript (7)
- jquery (0)
- Socket (1)
- ajax (1)
- 整合开发 (1)
- UDP协议 (1)
最新评论
-
hy18710385392:
亲:import com.nudms.server.nurse ...
java实现打印PDF文件解决方案 -
osacar:
MyPDFPrintPage这个类能提供下?
java实现打印PDF文件解决方案 -
井底之龙:
请问楼主定义的保存Button从开始到最后都没有从xml文件中 ...
Android之SharedPreferences的使用 保存用户设置 -
lohasle:
liangzb0614 写道你好,求一个MyPDFPrintP ...
java实现打印PDF文件解决方案 -
liangzb0614:
你好,求一个MyPDFPrintPage 类!拜托了liang ...
java实现打印PDF文件解决方案
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>
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开发草考文档,方便快捷1. AJAX介绍AJAX是一种运用JavaScript和可扩展标记语言(XML),在网络浏览器和服务器之间传送或接受数据的技术。2. AJAX实例AJAX可以用来创建更多交互式的网络应用程序。3. AJAX源...
Java AJAX(Asynchronous JavaScript and XML)分页与JSP(JavaServer Pages)相结合,可以提供无需刷新整个页面即可动态加载更多内容的能力,提高用户体验。本教程将深入探讨如何使用AJAX、JavaScript以及MySQL...
**Ajax 概述** Ajax(Asynchronous JavaScript and XML)是一种在无需刷新整个网页的情况下,能够更新部分网页的技术。它的核心是利用JavaScript与服务器进行异步数据交换,通过XML或者JSON格式传输数据,使得用户...
本卷从最易于理解和使用的那部分入手,介绍ASP.NET AJAX框架中能够与传统ASP.NET无缝对接的服务器端部分,包括服务器端ASP.NET AJAX Extensions与ASP.NET AJAX Control Toolkit。这部分内容不需要读者有任何的客户端...
在IT行业中,jQuery和Ajax是两个非常重要的技术,它们在构建动态、交互性强的Web应用程序时发挥着关键作用。jQuery是一个高效、简洁的JavaScript库,它简化了HTML文档遍历、事件处理、动画以及Ajax交互。Ajax...
"AJAX原理与技术的深入分析" AJAX(Asynchronous JavaScript and XML)是一种异步通信技术,允许Web应用程序异步地从服务器请求数据,而不需要重新加载整个网页。下面我们将深入分析AJAX的原理、技术、意义和发展...
**Ajax Interceptor:深入理解与应用** Ajax Interceptor 是一款专为谷歌浏览器(Chrome)设计的插件,它允许开发者在Ajax请求发送后和响应返回前进行干预,从而实现对AJAX请求数据的修改。这款插件对于前端开发、...
**AjaxRequest(Ajax使用包)** Ajax,全称Asynchronous JavaScript and XML(异步JavaScript和XML),是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。AjaxRequest是实现Ajax功能的一个工具包,它...
Android Webview虽然提供了页面加载及资源请求的钩子,但是对于h5的ajax请求并没有提供干涉的接口,这意味着我们不能在webview中干涉javascript发起的http请求,而有时候我们确实需要能够截获ajax请求并实现一些功能...
《Professional Ajax, 2nd Edition》是一本深入探讨Ajax技术的专业书籍,由三位作者Nicholas C. Zakas、Jeremy McPeak和Joe Fawcett共同撰写。本书在2007年由Wiley Publishing, Inc.出版,是针对网站开发、设计以及...
《Head Rush Ajax》是一本专为想要深入理解Ajax技术的开发者编写的书籍。Ajax,全称为"Asynchronous JavaScript and XML",并非一种单一的技术,而是一种综合了多种Web开发技术的运用方式,它允许网页在不刷新整个...
**Ajax+JSON 实例详解** 在现代Web开发中,AJAX(Asynchronous JavaScript and XML)技术已经成为提升用户体验的重要工具,它允许网页在不刷新整个页面的情况下与服务器进行数据交互。结合JSON(JavaScript Object ...
**Ajax(Asynchronous JavaScript and XML)技术是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。它通过在后台与服务器进行少量数据交换,使网页实现异步更新。这种技术可以提升用户体验,因为它...
标题中的“php+ajax例子”指的是使用PHP服务器端语言与AJAX(Asynchronous JavaScript and XML)客户端技术结合的示例应用。在Web开发中,PHP通常用于处理服务器端逻辑,而AJAX则允许网页在不刷新整个页面的情况下,...
本书重点介绍Ajax及相关的工具和技术,主要内容包括XMLHttpRequest对象及其属性和方法、发送请求和处理响应、构建完备的Ajax开发工具、使用JsUnit测试JavaScript、分析JavaScript调试工具和技术,以及Ajax开发模式和...
现在Ajax在Web项目中应用广泛,几乎可以说无处不在,这就带来另外一个问题:当Ajax请求遇到Session超时,应该怎么办? 显而易见,传统的页面跳转在此已经不适用,因为Ajax请求是XMLHTTPRequest对象发起的而不
**ASP.NET AJAX 全面解析** ASP.NET AJAX(Asynchronous JavaScript and XML)是微软为.NET Framework提供的一种技术,用于创建富交互式、响应快速的Web应用程序。它将JavaScript库(MicrosoftAjax.js)与服务器端...
2. **事件处理**:库内部监听`ajaxStart`、`ajaxSend`、`ajaxSuccess`、`ajaxError`等事件,提供了对Ajax请求生命周期的控制。开发者可以通过自定义事件处理器来扩展功能或处理错误。 3. **内容替换**:默认情况下...
Struts2与Ajax 的实现原理,于Servlet+Ajax原理是一致的,都是通过后台的response.getWriter().print("");把数据传输给前台的。 前台Ajax格式如下(需要导入ajax库,比如:jquery-1.11.3.js) 格式: $(function()...