dwr学习之 二、dwr功能演示
dwr学习 之 一、dwr+spring的简单集成
dwr学习之 二、dwr功能演示
文中代码均已简化。
1. hello world
定义DWRDemo类,并使用注解声明方式。
@Service
@RemoteProxy(name = "DWRDemo")
public class DWRDemo {
private static final Logger LOGGER = LoggerFactory.getLogger(DWRDemo.class);
/**
* 1. 基本调用,参数字符串,返回字符串
*
* @param test
* @return
* @throws Exception
*/
@RemoteMethod
public String sayHello(String test) throws Exception {
LOGGER.info("DWRDemo sayHello, test: " + test);
if (test.equals("error")) {
throw new Exception("出现异常");
}
return "Java: " + test;
}
}
js端首先导入dwr所需的js文件
<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/interface/DWRDemo.js'></script>
<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/engine.js'></script>
<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/util.js'></script>
js调用DWRDemo的sayHello方法:
DWRDemo.sayHello("我是js", function(data){
alert(data);
});
还可以定义超时时间,和错误方法:
DWRDemo.sayHello("error", {
callback: function(data){
alert(data);
},
timeout: 1000,
errorHandler:function(error){
alert(error);
}
});
2. 调用参数为实体类
使用@DataTransferObject(
或dwr:conver t) 声明实体类。
package liming.student.manager.web.model;
import org.directwebremoting.annotations.DataTransferObject;
import org.directwebremoting.io.FileTransfer;
import org.springframework.web.multipart.MultipartFile;
@DataTransferObject
public class StudentForm extends GeneralForm {
private String studentName;
private int studentSex;
private String studentBirthday;
private FileTransfer studentPhoto_dwr;
private String classId;
private String placeId;
}
java方法使用此实体类作参数:
@Service
@RemoteProxy(name = "StudentDWR")
public class StudentDWR {
@RemoteMethod
public boolean addStudent(StudentForm form) {
//代码省略
}
}
js端调用:
var student = {
studentName: $("#studentName").val(),
studentSex: $("#studentSex").val(),
studentBirthday: $("#studentBirthday").val(),
studentPhoto_dwr: dwr.util.getValue("studentPhoto"),
classId: "1",
placeId: "1"
};
StudentDWR.addStudent(student, function(data){
if( data == true ){
alert("dwr新增学生成功!");
window.location = "<%=request.getContextPath()%>/student/list.do";
}else{
alert("dwr新增学生失败!");
}
});
3. 获取实体类或列表
使用@DataTransferObject(
或dwr:conver t) 声明实体类。
@DataTransferObject
public class StudentEntity implements Serializable {
private String studentId;
private String studentName;
private int studentSex;
private Date studentBirthday;
private String photoId;
private String classId;
private String placeId;
}
java方法直接返回此实体类或列表:
@RemoteMethod
public List<StudentEntity> getStudentBaseAllList() {
return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");
}
在js端直接调用此方法后,得到的数据为json格式的object,可以直接调用属性。
StudentDWR.getStudentBaseAllList(function(data){
studentList = data;
for(var i=0; i<data.length; i++){
var studentId = data[i].studentId;
var studentName = data[i].studentName;
var studentSex = data[i].studentSex;
var studentBirthday = data[i].studentBirthday;
var classId = data[i].classId;
var placeId = data[i].placeId;
var photoId = data[i].photoId;
}
});
4. 导入页面
java代码写法:
@RemoteMethod
public String includeHtmlPage(String url) throws ServletException, IOException {
LOGGER.info("DWRDemo includeHtmlPage, url: " + url);
WebContext wctx = WebContextFactory.get();
return wctx.forwardToString(url);
}
js调用:
DWRDemo.includeHtmlPage("/templet/add.jsp", function(data) {
dwr.util.setValue("forward", data, { escapeHtml:false });
});
html中定义一个id为forward的div:
<div id="forward"></div>
5. 上传文件
使用DWR上传文件需要注意的几点:
1. java方法的参数必须是BufferedImage,InputStream,FileTransfer三种中其中一个,一般推荐使用FileTransfer,可以获取文件名、文件类型、和内置的inputStream;
2. js端使用dwr.util.getValue方法获取的obj当参数;
3. 不能与springMVC的上传文件兼容。(不能在spring配置文件中声明org.springframework.web.multipart.commons.CommonsMultipartResolver的bean);
4. web.xml中的filter-mapping的url-pattern尽量不要使用/*,写成具体的,例如:*.do。
下面代码为将上传的文件使用createStringPhoto方法保存到数据库,并且进行缩小并返回。
@RemoteMethod
public BufferedImage uploadPhtoFile(FileTransfer file) {
try {
if (file.getSize() > Integer.MAX_VALUE) {
return null;
}
LOGGER.info("DWRDemo uploadPhtoFile, file: " + file.toString());
InputStream input = file.getInputStream();
byte[] photoData = new byte[(int) file.getSize()];
input.read(photoData);
input.close();
this.studentService.createStringPhoto(photoData, file.getFilename());
BufferedImage image = scaleImageBytesToBufferedImage(photoData, 100, 100);
return image;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static BufferedImage scaleImageBytesToBufferedImage(byte[] data, int width, int height) throws IOException {
BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
int imageOldWidth = buffered_oldImage.getWidth();
int imageOldHeight = buffered_oldImage.getHeight();
double scale_x = (double) width / imageOldWidth;
double scale_y = (double) height / imageOldHeight;
double scale_xy = Math.min(scale_x, scale_y);
int imageNewWidth = (int) (imageOldWidth * scale_xy);
int imageNewHeight = (int) (imageOldHeight * scale_xy);
BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0,
0, null);
buffered_newImage.getGraphics().dispose();
return buffered_newImage;
}
html代码:
<input type="file" id="uploadImage"/>
<input type="button" onclick="uploadFile()" value="dwr上传文件"/>
<img id="image"/>
js代码,使用dwr.util.getValue获取文件对象上传文件,使用dwr.util.setValue方法设置显示图片。
function uploadFile(){
var image = dwr.util.getValue('uploadImage');
DWRDemo.uploadPhtoFile(image, function(data){
if( data != null ){
dwr.util.setValue('image', data);
}
});
}
6. 下载文件
在java方法中,使用字节数组构造出一个FileTransfer对象,并返回。
在js端,将获取到的数据当参数,调用dwr.engine.openInDownload即可。
java代码:
@RemoteMethod
public FileTransfer downloadPhotoFile(String studentId) throws Exception {
LOGGER.info("DWRDemo downloadPhotofFile, studentId: " + studentId);
PhotoEntity photoEntity = this.studentService.getPhotoDataByStudentId(studentId);
if (photoEntity != null && photoEntity.getPhotoData() != null && photoEntity.getPhotoData().length > 0) {
byte[] data = photoEntity.getPhotoData();
String fileName = photoEntity.getFileName();
fileName = fileName == null ? "照片" + studentId + ".png" : fileName;
fileName = URLEncoder.encode(fileName, "UTF-8");
return new FileTransfer(fileName, "application/octet-stream;charset=UTF-8", data);
} else {
return null;
}
}
js代码:
DWRDemo.downloadPhotoFile("10000032", function(data){
if( data != null ){
dwr.engine.openInDownload(data);
}else{
alert("此照片不存在");
}
});
dwr学习 之 一、dwr+spring的简单集成
dwr学习之 二、dwr功能演示
分享到:
相关推荐
DWR(Direct Web Remoting)是一个WEB远程调用框架.利用这个框架可以让AJAX开发变得很简单.利用DWR可以在客户端利用JavaScript直接调用服务端的Java方法并...本次例子只是用于演示,说明DWR的使用,类设计并不是最优的
dwr项目演示案例。 DWR(Direct Web Remoting)是一个用于改善web页面与Java类交互的远程服务器端Ajax开源框架,可以帮助开发人员开发包含AJAX技术的网站。它可以允许在浏览器里的代码使用运行在WEB服务器上的JAVA...
dwr的例子。能够让你轻松了解dwr的使用方法。
springMVC+dwr技术实现消息推送实例,简单实例演示如何用dwr实现后台向前台主动推送消息
本资源演示javascript 调用dwr java 类,希望能抛砖引玉
环境:Window Xp Professional, JDK 1.6, Tomcat 6.0, MyEclipse 5.5 MS SQL Server 2000.... 使用DWR可以方便的使用Spring托管的持久层功能。 目的:希望广大Java程序能够熟练的使用SSHA整合框架来作轻量的项目开发。
DWR js框架 javascript框架 web与java交互 Direct Web Remoting Ajax开源框架 即有java源码又有dwr.jar包 有实现步骤及演示源码
java+dwr框架:dwr框架入门demo,演示用dwrAjax实现List/Map/ Set等常用集合内容展示
34 4.2.4 使用Spring配置DWR 35 4.3 DWR与JSF 36 4.3.1 JSF Creator 36 4.3.2 Servlet Filter 36 4.4 DWR与Struts 37 4.4.1 Struts creator 37 4.4.2 开始顺序 37 4.5 DWR与...
该资源使用了众多的java软件开发项目用到的基本内容,包含jsf,ajax技术,hibernate映射,log4j记录日志和dom4j解析xml以及使用的dwr使用的ajax技术以及基本的ajax应用,数据库使用的是mysql。演示的是用户注册系统,...
一个比较不错的演示程序。
我以一个三级联动下拉框的例子给大家演示dwr是如何实现的。我用到的技术有spring 2.0.5 ,dwr2.0.5,hibernate3.2.3.ga,struts1.2.9,主要涉及到dwr如何调用spring管理的业务方法,以及dwr如何处理返回的数据。
简单的SSH和DWR的整合,该例子中使用注册页面演示框架的整合。我也是初学者,所以代码的成分不高,只是简单的实现了整合。 例子中没有Jar包,需下载我的其它资源SSH+Jar中(因为我现在不能上传大于15M的内容),将其...
一个DWR的消息推送实时聊天功能,可执行的小Demo演示,因为没有去写过多的解释,附带了一个理解DWR的地址在里面,想要更深的了解需要去游览博客
dwr无限极下拉联动(运行6级下拉联动效果演示含说明,数据库数据来源于数据库中 这里为一个视频演示程序,有什么疑问可以留言。 这个视频是一个avi的文件,压缩后不到8M,源文件有500M,需要看看的朋友可以下载。
WEB-2.0-AJAX-DWR 关于WEB 2.0 AJAX DWR的演示源码
网上dwr的例子真是太少了,本例用最简单的例子。 演示一个调用demo
这个demo演示了使用DWR框架配合数据库来做的下拉列表级联。dao层采用了jsp中经典的JDBC封装、单例、属性文件等技术。数据文件可以按照我的entity层里面写的代码创建就可以了。这个文件直接导入你的工程在属性文件中...
war:为tomcat / jetty / etc创建一个干净的解压缩演示war文件 软件包:构建一组输出.zip文件以进行分发 DWR构建系统可以调整为创建包含不同模块的输出(请参见术语),因此创建包含确切所需模块的dwr.jar文件非常...
dwr+spring+hibernate分页演示例子.对dwr框架有兴趣可以参考参考。