1. 程式人生 > >ajax與Servlet

ajax與Servlet

jsp round public 用戶名 gets json格式 list words tco

1.後臺返回text類型的數據

技術分享
<%@ 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> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"
> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type
="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function(){ $("#btn").click(function(){ //獲取用戶的輸入 var name= $("#name").val(); $.ajax({ url:"AjaxServlet", /*對應的是web.xml文件中url 也是我們的請求路徑 */ type:"post", /* 請求的方式 */ data:"name="+name, /* 請求中攜帶的數據 */ dataType:"text", /* 後臺返回的數據類型 */ beforeSend:function(){ alert("請求正在處理。。。。。。"); }, success:function(data){ alert(data); } }); }); }); </script> </head> <body> 用戶名:<input type="text" id="name"> <input type="button" id="btn" value="請求ajax"> </body> </html>
前臺jsp頁面

技術分享
public class AjaxServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("進入了ajax..........");
        response.setHeader("Content-type", "text/html;charset=utf-8");

         // 01.獲取ajax請求過來的name值
        String name = request.getParameter("name");
            response.getWriter().print(name);
        

    }

}
創建對應的servlet

2.返回單個對象

技術分享
public class Student {
    private String name;
    private String pwd;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Student(String name, String pwd) {
        super();
        this.name = name;
        this.pwd = pwd;
    }

    public Student() {
        super();
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", pwd=" + pwd + "]";
    }

}
Student實體類

技術分享
<%@ 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>
<base href="<%=basePath%>">

<title>My JSP ‘index.jsp‘ starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
       $(function(){
          $("#btn").click(function(){
          //獲取用戶的輸入
         var name= $("#name").val();
           $.ajax({   
            url:"AjaxServlet",  /*對應的是web.xml文件中url  也是我們的請求路徑  */
            type:"post", /* 請求的方式 */
            data:"name="+name,  /* 請求中攜帶的數據 */
            dataType:"json",  /* 後臺返回的數據類型  */
            beforeSend:function(){
              alert("請求正在處理。。。。。。");
            },
            success:function(data){
            /* 返回集合 */

            
           //返回單個對象 alert(data);
            $("#myDiv").append("姓名:"+data.name);
            $("#myDiv").append("密碼:"+data.pwd); 
            }
            });
          });
       });
    </script>
    
</head>

<body>


     用戶名:<input  type="text" id="name">
   <input  type="button" id="btn" value="請求ajax">
   <div id="myDiv"></div>
   
</body>
</html>
前臺jsp頁面

技術分享
public class AjaxServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("進入了ajax..........");
        response.setHeader("Content-type", "text/html;charset=utf-8");

        // 創建一個Student對象 返回給前臺
        Student student = new Student("admin1", "123456");
        // 需要把student對象轉換成json格式
        System.out.println("轉換前==》" + student);
        Gson gson = new Gson();
        // json 就是轉換之後的 student對象 {"name":"admin","pwd":"123456"}
        String json = gson.toJson(student);
        System.out.println("轉換後==" + json);
        response.getWriter().print(json);

    }

}
對應的servlet

3.返回對象的集合

技術分享
<%@ 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>
<base href="<%=basePath%>">

<title>My JSP ‘index.jsp‘ starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
       $(function(){
          $("#btn").click(function(){
          //獲取用戶的輸入
         var name= $("#name").val();
           $.ajax({   
            url:"AjaxServlet",  /*對應的是web.xml文件中url  也是我們的請求路徑  */
            type:"post", /* 請求的方式 */
            data:"name="+name,  /* 請求中攜帶的數據 */
            dataType:"json",  /* 後臺返回的數據類型  */
            beforeSend:function(){
              alert("請求正在處理。。。。。。");
            },
            success:function(data){
            /* 返回集合 */
             $("#myDiv").append("<span>姓名</span>&nbsp;&nbsp;&nbsp;");
             $("#myDiv").append("<span>密碼</span></br>"); 
            //遍歷傳遞過來的json數組
            $(data).each(function(i){
            $("#myDiv").append("<span>"+data[i].name+"</span>&nbsp;&nbsp;&nbsp;");
            $("#myDiv").append("<span>"+data[i].pwd+"</span></br>");
            })
            
          
            }
            });
          });
       });
    </script>
    
</head>

<body>


     用戶名:<input  type="text" id="name">
   <input  type="button" id="btn" value="請求ajax">
   <div id="myDiv"></div>
   
</body>
</html>
前臺jsp頁面

技術分享
public class AjaxServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("進入了ajax..........");
        response.setHeader("Content-type", "text/html;charset=utf-8");

        Student student1 = new Student("admin1", "123456");
        Student student2 = new Student("admin2", "123456");
        Student student3 = new Student("admin3", "123456");
        Student student4 = new Student("admin4", "123456");

        ArrayList<Student> list = new ArrayList<Student>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        System.out.println("轉換前==》" + list);
        Gson gson = new Gson();
        String json = gson.toJson(list);
        System.out.println(json);
        response.getWriter().print(json);

    }

}
對應的servlet

ajax與Servlet