目前編碼會有問題

這是很簡易在後端生成一段json並傳送到前端的程式

生成json的方法是使用gson

必須要下載jar檔,因為OOO所以jar檔用拉的到WebContent/WEB-INF/bin下就好了

http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm

  • 目錄

 

  • GsonCreate.java

package tw.com.GsonServlet;

public class GsonCreate {

    private String name;
    private int age;
    
    public GsonCreate(String name, int age) {
        this.name=name;
        this.age=age;
    }
}
 

  • GsonServlet.java

我是使用POST,所以就只貼POST上來

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //生成json
        Gson gson = new Gson();
        GsonCreate test_tojson = new GsonCreate("你好",24);
        String jsonObject = gson.toJson(test_tojson); 
        System.out.println(jsonObject);
                      
        PrintWriter out = response.getWriter();
        out.print(jsonObject);          
        out.close();
            
    }

  • index.jsp

有底色的部分為我加上去的

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>  
       
<script type="text/javascript">        
    function jsonAjaxPost(){     
        $.ajax({  
            type:"post", 
            url:"GsonServlet",   
            dataType:"json",//设置返回数据的格式 ,请求成功后的回调函数 data为json格式  
            success:
                function(data){  
                    $("#resultJsonText").text("name:"+data.name+"  age:"+data.age);  
                },  
            error:
                function(xhr, ajaxOptions, thrownError){
                    alert(xhr.status+"\n"+thrownError);
                }
        });  
    }  
</script>  
</head>
<body>

<input type="button" id="btn" name="btn" value="點我" onclick="jsonAjaxPost()">
<div id="resultJsonText"></div>
</body>
</html>

  • 執行結果

目前在學習中,有任何錯誤請見諒!!=)

 

arrow
arrow

    我的暱稱 發表在 痞客邦 留言(0) 人氣()