JQuery通過JSON和Servlet進行互動

來源:互聯網
上載者:User

今天接著看Hibernate的視頻,中間休息的時候隨手點了幾個網頁,看到JSON這個東西,心裡琢磨這個東西以前見過,沒用過,這是個啥玩意。

JSON是一種資料交換格式,如同常用的xml,不過在javascript領域中,這個東西可以xml好操作多了。

找了一下相應的例子,有一個ASP.net和前台通過Jquery互動的例子,參考著寫了一個同Servlet互動的例子。把代碼得瑟出來,以供不時之需。

前提:要把jquery的js檔案放到WebRoot的下面的js檔案夾下。

Index.jsp頁面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    function getData(){
        $("#list").html("");//清空列表中的資料
        //發送ajax請求
        $.getJSON(
            "servlet/ServletJson",//產生JSON資料的服務端頁面
            {name:"胡陽",age:23},//向伺服器發出的查詢字串(此參數可選)
             //對返回的JSON資料進行處理,本例以列表的形式呈現
            function(json){
                //迴圈取json中的資料,並呈現在列表中
                $.each(json,function(i){
                    $("#list").append("<li>name:"+json[i].name+"&nbsp; Age:"+json[i].age+"</li>")
                })
            }
        )
        }
    </script>
</head>
<body>
    <input id="Button1" type="button" value="擷取資料" onclick="getData()" />
        <ul id="list"></ul>
    </body>
</html>

配置web.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>ServletJson</servlet-name>
        <servlet-class>com.json.servlet.ServletJson</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>ServletJson</servlet-name>
        <url-pattern>/servlet/ServletJson</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

伺服器端的Servlet編寫:

package com.json.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletJson extends HttpServlet {
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        System.out.println(request.getParameter("name"));
        response.setContentType("text/plain;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String data = "[{name:/"胡陽/",age:24},{name:/"胡陽/",age:23}]";//構建的json資料
        out.println(data);

     }

     public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
         doPost(request, response);
     }
}

這樣就可通過JQuery在web端直接和伺服器端通過JSON進行資料交換了。


原創文章,轉載請註明出處:http://www.the5fire.net/?p=208
本文固定連結:the5fire的技術部落格 | 如果喜歡我的部落格的話可以訂閱本博以便及時收到更新

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.