当前位置: 移动技术网 > IT编程>网页制作>CSS > Ajax框架之DWR学习(异常处理案例、Bean传递参数、多个Service)

Ajax框架之DWR学习(异常处理案例、Bean传递参数、多个Service)

2017年12月27日  | 移动技术网IT编程  | 我要评论

Ajax框架之DWR学习(异常处理案例、Bean传递参数、多个Service)。

1、在DWR中处理异常的方式,2、多个Dwr的service调用,3、通过Bean来传递参数

这里写图片描述

项目结构

这里写图片描述

环境搭建 pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>yellowcong</groupId>
    <artifactId>day11_29</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>day11_29 Maven Webapp</name>
    <url>https://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <!-- Dwr框架 -->
        <dependency>
            <groupId>org.directwebremoting</groupId>
            <artifactId>dwr</artifactId>
            <version>3.0.2-RELEASE</version>
        </dependency>

        <!-- 必须也连带加上这个日志包,不然报错 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.0.4</version>
        </dependency>
        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>day11_29</finalName>
    </build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>day1_27_dwr</display-name>
    <!-- a)配置DwrListener 监听器-->
    <listener>
        <listener-class>org.directwebremoting.servlet.DwrListener</listener-class>
    </listener>

    <!-- b)配置DwrServlet  -->
    <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>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp/" target="_blank">jsp</welcome-file>
    </welcome-file-list>
</web-app>
dwr.xml

配置多个dwr的Service,同时添加Service的错误处理

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "https://getahead.org/dwr/dwr30.dtd">

<dwr>
  <allow>
    <!-- 用户操作的Service -->
    <create creator="new" >
        <!-- 公布我们的 Java/" target="_blank">Java 文件 -->
        <param name="class" value="com.yellowcong.service.UserService" />
        <exclude method="sayHello"/>
        <exclude method="load"/>

        <!-- 只可以访问 load方法, 其中 javascript 是我们在 js中调用的那个, 如果 配置了 include 和 exclude -->
        <!-- 
        <include method="sayHello"/>
         -->
        <!-- 除了load 方法,其他方法都可以用 -->
        <exclude method="sayHello"/>
    </create>

    <!-- UploadService  -->
    <create creator="new" >
        <param name="class" value="com.yellowcong.service.UploadService" /> 
    </create>

    <!-- 创建 bean,通过bean来传值 -->
    <convert converter="bean" match="com.yellowcong.entity.User" />

    <!-- 配置错误处理, 添加这两个类就可以了 -->
    <convert converter="exception" match="java.lang.Exception" />
    <convert converter="bean" match="java.lang.StackTraceElement"/>
  </allow>
</dwr>
Service

用户的服务

package com.yellowcong.service;

import com.yellowcong.entity.User;

public class UserService {

    public String sayHello(String name){
        System.out.println(name);

        /*Browser.withPage("", new Runnable() {

            public void run() {
                // TODO Auto-generated method stub

            }
        });*/
        return  "你好"+name;
    }

    public String addUser(User user){
        System.out.println(user.getAge());
        System.out.println(user.getUsername());

        String username = user.getUsername();
        if(username == null || "".equals(username == null)){
            throw new RuntimeException("用户名不为空");
        }
        return "添加成功";
    }
}

下一个是文件上传的service

package com.yellowcong.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

public class UploadService {

    /**
     * 这个导入的是InputStream 的方法,而不是通过 File
     * 
     * @param in
     *            输入流
     * @param filename
     *            文件名称
     * @return
     * @throws IOException
     */
    public String upload(InputStream in, String filename) throws IOException {

        // 对于 服务器,我们需要通过ServletContext 获取我们的绝对路径 ,存储在可操作的文件夹中
        //这个对象是DWR给我们封装的
        WebContext context = WebContextFactory.get();

        //获取文件路径
        String path =context.getServletContext().getRealPath("/resources/");

        //新建文件
        File outFile = new File(path+File.separator+filename);
        System.out.println(outFile.getAbsolutePath());
        //当文件夹不存在的情况新建
        if(!outFile.getParentFile().exists()){
            outFile.getParentFile().mkdirs();
        }
        //写文件
        FileUtils.copyInputStreamToFile(in, outFile);
        return outFile.getAbsolutePath();
    }
}
Entity
package com.yellowcong.entity;

public class User {

    private String username;
    private Integer age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
界面

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/UserService.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/UploadService.js"></script>

<!-- 调用我们的JAVA代码 -->
<script type="text/javascript">
    function addUser(age,username){
        var user ={age:age,username:username};
        UserService.addUser(user,{
            callback:function(data){
                alert("处理结果\t"+data);
            },
            errorHandler:function(message,error){
                //相当于一个Map 中获取key 和 value  
                for(var key in error){
                    alert(key+"__"+error[key]);
                }
            }
        }); 
    }


    function uploadFile(){
        var file = document.getElementById("file_upload");
        var names = file.value.split("\\");

        var fileName = names[names.length-1];
        UploadService.upload(file,fileName,function(data){
            alert("文件路径\t"+data);
        }); 
    }
</script>
</head>
<body>
<h2>异常处理</h2>
<input type="button" value="正常数据" onclick="addUser('21','yellowcong')" />
<input type="button" value="异常数据" onclick="addUser()" />

<h2>文件上传</h2>
<input type="file" id="file_upload"><input type="button" value="上传" onclick="uploadFile()" />

</body>
</html>
文件上传效果

这里写图片描述

异常处理

这里写图片描述

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网