码迷,mamicode.com
首页 > Web开发 > 详细

ajax与Servlet

时间:2017-06-29 12:00:54      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:des   return   ...   lin   hid   json格式   姓名   each   string   

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

标签:des   return   ...   lin   hid   json格式   姓名   each   string   

原文地址:http://www.cnblogs.com/xtdxs/p/7093639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!