文中代码均已简化。
1. hello world
定义DWRDemo类,并使用注解声明方式。
Java代码
1.@Service
2.@RemoteProxy(name = "DWRDemo")
3.public class DWRDemo {
4.
5. private static final Logger LOGGER = LoggerFactory.getLogger(DWRDemo.class);
6.
7. /**
8. * 1. 基本调用,参数字符串,返回字符串
9. *
10. * @param test
11. * @return
12. * @throws Exception
13. */
14. @RemoteMethod
15. public String sayHello(String test) throws Exception {
16. LOGGER.info("DWRDemo sayHello, test: " + test);
17. if (test.equals("error")) {
18. throw new Exception("出现异常");
19. }
20. return "Java: " + test;
21. }
22.}
@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文件
Html代码
1.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/interface/DWRDemo.js'></script>
2.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/engine.js'></script>
3.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/util.js'></script>
<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方法:
Js代码
1.DWRDemo.sayHello("我是js", function(data){
2. alert(data);
3.});
DWRDemo.sayHello("我是js", function(data){
alert(data);
});
还可以定义超时时间,和错误方法:
Js代码
1.DWRDemo.sayHello("error", {
2. callback: function(data){
3. alert(data);
4. },
5. timeout: 1000,
6. errorHandler:function(error){
7. alert(error);
8. }
9.});
DWRDemo.sayHello("error", {
callback: function(data){
alert(data);
},
timeout: 1000,
errorHandler:function(error){
alert(error);
}
});
2. 调用参数为实体类
使用@DataTransferObject( 或dwr:conver t) 声明实体类。
Java代码
1.package liming.student.manager.web.model;
2.
3.import org.directwebremoting.annotations.DataTransferObject;
4.import org.directwebremoting.io.FileTransfer;
5.import org.springframework.web.multipart.MultipartFile;
6.
7.@DataTransferObject
8.public class StudentForm extends GeneralForm {
9. private String studentName;
10. private int studentSex;
11. private String studentBirthday;
12. private FileTransfer studentPhoto_dwr;
13. private String classId;
14. private String placeId;
15.
16.}
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方法使用此实体类作参数:
Java代码
1.@Service
2.@RemoteProxy(name = "StudentDWR")
3.public class StudentDWR {
4.
5. @RemoteMethod
6. public boolean addStudent(StudentForm form) {
7.
8. //代码省略
9.
10. }
11.}
@Service
@RemoteProxy(name = "StudentDWR")
public class StudentDWR {
@RemoteMethod
public boolean addStudent(StudentForm form) {
//代码省略
}
}
js端调用:
Js代码
1.var student = {
2. studentName: $("#studentName").val(),
3. studentSex: $("#studentSex").val(),
4. studentBirthday: $("#studentBirthday").val(),
5. studentPhoto_dwr: dwr.util.getValue("studentPhoto"),
6. classId: "1",
7. placeId: "1"
8.};
9.StudentDWR.addStudent(student, function(data){
10. if( data == true ){
11. alert("dwr新增学生成功!");
12. window.location = "<%=request.getContextPath()%>/student/list.do";
13. }else{
14. alert("dwr新增学生失败!");
15. }
16.});
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) 声明实体类。
Java代码
1.@DataTransferObject
2.public class StudentEntity implements Serializable {
3. private String studentId;
4. private String studentName;
5. private int studentSex;
6. private Date studentBirthday;
7. private String photoId;
8. private String classId;
9. private String placeId;
10.
11.}
@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方法直接返回此实体类或列表:
Java代码
1.@RemoteMethod
2.public List<StudentEntity> getStudentBaseAllList() {
3. return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");
4.}
@RemoteMethod
public List<StudentEntity> getStudentBaseAllList() {
return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");
}
在js端直接调用此方法后,得到的数据为json格式的object,可以直接调用属性。
Js代码
1.StudentDWR.getStudentBaseAllList(function(data){
2. studentList = data;
3. for(var i=0; i<data.length; i++){
4. var studentId = data[i].studentId;
5. var studentName = data[i].studentName;
6. var studentSex = data[i].studentSex;
7. var studentBirthday = data[i].studentBirthday;
8. var classId = data[i].classId;
9. var placeId = data[i].placeId;
10. var photoId = data[i].photoId;
11. }
12.});
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代码写法:
Java代码
1.@RemoteMethod
2.public String includeHtmlPage(String url) throws ServletException, IOException {
3. LOGGER.info("DWRDemo includeHtmlPage, url: " + url);
4. WebContext wctx = WebContextFactory.get();
5. return wctx.forwardToString(url);
6.}
@RemoteMethod
public String includeHtmlPage(String url) throws ServletException, IOException {
LOGGER.info("DWRDemo includeHtmlPage, url: " + url);
WebContext wctx = WebContextFactory.get();
return wctx.forwardToString(url);
}
js调用:
Js代码
1.DWRDemo.includeHtmlPage("/templet/add.jsp", function(data) {
2. dwr.util.setValue("forward", data, { escapeHtml:false });
3.});
DWRDemo.includeHtmlPage("/templet/add.jsp", function(data) {
dwr.util.setValue("forward", data, { escapeHtml:false });
});
html中定义一个id为forward的div:
Html代码
1.<div 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方法保存到数据库,并且进行缩小并返回。
Java代码
1.@RemoteMethod
2.public BufferedImage uploadPhtoFile(FileTransfer file) {
3. try {
4. if (file.getSize() > Integer.MAX_VALUE) {
5. return null;
6. }
7. LOGGER.info("DWRDemo uploadPhtoFile, file: " + file.toString());
8. InputStream input = file.getInputStream();
9. byte[] photoData = new byte[(int) file.getSize()];
10. input.read(photoData);
11. input.close();
12. this.studentService.createStringPhoto(photoData, file.getFilename());
13. BufferedImage image = scaleImageBytesToBufferedImage(photoData, 100, 100);
14. return image;
15. } catch (Exception e) {
16. e.printStackTrace();
17. }
18. return null;
19.}
20.
21.public static BufferedImage scaleImageBytesToBufferedImage(byte[] data, int width, int height) throws IOException {
22. BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
23. int imageOldWidth = buffered_oldImage.getWidth();
24. int imageOldHeight = buffered_oldImage.getHeight();
25. double scale_x = (double) width / imageOldWidth;
26. double scale_y = (double) height / imageOldHeight;
27. double scale_xy = Math.min(scale_x, scale_y);
28. int imageNewWidth = (int) (imageOldWidth * scale_xy);
29. int imageNewHeight = (int) (imageOldHeight * scale_xy);
30. BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
31. buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0,
32. 0, null);
33. buffered_newImage.getGraphics().dispose();
34. return buffered_newImage;
35.}
@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代码:
Html代码
1.<input type="file" id="uploadImage"/>
2.<input type="button" onclick="uploadFile()" value="dwr上传文件"/>
3.<img id="image"/>
<input type="file" id="uploadImage"/>
<input type="button" onclick="uploadFile()" value="dwr上传文件"/>
<img id="image"/>
js代码,使用dwr.util.getValue获取文件对象上传文件,使用dwr.util.setValue方法设置显示图片。
Js代码
1.function uploadFile(){
2. var image = dwr.util.getValue('uploadImage');
3. DWRDemo.uploadPhtoFile(image, function(data){
4. if( data != null ){
5. dwr.util.setValue('image', data);
6. }
7. });
8.}
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代码:
Java代码
1.@RemoteMethod
2.public FileTransfer downloadPhotoFile(String studentId) throws Exception {
3. LOGGER.info("DWRDemo downloadPhotofFile, studentId: " + studentId);
4. PhotoEntity photoEntity = this.studentService.getPhotoDataByStudentId(studentId);
5. if (photoEntity != null && photoEntity.getPhotoData() != null && photoEntity.getPhotoData().length > 0) {
6. byte[] data = photoEntity.getPhotoData();
7. String fileName = photoEntity.getFileName();
8. fileName = fileName == null ? "照片" + studentId + ".png" : fileName;
9. fileName = URLEncoder.encode(fileName, "UTF-8");
10. return new FileTransfer(fileName, "application/octet-stream;charset=UTF-8", data);
11. } else {
12. return null;
13. }
14.}
@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代码:
Js代码
1.DWRDemo.downloadPhotoFile("10000032", function(data){
2. if( data != null ){
3. dwr.engine.openInDownload(data);
4. }else{
5. alert("此照片不存在");
6. }
7.});
原文 :http://limingnihao.iteye.com/blog/1074204
1. hello world
定义DWRDemo类,并使用注解声明方式。
Java代码
1.@Service
2.@RemoteProxy(name = "DWRDemo")
3.public class DWRDemo {
4.
5. private static final Logger LOGGER = LoggerFactory.getLogger(DWRDemo.class);
6.
7. /**
8. * 1. 基本调用,参数字符串,返回字符串
9. *
10. * @param test
11. * @return
12. * @throws Exception
13. */
14. @RemoteMethod
15. public String sayHello(String test) throws Exception {
16. LOGGER.info("DWRDemo sayHello, test: " + test);
17. if (test.equals("error")) {
18. throw new Exception("出现异常");
19. }
20. return "Java: " + test;
21. }
22.}
@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文件
Html代码
1.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/interface/DWRDemo.js'></script>
2.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/engine.js'></script>
3.<script type='text/javascript' src='<%=request.getContextPath() %>/dwr/util.js'></script>
<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方法:
Js代码
1.DWRDemo.sayHello("我是js", function(data){
2. alert(data);
3.});
DWRDemo.sayHello("我是js", function(data){
alert(data);
});
还可以定义超时时间,和错误方法:
Js代码
1.DWRDemo.sayHello("error", {
2. callback: function(data){
3. alert(data);
4. },
5. timeout: 1000,
6. errorHandler:function(error){
7. alert(error);
8. }
9.});
DWRDemo.sayHello("error", {
callback: function(data){
alert(data);
},
timeout: 1000,
errorHandler:function(error){
alert(error);
}
});
2. 调用参数为实体类
使用@DataTransferObject( 或dwr:conver t) 声明实体类。
Java代码
1.package liming.student.manager.web.model;
2.
3.import org.directwebremoting.annotations.DataTransferObject;
4.import org.directwebremoting.io.FileTransfer;
5.import org.springframework.web.multipart.MultipartFile;
6.
7.@DataTransferObject
8.public class StudentForm extends GeneralForm {
9. private String studentName;
10. private int studentSex;
11. private String studentBirthday;
12. private FileTransfer studentPhoto_dwr;
13. private String classId;
14. private String placeId;
15.
16.}
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方法使用此实体类作参数:
Java代码
1.@Service
2.@RemoteProxy(name = "StudentDWR")
3.public class StudentDWR {
4.
5. @RemoteMethod
6. public boolean addStudent(StudentForm form) {
7.
8. //代码省略
9.
10. }
11.}
@Service
@RemoteProxy(name = "StudentDWR")
public class StudentDWR {
@RemoteMethod
public boolean addStudent(StudentForm form) {
//代码省略
}
}
js端调用:
Js代码
1.var student = {
2. studentName: $("#studentName").val(),
3. studentSex: $("#studentSex").val(),
4. studentBirthday: $("#studentBirthday").val(),
5. studentPhoto_dwr: dwr.util.getValue("studentPhoto"),
6. classId: "1",
7. placeId: "1"
8.};
9.StudentDWR.addStudent(student, function(data){
10. if( data == true ){
11. alert("dwr新增学生成功!");
12. window.location = "<%=request.getContextPath()%>/student/list.do";
13. }else{
14. alert("dwr新增学生失败!");
15. }
16.});
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) 声明实体类。
Java代码
1.@DataTransferObject
2.public class StudentEntity implements Serializable {
3. private String studentId;
4. private String studentName;
5. private int studentSex;
6. private Date studentBirthday;
7. private String photoId;
8. private String classId;
9. private String placeId;
10.
11.}
@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方法直接返回此实体类或列表:
Java代码
1.@RemoteMethod
2.public List<StudentEntity> getStudentBaseAllList() {
3. return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");
4.}
@RemoteMethod
public List<StudentEntity> getStudentBaseAllList() {
return this.studentService.getStudentBaseAllList(0, StudentForm.DEFAULT_PAGE_SEZE, "");
}
在js端直接调用此方法后,得到的数据为json格式的object,可以直接调用属性。
Js代码
1.StudentDWR.getStudentBaseAllList(function(data){
2. studentList = data;
3. for(var i=0; i<data.length; i++){
4. var studentId = data[i].studentId;
5. var studentName = data[i].studentName;
6. var studentSex = data[i].studentSex;
7. var studentBirthday = data[i].studentBirthday;
8. var classId = data[i].classId;
9. var placeId = data[i].placeId;
10. var photoId = data[i].photoId;
11. }
12.});
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代码写法:
Java代码
1.@RemoteMethod
2.public String includeHtmlPage(String url) throws ServletException, IOException {
3. LOGGER.info("DWRDemo includeHtmlPage, url: " + url);
4. WebContext wctx = WebContextFactory.get();
5. return wctx.forwardToString(url);
6.}
@RemoteMethod
public String includeHtmlPage(String url) throws ServletException, IOException {
LOGGER.info("DWRDemo includeHtmlPage, url: " + url);
WebContext wctx = WebContextFactory.get();
return wctx.forwardToString(url);
}
js调用:
Js代码
1.DWRDemo.includeHtmlPage("/templet/add.jsp", function(data) {
2. dwr.util.setValue("forward", data, { escapeHtml:false });
3.});
DWRDemo.includeHtmlPage("/templet/add.jsp", function(data) {
dwr.util.setValue("forward", data, { escapeHtml:false });
});
html中定义一个id为forward的div:
Html代码
1.<div 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方法保存到数据库,并且进行缩小并返回。
Java代码
1.@RemoteMethod
2.public BufferedImage uploadPhtoFile(FileTransfer file) {
3. try {
4. if (file.getSize() > Integer.MAX_VALUE) {
5. return null;
6. }
7. LOGGER.info("DWRDemo uploadPhtoFile, file: " + file.toString());
8. InputStream input = file.getInputStream();
9. byte[] photoData = new byte[(int) file.getSize()];
10. input.read(photoData);
11. input.close();
12. this.studentService.createStringPhoto(photoData, file.getFilename());
13. BufferedImage image = scaleImageBytesToBufferedImage(photoData, 100, 100);
14. return image;
15. } catch (Exception e) {
16. e.printStackTrace();
17. }
18. return null;
19.}
20.
21.public static BufferedImage scaleImageBytesToBufferedImage(byte[] data, int width, int height) throws IOException {
22. BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
23. int imageOldWidth = buffered_oldImage.getWidth();
24. int imageOldHeight = buffered_oldImage.getHeight();
25. double scale_x = (double) width / imageOldWidth;
26. double scale_y = (double) height / imageOldHeight;
27. double scale_xy = Math.min(scale_x, scale_y);
28. int imageNewWidth = (int) (imageOldWidth * scale_xy);
29. int imageNewHeight = (int) (imageOldHeight * scale_xy);
30. BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
31. buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0,
32. 0, null);
33. buffered_newImage.getGraphics().dispose();
34. return buffered_newImage;
35.}
@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代码:
Html代码
1.<input type="file" id="uploadImage"/>
2.<input type="button" onclick="uploadFile()" value="dwr上传文件"/>
3.<img id="image"/>
<input type="file" id="uploadImage"/>
<input type="button" onclick="uploadFile()" value="dwr上传文件"/>
<img id="image"/>
js代码,使用dwr.util.getValue获取文件对象上传文件,使用dwr.util.setValue方法设置显示图片。
Js代码
1.function uploadFile(){
2. var image = dwr.util.getValue('uploadImage');
3. DWRDemo.uploadPhtoFile(image, function(data){
4. if( data != null ){
5. dwr.util.setValue('image', data);
6. }
7. });
8.}
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代码:
Java代码
1.@RemoteMethod
2.public FileTransfer downloadPhotoFile(String studentId) throws Exception {
3. LOGGER.info("DWRDemo downloadPhotofFile, studentId: " + studentId);
4. PhotoEntity photoEntity = this.studentService.getPhotoDataByStudentId(studentId);
5. if (photoEntity != null && photoEntity.getPhotoData() != null && photoEntity.getPhotoData().length > 0) {
6. byte[] data = photoEntity.getPhotoData();
7. String fileName = photoEntity.getFileName();
8. fileName = fileName == null ? "照片" + studentId + ".png" : fileName;
9. fileName = URLEncoder.encode(fileName, "UTF-8");
10. return new FileTransfer(fileName, "application/octet-stream;charset=UTF-8", data);
11. } else {
12. return null;
13. }
14.}
@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代码:
Js代码
1.DWRDemo.downloadPhotoFile("10000032", function(data){
2. if( data != null ){
3. dwr.engine.openInDownload(data);
4. }else{
5. alert("此照片不存在");
6. }
7.});
原文 :http://limingnihao.iteye.com/blog/1074204
- liming.dwr.example.rar (1.1 MB)
- 下载次数: 7
发表评论
-
[转载]WebUtils
2013-03-19 21:20 853http://blog.sina.com.cn/s/blog_ ... -
配置整合DWR3.0和Spring2.5使用annotation注解
2013-02-25 09:11 1002这里使用 DWR3.rc1, Spring2.5 and Sp ... -
dwr学习 之 一、dwr+spring的简单集成
2013-02-25 09:10 747dwr学习 之 一、dwr+spring的简单集成 转自:ht ... -
Spring3.0的任务调度<转>
2013-02-23 12:34 1034Spring Security 3.0系列开发出来的时间并不长 ... -
spring集成log4j .
2013-02-20 10:16 11021、 log4j.properties文件 1)文件位置:在 ... -
在servlet中注入spring容器中的bean(转)
2013-01-29 14:49 1191在servlet中注入spring容器中的bean 在使用s ... -
控制台WARN No appenders could be found for logger
2013-01-17 15:36 1180错误:tomcat里的shutdown.bat无法关闭启动的d ...
相关推荐
DWR开发培训.ppt、DWR.ppt:这些可能是DWR的培训演示文稿,包含了一系列主题的讲解,可能涵盖了DWR的工作原理、核心组件、使用示例和最佳实践。通过这些PPT,你可以系统地学习DWR,并通过实例加深理解。 DWR与界面...
首先,"DWR学习笔记"提供了对DWR基础概念、核心功能以及实际应用的概述。这些笔记可能包含了DWR的基本架构,如它如何通过AJAX技术实现实时的Web交互,以及如何创建和调用服务器端的Java方法。 "DWR中文API"是DWR库...
`dwrdemo`可能是一个完整的DWR演示项目,包含运行示例的源代码。`dwr需要用的jar`是DWR运行所需的库文件。`Ajax无刷新页的业务逻辑实现`可能探讨了如何在不刷新页面的情况下实现复杂的业务逻辑。`ajaxReg(解决中文...
1. **DWR简介**:DWR的核心功能是通过AJAX技术实现浏览器与服务器之间的双向通信。它提供了一种简单的方式来执行异步请求,使得前端JavaScript代码可以调用后台Java方法,仿佛它们是在同一进程中运行一样。 2. **...
视频解说部分应该会详细演示如何配置DWR与框架的整合,包括在web.xml中的DWR配置,创建并注册Remote Classes,以及在前端JavaScript中如何调用这些远程方法。 `DWR小例子.avi`可能是一个视频教程,展示了具体的DWR...
通过这个简单的DWR演示项目,你可以深入理解DWR的工作原理,掌握如何配置DWR、编写可被客户端调用的Java方法,以及如何在JavaScript中使用这些方法。这对于想要学习和使用DWR来构建动态Web应用的初学者来说是一个很...
9. **实战项目**:“[浪曦原创]零散视频三 使用DWR开发AJAX For J2EE(JustCode).wrf”可能是一个实际操作视频,详细演示如何使用DWR构建一个简单的AJAX应用,通过观看可以加深对上述理论知识的理解。 10. **资源...
- **Hello, World**:一个简单的示例,演示如何通过DWR调用服务器上的"hello"方法并在浏览器中显示结果。 - **动态数据更新**:可能是一个实时数据显示的例子,例如,服务器端定期更新数据库中的数据,前端通过DWR...
3. **dwr.ppt** - 这可能是一个PPT演示文稿,可能包含了DWR的基础概念、工作原理、配置教程以及一些示例,有助于快速理解DWR的使用。 4. **dwr** - 这可能是DWR的源码或者示例项目的文件夹,用户可以通过查看这些...
DWR2是DWR的第二个主要版本,提供了许多改进和新特性,使得开发人员能够更轻松地构建动态、交互性强的Web应用。 在这个"DWR2相关资料"的压缩包中,我们可能找到了一个完整的DWR2演示项目,这个项目是为在MyEclipse...
这个例子“dwr例子演示级联菜单”旨在帮助我们理解如何使用DWR来创建动态的、交互式的级联下拉菜单。级联菜单常用于Web应用程序中,例如在选择国家时自动更新相应的省份列表。 首先,让我们了解一下DWR的基本工作...
2. **环境搭建**:演示如何配置开发环境,包括服务器、浏览器支持和DWR库的添加。 3. **基本使用**:通过实例展示如何创建可调用的Java对象和方法,以及JavaScript端的调用语法。 4. **高级特性**:涵盖批量调用、...
3. **实例演示**:提供一个或多个实际应用案例,展示如何使用DWR构建Ajax功能。 4. **最佳实践**:分享一些在开发过程中应该遵循的准则,以提高代码质量和可维护性。 5. **常见问题与解决方案**:列举开发过程中可能...
#### 二、DWR入门案例详解 ##### 2.1 HelloWorld示例 **目的**:通过一个简单的“Hello World”示例来了解DWR的基本使用流程。 **步骤**: 1. **准备环境**:确保已安装Java开发环境,并且服务器支持运行Java ...
DWR使得JavaScript能够调用服务器端的Java方法,就像它们是本地函数一样,这样就可以在不刷新整个页面的情况下更新部分网页内容,从而实现即时提醒功能。 反向AJAX是相对于传统AJAX(用户发起请求,服务器响应)的...
在`dwr_demo_test`中,可能演示了如何使用DWR实现一个简单的交互功能,如动态加载数据、实时验证用户输入等。 6. **DWR的优点**: - **易用性**:DWR的API设计简洁,易于理解和使用。 - **性能**:由于减少了HTTP...
Direct Web Remoting (DWR) 是一个开源Java库,它允许在浏览器和服务器之间进行实时、安全的双向通信,使得JavaScript可以直接调用Java方法,从而实现Web应用的Ajax功能。这个"TestDWR"文件很可能是DWR的一个简单...
**DWR (Direct Web ...通过这个"可以直接运行的eclipse工程",开发者不仅可以学习DWR的基本用法,还能了解如何在实际开发环境中配置和调试DWR应用。这对于初学者理解DWR的工作原理和提升Web开发技能非常有帮助。
在我们的例子中,"HelloDWR"可能是DWR的一个简单示例,用于演示如何设置和使用DWR的基本功能。这个示例通常包括以下步骤: 1. 创建一个简单的Java类,如`HelloWorld.java`,其中有一个返回字符串的方法。 2. 在`dwr....