ajax与servlet交互(通过JSON),JAVA的arraylist传到前端的方法

所实现的效果:首先从前端(ajax)传参数给servlet,然后servlet经过处理,把arraylist类型的参数以JSON字符串的形式返回给前端(ajax),然后前端经过解析,把JSON字符串解析为JS数组。

直接上代码吧。

1.JSP代码(test.jsp),需要下载jQuery,下载地址,把jQuery路径也修改一下:

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



    test page

    
    
        
    
    
    
        
        



    
UserName: PassWord:
2.javabean代码(User.java):

package com.test;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
3.servlet代码(TestServlet.java),需要GSON.jar, 下载地址,并放在项目的WEB-INF/lib下面:

package com.test;
import java.io.IOException;
import java.io.PrintWriter;

import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

import com.test.User;
//import com.beans.AerialPhotographBean;
import com.google.gson.Gson;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {

    public TestServlet() {
        super();
    }

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

        doPost(request, response);
    }

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String username=request.getParameter("username");
        String password=request.getParameter("password");

        System.out.println("UserName:"+username+";"+"PassWord:"+password);

        Gson gson=new Gson();
        ArrayList arraylistUsers = new ArrayList();
        User user1=new User();
        user1.setUsername(username);
        user1.setPassword(password);
        
        User user2=new User();
        user2.setUsername(username);
        user2.setPassword(password);
        
        arraylistUsers.add(user1);
        arraylistUsers.add(user2);


        
        String info=gson.toJson(arraylistUsers);
        System.out.println(info);
        
        out.write(info);
//        out.print("success");
//        out.flush();
//        out.close();
    }

}


运行结果图:

ajax与servlet交互(通过JSON),JAVA的arraylist传到前端的方法_第1张图片



ajax与servlet交互(通过JSON),JAVA的arraylist传到前端的方法_第2张图片

ajax与servlet交互(通过JSON),JAVA的arraylist传到前端的方法_第3张图片

你可能感兴趣的:(java,web,JAVA,JavaScript)