【问题标题】:Putting a JQuery Array into a Java ArrayList String then using it将 JQuery 数组放入 Java ArrayList 字符串然后使用它
【发布时间】:2015-06-25 11:59:53
【问题描述】:

我有一个成功的 ajax,它需要一个 url 数组,例如“www.asd.com,www.efuief.com”和 POST 到我的生成 servlet。当我在 ajax javascript 文件中提醒它时,我可以看到数组字符串。我可以看到生成 servlet 的 POST 发生在浏览器网络选项卡中。

数组被传递给我的生成 serlvet,我想在那里

a) 查看数组的内容,但我不确定如何。我有一些 system.out.printlns 但当我运行网页并单击按钮时它们似乎没有做任何事情。

b) 获取数组的内容,并且(如果它们还不是字符串)然后将它们解析为 java arraylist 。一个网站给了我(相当冗长的)方法来做到这一点,我将数组转换为列表(对象?)然后将列表转换为 ArrayList 字符串

c) 最后我想将数组提供给我的 imageController,它试图循环遍历数组列表。但是,它给了我消息“对象无法转换为字符串”,表明有些事情没有成功?

代码很长,但我认为问题区域非常不同(我评论了两个可疑区域)。如果你能看看那将是惊人的。如果有的话,也许你可以告诉我如何以某种方式将这些值打印到我的屏幕上,因为我的 system.out.println 东西没有激活......

谢谢

Ajax(应该可以工作...)

$(document).ready(function () {
    $('#button').click(function () {

        var array = [];

        $('#sortable2 .selectedItemImg').each(function () {

            array.push($(this).attr('src'));
        });

      alert(array);

        $.ajax({
            url: 'generate',
            type: 'POST',
            dataType: 'array',
            data: (array),

            success: function (data) {
//                alert("test44");
            }

// send url to user
// 
//
        }
        );
    });
    return false;
    }
    );

小服务程序

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author J
 */
@WebServlet(name = "ImageGenerationServlet", urlPatterns = {"/generate"})
public class ImageGenerationServlet extends HttpServlet {



    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ImageGenerationServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ImageGenerationServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


        // THESE PARTS DONT APPEAR TO WORK!! :)

        List imageList = Arrays.asList(request.getParameter("button"));

        System.out.println(imageList);

        ArrayList <String> imageURLs = new ArrayList(Arrays.asList(imageList));

        System.out.println(imageURLs);

        ImageController imgc = new ImageController(imageURLs);




         // 1) retrieve array of urls
         // 2) send to imagegenerationcontroller
         // 3) send to uploadcontroller
         // 4) retrieve and parse the json response to get the imgur url
         // 5) response from here to user


    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

ImageController(对字符串做一些事情,除了它似乎没有变成字符串)

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 * @author J
 */
public class ImageController {

//int roundUp(int numToRound, int multiple) 
//{ 
// if(multiple == 0) 
// { 
//  return numToRound; 
// } 
//
// int remainder = numToRound % multiple;
// if (remainder == 0)
//  return numToRound;
// return numToRound + multiple - remainder;
//}

    int roundUp(int numToRound, int multiple) {
    return (numToRound+multiple-1) / multiple;
}

public ImageController(ArrayList imageURLs) throws IOException

  {



//      ArrayList <String> imageURLs = new ArrayList<>();

//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");

//Integer totalHeight= 300*((Math.round(imageURLs.size()/6)));

//Integer totalHeight = imageURLs.size()*300/4;


//Integer totalHeight = 300*(roundUp(imageURLs.size(), 4));

Integer totalHeight = (roundUp(imageURLs.size(),4))*200;

System.out.println(imageURLs.size());
System.out.println(totalHeight);

// height = numberofentries / 4 rounded up to the nearest multiple of 4

// height = numberofentries rounded up to the nearest 4, divided by 4, times 300px

//Double heightMath= 300*(4*(Math.ceil(Math.abs(imageURLs.size()/4.0))));

//Long heightMath= 300*(long)Math.floor(imageURLs.size() + 1d);

//Integer totalHeight = (int) (double) heightMath;

//if (totalHeight < 300){ 
//      totalHeight = 300; 
//  }

BufferedImage result = new BufferedImage(
                               736, totalHeight, //work these out
                               BufferedImage.TYPE_INT_RGB);

Graphics g = result.getGraphics();

Integer x = 0;
Integer y = 0;



//THIS SAYS "OBJECT CANNOT BE CONVERTED TO STRING!"
// IT SHOULD HAVE BEEN PARSED INTO AN ARRAYLIST<STRING> ALREADY?

for(String imageURL : imageURLs){

        BufferedImage bi = ImageIO.read(new File(imageURL));
        g.drawImage(bi, x, y, null);
        x += 184;
        if(x >= result.getWidth()){
            x = 0;
            y += bi.getHeight();
        }

          ImageIO.write(result,"png",new File("C:\\Users\\J\\Desktop\\resultimage.jpg"));
    }
}
}

编辑我的所有文件(更新版本):

索引jsp

<%@page language ="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Anime List Creator</title>

        <script src="webresources/jquery-2.1.3.min.js"></script>
        <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>-->
        <script src="webresources/basic.js"></script>
<script src="webresources/submitList.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <!--<link rel="stylesheet" href="/resources/demos/style.css">-->
        <style>

            body {
                background-color: #ffffff;
            }

            #sortable1 {
                /*                border: 1px solid #eee;
                                width: 142px;
                                min-height: 20px;
                                list-style-type: none;
                                margin: 0;
                                padding: 5px 0 0 0;
                                float: left;
                                margin-right: 10px;*/

                list-style-type: none; padding: 0px; width: 926px; border-style: solid; border-width: 2px; min-height: 310px; float: left; background-color: #e9e9e9; max-height: 1240px; overflow: auto;
            }

            #sortable2 {
                /*                border: 1px solid #eee;
                                width: 142px;
                                min-height: 20px;
                                list-style-type: none;
                                margin: 0;
                                padding: 5px 0 0 0;
                                float: left;
                                margin-right: 10px;*/

                list-style-type: none; padding: 0px; width: 926px; margin-left: 30px; border-style: solid; border-width: 2px; min-height: 310px; float: left; background-color: #7fc1ff;
            }


            #sortable1 li, #sortable2 li {
                /*                margin: 0 5px 5px 5px;
                                padding: 5px;
                                font-size: 1.2em;
                                width: 120px;*/

                margin: 10px 0px 45px 10px; padding: 0px; width: 216px; height: 300px; font-size: 16px; text-align: center; float: left; color: white; border-style: none; font-family: Geneva,Tahoma,Verdana,sans-serif;
            }





        </style>
        <script>
            $(function () {
                $("#sortable1, #sortable2").sortable({
                    connectWith: ".connectedSortable"
                }).disableSelection();
            });
        </script>

        <script>


//            $("#button").click(function() {
//
////            function loop() {
////            alert()
////                    $('#sortable2 .row.selected img').each(function() {
////            alert($(this).attr('src'))
////            })
//
//alert("hi");

//$(document).ready(function() {
//  $("#button").click(function () {
//    alert("Hello1");


//        $('#sortable2 .selectedItemImg').each(function() {
//$('img.selectedItemImg').each(function() {
//        alert(this.src);

//    $('.userList .selectedItemId .selectedItemImg img').each(function() {
//    $(".userList").each(function() {
//        $('.userList').find('#textid');
//        alert($('.userList id img'));
//        alert($(this).attr.div($(this).attr("id")));
//        alert($(this).attr("id"));
//        alert($(this).attr("src"));
//        alert("Hello2!");
//            });
//  });




        </script>


<!--        <script src="${page.request.contextPath}/webresources/jquery-2.1.3.min.js"></script>
        <script src="${page.request.contextPath}/webresources/basic.js"></script>-->


        <!--<link rel="stylesheet" href="webresources/css/basic.css" type="text/css" media="screen"/>-->
    </head>

    <body background-color:black;>
          <h1>Anime List Creator</h1>

        <form id="searchForm">
            <label for="searchQuery">Make a search</label>
            <input type="text" id="searchQuery" name="searchQuery"/>
            <input type="submit"/>
        </form>

        <div id="searchContainer1"></div>




        <!--<p id="displaySearchResults"><p/>-->

        <!--        <div id="searchContainer1"
                <p id="displaySearchResults1"><p/>
                <p id="displaySearchResults2"><p/>
                <p id="displaySearchResults3"><p/>
                </div>-->


        <hr/>

        <ul id="sortable1" class="connectedSortable">
            <!--            <li class="ui-state-default">Item 1</li>
                        <li class="ui-state-default">Item 2</li>
                        <li class="ui-state-default">Item 3</li>
                        <li class="ui-state-default">Item 4</li>
                        <li class="ui-state-default">Item 5</li>-->
        </ul>

        <ul id="sortable2" class="connectedSortable">
            <!--            <li class="ui-state-highlight">Item 1</li>
                        <li class="ui-state-highlight">Item 2</li>
                        <li class="ui-state-highlight">Item 3</li>
                        <li class="ui-state-highlight">Item 4</li>
                        <li class="ui-state-highlight">Item 5</li>-->
        </ul>

        <hr/>

        <button id="button" name="button">Save List</button>

    </body>
</html>

图像小服务程序

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author J
 */
@WebServlet(name = "ImageGenerationServlet", urlPatterns = {"/generate"})
public class ImageGenerationServlet extends HttpServlet {



    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ImageGenerationServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ImageGenerationServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


        // THESE PARTS DONT APPEAR TO WORK!! :)

//        List imageList = Arrays.asList(request.getParameter("button"));
//        
//        System.out.println(imageList);
//         
//        ArrayList <String> imageURLs = new ArrayList(Arrays.asList(imageList));
//        
//        System.out.println(imageURLs);

//         ArrayList <String> imageURLs = new ArrayList(request.getParameter("button"));

//        String postResponse = request.getParameter("button");

//        ArrayList<Map> imageMap = new ArrayList<Map>();

//        String[] urls1 = postResponse.split(",");


//        ImageController.controlImage(urls1);

        List<String> imageURLs = new ArrayList<String>();
try {
    BufferedReader reader = request.getReader();
    String line;
    do {
        line = reader.readLine();
        imageURLs.add(line);

    } while (line != null);
}catch(Exception e){};

//int size = imageURLs.length();

        ImageController.controlImage((ArrayList<String>) imageURLs);


         // 1) retrieve array of urls
         // 2) send to imagegenerationcontroller
         // 3) send to uploadcontroller
         // 4) retrieve and parse the json response to get the imgur url
         // 5) response from here to user


    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

图像控制器

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 * @author J
 */
public class ImageController {

//int roundUp(int numToRound, int multiple) 
//{ 
// if(multiple == 0) 
// { 
//  return numToRound; 
// } 
//
// int remainder = numToRound % multiple;
// if (remainder == 0)
//  return numToRound;
// return numToRound + multiple - remainder;
//}





public static void controlImage(ArrayList<String>imageURLs ) throws IOException

  {



//      ArrayList <String> imageURLs = new ArrayList<>();

//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");
//imageURLs.add("C:\\Users\\J\\Desktop\\test5.jpg");


//Integer totalHeight= 300*((Math.round(imageURLs.size()/6)));
//
//Integer totalHeight = imageURLs.size()*300/4;
//
//Integer totalHeight = 300*(roundUp(imageURLs.size(), 4));

//      int arraySize = imageURLs.length();

Integer totalHeight = (roundUp(imageURLs.size(),4))*200;


//System.out.println(imageURLs.size());
//System.out.println(totalHeight);

// height = numberofentries / 4 rounded up to the nearest multiple of 4

// height = numberofentries rounded up to the nearest 4, divided by 4, times 300px

//Double heightMath= 300*(4*(Math.ceil(Math.abs(imageURLs.size()/4.0))));

//Long heightMath= 300*(long)Math.floor(imageURLs.size() + 1d);

//Integer totalHeight = (int) (double) heightMath;

//if (totalHeight < 300){ 
//      totalHeight = 300; 
//  }

BufferedImage result = new BufferedImage(
                               736, totalHeight, //work these out
                               BufferedImage.TYPE_INT_RGB);

Graphics g = result.getGraphics();

Integer x = 0;
Integer y = 0;



//THIS SAYS "OBJECT CANNOT BE CONVERTED TO STRING!"
// IT SHOULD HAVE BEEN PARSED INTO AN ARRAYLIST<STRING> ALREADY?

for(String imageURL :  imageURLs){

        BufferedImage bi = ImageIO.read(new File(imageURL));
        g.drawImage(bi, x, y, null);
        x += 184;
        if(x >= result.getWidth()){
            x = 0;
            y += bi.getHeight();
        }

          ImageIO.write(result,"png",new File("C:\\Users\\J\\Desktop\\resultimage.jpg"));
    }
}

    private static int roundUp(int numToRound, int multiple) {
    return (numToRound+multiple-1) / multiple;
}

}

提交列表 ajax

$(document).ready(function () {
    $('#button').click(function () {

        var array1 = [];

        $('#sortable2 .selectedItemImg').each(function () {

            array1.push($(this).attr('src'));
        });

      alert(array1);

        $.ajax({
            url: 'generate',
            type: 'POST',
            dataType: 'json',
            data: (array1),

            success: function (data) {
//                alert("test44");
            }

// send url to user
// 
//
        }
        );
    });
    return false;
    }
    );

我能想到的唯一奇怪的事情是我删除了我的 WEB-INF 配置文件(servlet 映射的东西),因为它在我重命名文件时有奇怪的重复。我的网络应用程序停止工作了一段时间,最终我删除了整个文件夹,它又开始工作了。所以我怀疑这与任何事情有关。

【问题讨论】:

  • 那么,POST 数据是什么样的? 完整请求是什么?
  • 我同意鲍里斯的观点。我不确定'array' 是一个有效的数据类型,所以它可能是 json。如果是这样,您可以在 Java 端使用 Jackson 进行转换。
  • 您知道我如何“查看”然后 POST 以使用 Chrome 查看数据吗?我可以单击网络并查看:`生成:方法:POST,状态:200,类型 Text/html。所以你可以在那里谢谢你们俩。

标签: java string list arraylist


【解决方案1】:

这里有几个问题。请注意,ArrayList 实现了 List,因此您几乎不需要将 List 转换为 ArrayList。 在 doPost 中,request.getParameter("button") 将获取您未在 ajax 调用中传递的表单或查询参数“button”。要获取原始 POST 正文,请使用类似这样的内容

List<String> imageURLs = new ArrayList<String>();
try {
    BufferedReader reader = request.getReader();
    String line;
    do {
        line = reader.readLine();
        imageURLs.add(line);
    } while (line != null);

在 ajax 调用中,dataType "array" 无效。 dataType 还指定您希望从服务器返回的内容,如果您在 doPost 中调用 processRequest,它将是 html。 You can receive a JSON object that will automatically be converted to a Javascript Object, just plain text as a string, or a few others。上面的代码已经分隔了 POST 正文的每一行,所以为了简单起见,下面的代码只是将每个 URL 发送到一个新行。如果您的数据变得更复杂,您可能需要研究 Java 中的 JSON 解析。

$.ajax({
    url: 'generate',
    type: 'POST',
    contentType: 'text/plain',
    dataType: 'html'
    data: array.join('\n'),
    success: function (data) {
        // data will be html as text
        // This executes only when the request returns successfully.
    }
});

您会收到编译错误“对象无法转换为字符串”,因为当没有类型参数时,像 ArrayList 这样的泛型类型被隐式声明为 ArrayList。查找原始类型以获取更多信息。要修复编译错误,请将 ImageController 的构造函数更改为

public ImageController(ArrayList<String> imageURLs)

【讨论】:

  • 感谢您抽出宝贵时间查看并为我解释一下。我的代码现在没有“红线”。问题是我不确定如何检查它是否正常工作。我拥有的唯一返回值是图像生成器将新图像保存到我的磁盘,但它没有这样做。我不知道如何让诸如“system.out.writeline”之类的东西出现在 Web 应用程序中。我唯一能看到的是,当我在 POST 上查看 chrome 的开发人员控制台时,发现它仍然显示“未定义、未定义、未定义”。我截图了imgur.com/pxuw2jR
  • 我用我所有的(更新的)文件(包括索引)更新了我的线程。我要休息一下然后回来。现在真是一场噩梦!
  • 非常抱歉。我一定是在你的帖子中走偏了。我现在实现了你的 ajax 版本
  • 在实现解析器更改和 ajax 更改之后,我不得不告诉我的 imageWriter 使用 URL 形式的数据,因为数据是超链接的形式。我很欣慰,也很感激,非常感谢,终于把这个整理好了,感觉难以置信。
  • @user3474126 如果您要制作许多此类 Web 服务,您可能需要研究 RestEasy 或 Jersey。两者都可以轻松创建 Web 服务,并且可以自动将 JSON 或 XML 请求解析为 Java 对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2018-04-25
相关资源
最近更新 更多