1. 程式人生 > >前臺通過JS請求後臺的幾種方法

前臺通過JS請求後臺的幾種方法

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>

後臺對應的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通過改變帶有路徑屬性的元素得路徑
前臺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>

後臺對應的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.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.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>

後臺對應的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.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>

後臺對應的整個類

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);
            }
        }
    }

}