Java自学笔记之Ajax案例

前言

在javaweb中,ajax是前后台交互的技术,可以实现异步请求,不用刷新整个页面就可以完成操作。

案例1:用ajax实现登录

1、在myeclipce中创建web项目,目录结构如下,该建包建包,该建类建类,该建jsp建jsp,该导入jquery导入jquery。
这里写图片描述
**2、实现的功能是:在index.jsp 中用户输入id和username,点击登录,传到后台,如果id为110,username为helloworld,那么页面跳转到pages/sussess.jsp中(当然,是用Ajax实现)
3、前台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>
    <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">
    <script type="text/javascript" src="script/jquery-1.4.4.min.js"></script>
    <script type = "text/javascript">

        function login(){
            var id = document.getElementById("id").value;
            var username = document.getElementById("username").value;
            $.ajax({
                type:"post",
                url:"${pageContext.request.contextPath}/LoginServlet",
                data:{"id":id, "username":username},
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                success:function(data){
                            if(data == "0"){
                                alert("您输入的用户名或密码有错!");loginform.username.focus();return false;
                            }else{
                                window.location.href = "${pageContext.request.contextPath}/pages/success.jsp";//跳转
                            }
                        },
                  error:function(arr) {
                        alter("有错误");
                    }


            });
        }
  </script>
  </head>


  <body>

    id:<input id="id" type="text" name="id" /><br>
   username:<input id="username" type="text" name="username" /><br>
   <input  type="submit" value="登录" onclick="login()"/>


  </body>
</html>

4、LoginServlet代码

package com.web.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 LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String flag = "0";
        PrintWriter out = response.getWriter();
        if(id != null && !username.trim().equals("") && username != null){
            if(id.equals("110") && username.equals("helloworld")){
                flag = "1";
                request.getSession().setAttribute("username", username);
                request.getSession().setAttribute("id", id);
            }
        }
        out.print(flag);// 返回登录信息
        out.flush();
        out.close();
    }

}

5、success.jsp 代码(就加了一句${sessionScope.username })

<%@ 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 'success.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">

  </head>

  <body>
    Hello World ${sessionScope.username }
  </body>
</html>

6、效果截图
这里写图片描述
这里写图片描述
这里写图片描述

注:LoginServlet的url-pattern是/LoginServlet

案例2:局部刷新

1、在案例一的基础上,新建了这么几个文件,看下图,没有建的建好
这里写图片描述
**2、实现的功能:在test.jsp 中有一个button,点击button,从后台获取数据,输出到前台的table中。
3、test.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>
    <base href="<%=basePath%>">

    <title>My JSP 'test.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">
    <script type="text/javascript" src="script/jquery-1.4.4.min.js"></script>
    <script type = "text/javascript">
        function showAll(){
            $.ajax({
                type:"post",
                url:"${pageContext.request.contextPath}/ShowServlet",
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                success:function(data){
                    var data = JSON.parse(data);
                    var inner = "<tr><td>id</td><td>username</td></tr>";
                    for(var i = 0; i < data.length; i++){
                        inner += "<tr><td>"+data[i].id+"</td><td>"+data[i].username+"</td></tr>";
                    }
                    $("#content").html(inner);
                },
                error:function(arr) {
                    alert("有错误");
                }


            });

        }

    </script>

  </head>

  <body>
    <button id="showAll" onclick="showAll()">查看</button>
    <table id="content">

    </table>

  </body>
</html>

4、几个java类的代码

package com.domain;

public class User {

    private String id;
    private String username;
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(String id, String username) {
        super();
        this.id = id;
        this.username = username;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + "]";
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

}
package com.common;

import java.util.ArrayList;

import com.domain.User;

public class UserFactory {

    /**
     * 这个方法可以从数据库中提取
     * @return
     */
    public static ArrayList<User> getUsers(){
        ArrayList<User> users = new ArrayList<User>();
        User user = null;
        for (int i = 0; i < 10; i++) {
            user = new User(i+"","user"+i);
            users.add(user);
        }

        return users;
    }
}
package com.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.common.UserFactory;
import com.domain.User;

public class ShowServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ArrayList<User> users = UserFactory.getUsers();
        JSONArray jsonArray2 =JSONArray.fromObject(users);
        PrintWriter out = response.getWriter();
        out.print(jsonArray2);
        out.flush();
        out.close();
    }

}

注1:ShowServlet的url-pattern是/ShowServlet
注2:原理什么的我简单说,Java里面生成的是ArrayList,要把它转化成json格式(我用了JSONArray),需要用几个jar包;相应的,在前台收到后台发送过来的json格式,需要解析(JSON.parse),因为我后台传输的是JSONArray,所以前台解析出来的就是json数组形式,因此循环遍历一下就可以了。
注3:案例2需要的jar包下载地址:http://download.csdn.net/download/tsfx051435adsl/10157423

案例截图:
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/tsfx051435adsl/article/details/78796184