前台通过JS请求后台的几种方法

25 篇文章 3 订阅
18 篇文章 0 订阅

1.1通过设置form action的路径请求后台方法 
在Structs框架下的一个上传文件的例子,前台html页面部分代码:

<form action="Test!UploadFile.action" enctype="multipart/form-data" method="post">
            用户名:<input type="text" name="username" >
            文件名:<input type="file" name="myFile">
        <input type="submit" value="提交" class="file" />
</form>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

后台对应的Java函数

// myFileFileName属性用来封装上传文件的文件名
public String myFileFileName;
// myFileContentType属性用来封装上传文件的类型
public String myFileContentType;
// myFile属性用来封装上传的文件
public File myFile;
public void UploadFile() throws IOException{
    //基于myFile创建一个文件输入流
    InputStream is = new FileInputStream(myFile);
    // 设置上传文件目录
    String uploadPath = ServletActionContext.getServletContext().getRealPath("/Upload");
    File tmpFile = new File(uploadPath);
    if (!tmpFile.exists()) {
        //创建临时目录
        tmpFile.mkdir();
    }
    File toFile = new File(uploadPath, myFileFileName);
    // 创建一个输出流
    OutputStream os = new FileOutputStream(toFile);
    //设置缓存
    byte[] buffer = new byte[1024];
    int length = 0;
    //读取myFile文件输出到toFile文件中
    while ((length = is.read(buffer)) > 0) {
        os.write(buffer, 0, length);
    }
    //关闭输入流
    is.close();
    //关闭输出流
    os.close();
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

1.2通过改变带有路径属性的元素得路径 
前台html页面部分代码:

<img id="imgCode" src="toCode" onclick="ChangeCode()" style="padding-top:8px"/>
<script type="text/javascript">         
    function ChangeCode()
    {
        var img = document.getElementById("imgCode");
        img.src = 'Test!getCode.action?time='+new Date().getTime();
    }
</script>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

后台对应的java方法

//生成验证码
private static Font VALIDATECODE_FONT = new Font("Times New Roman ",Font.PLAIN, 21);
public void getCode() {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 在内存中创建图象
        BufferedImage image = new BufferedImage(80, 30,BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 设定背景色
        g.setColor(Color.white);
        g.fillRect(0, 0, 80, 30);
        // 画边框
        g.setColor(Color.blue);
        g.drawRect(0, 0, 80 - 1, 30 - 1);
        Long validate = new Long(10000 + Math.round((Math.random() * 90000)));
        String validateCode = validate.toString();
        // 将认证码显示到图象中
        g.setColor(Color.black);
        g.setFont(VALIDATECODE_FONT);
        g.drawString(validateCode.toString(), 10, 22);
        // 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
        Random random = new Random();
        for (int iIndex = 0; iIndex < 100; iIndex++) {
            int x = random.nextInt(80);
            int y = random.nextInt(30);
            g.drawLine(x, y, x, y);
        }
        // 图象生效
        g.dispose();
        try {
            // 输出图象到页面
            ServletOutputStream sos = response.getOutputStream();
            ImageIO.write(image, "jpeg", sos);
            sos.close();
        } catch (Exception e) {
        }
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

1.3使用Ajax(异步JavaScript和XML)请求后台方法 
前台html页面部分代码:

$.ajax({
        async : false,
        cache : false,
        timeout: 1000,
        url: 'Test!sendDate.action?time='+new Date().getTime(), 
        type: "post",
        data:{"username":"1","userpass":2,"validate":3},
        success: function(data){

        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);  
        }
    });     
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

1.4使用Service sent Event 
前台html页面部分代码:

<div align="center">
<table>
    <tr>
        <td><input type="button" value="Server" onclick="ServerSent()"></td>
        <td><input id="ConnectInfor" type="text" value="服务器推送事件"></td>
        <td><input id="pushData" type="text" value="服务器推送事件"></td>
        <td><input id="errorData" type="text" value="服务器推送事件"></td>
    </tr>
</table>
</div>
<script type="text/javascript">
function ServerSent() {
        if (typeof (EventSource) !== "undefined") {
            try{
                var source = new EventSource("Test_SSE!ServicePush.action");
                source.onopen = function(event) {
                    document.getElementById("ConnectInfor").value = "链接成功"+this.readyState; 
                };
                source.onmessage = function(event) {
                    document.getElementById("pushData").value = event.data+"/"+this.readyState;
                };
                source.onerror = function(event) {
                    document.getElementById("errorData").value = "发生错误"+this.readyState;
                }
            }catch(err){
                alert('出错啦,错误信息:'+err.message);
            }   

        } else {
            document.getElementById("ConnectInfor").innerHTML = "抱歉,你的浏览器不支持 server-sent 事件...";
        }
    }
</script>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

后台对应的java方法

public void ServicePush(){
    long str = System.currentTimeMillis();
    backMessage(str+"");
}
public void backMessage(String str){
        try {
            response.setContentType("text/event-stream");   
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write("data: "+ str +"\n\n");
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

1.5使用WebSocket

前台对应html部分代码:

<div align="center">
        <table>
            <tr>
                <td><input type="button" value="退出"
                    onclick="Chat.socket.onclose()"></td>
                <td><input type="button" value="连接"
                    onclick="Chat.socket.onopen()"></td>
                <td><input type="button" value="WebSocket"
                    onclick="Chat.socket.sendMessage()"></td>
                <td><input id="chat" type="text" value="服务器推送事件"></td>
            </tr>
        </table>
        <div id="console"></div>
    </div>
<script type="text/javascript">
//websocket
    var Chat = {};
    Chat.socket = null;
    Chat.connect = (function(host) {
        if ('WebSocket' in window) {
            Chat.socket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            Chat.socket = new MozWebSocket(host);
        } else {
            Console.log('错误:您的浏览器不支持WebSocket');
            return;
        }

        Chat.socket.onopen = function() {
            Console.log('提示: 您已经进入了聊天室');
            document.getElementById('chat').onkeydown = function(event) {
                if (event.keyCode == 13) {
                    Chat.sendMessage();
                }
            };
        };

        Chat.socket.onclose = function() {
            document.getElementById('chat').onkeydown = null;
            Console.log('提示: 您退出了聊天室');
        };

        Chat.socket.onmessage = function(message) {
            Console.log(message.data);
        };

    });

    Chat.initialize = function() {

        if (window.location.protocol == 'http:') {
            Chat.connect('ws://localhost:8080/ShowDate/WebSocket');
        } else {
            Chat.connect('ws://localhost:8080/ShowDate/WebSocket');
        }

    };

    Chat.sendMessage = (function() {
        var message = document.getElementById('chat').value;
        if (message != '') {
            Chat.socket.send(message);
            document.getElementById('chat').value = '';
        }
    });

    var Console = {};

    Console.log = (function(message) {
        var console = document.getElementById('console');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.innerHTML = message;
        console.appendChild(p);
        while (console.childNodes.length > 25) {
            console.removeChild(console.firstChild);
        }
        console.scrollTop = console.scrollHeight;
    });

    Chat.initialize();
</script>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82

后台对应的整个类

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/WebSocket")
public class WebSocket {
    private static final String GUEST_PREFIX = "用户";
    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<WebSocket> connections = new CopyOnWriteArraySet<>();
    private final String nickname;
    private Session session;

    public WebSocket() {
        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
    }

    @OnOpen
    public void start(Session session) {
        this.session = session;
        connections.add(this);
        String message = String.format("%s %s", nickname, "加入了聊天室");
        broadcast(message);
    }

    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("%s %s", nickname, "已经断开连接");
        broadcast(message);
    }

    @OnMessage
    public void incoming(String message) {
        broadcast(message);
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        System.out.println("聊天错误: " + t.toString());
    }

    private static void broadcast(String msg) {
        for (WebSocket client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                System.out.println("聊天错误: 未能发送消息到客户端");
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {

                }
                String message = String.format("%s %s", client.nickname,
                        "已经断开连接");
                broadcast(message);
            }
        }
    }

} 总结:目前js请求后台数据的几种方式有1.form表单提交2.ajax请求3.jsonp请求4.EventSource(HTML5 服务器发送事件(server-sent event)允许网页获得来自服务器的更新。)5.WebSocket(HTML5一种新的协议,浏览器与服务器全双工通信)

6.iframe的postMessage(貌似然并卵)

其中jsonp和WebSocket支持跨域,form表单可以跨域提交,但是得不到返回值。ajax不支持跨域。EventSource似乎也支持跨域

后续或许会不断补充方法

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值