我有一个成功的ajax,它采用了一系列网址,例如" www.asd.com,www.efuief.com"和POST到我的生成servlet。当我在ajax javascript文件中提醒它时,我可以看到数组字符串。我可以看到用于生成servlet的POST来自浏览器网络选项卡。
数组传递给我的生成serlvet,我想
a)查看数组的内容,但我不确定如何。我有一些system.out.printlns,但是当我运行网页并点击按钮时,他们似乎什么都不做。
b)获取数组的内容(如果它们不是字符串),然后将它们解析为java arraylist。一个网站给了我(相当longwinded)方法来做到这一点,我将数组转换为List(对象?)然后将List转换为ArrayList字符串
c)最后我想将数组提供给我的imageController,它试图遍历arraylist。但是,它给了我消息"对象无法转换为字符串" ,表明某些事情没有起作用?
代码很长但我认为问题领域非常明显(我评论了两个可疑区域)。如果你可以看一看会很棒。如果有的话,也许你可以告诉我如何以某种方式将这些值打印到我的屏幕上,因为我的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;
}
);
的Servlet
* 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>
图片servlet
/*
* 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;
}
}
SubmitList 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映射的东西),因为它在我重命名文件时有奇怪的重复。我的网络应用程序停止工作了一段时间,最终我删除了整个文件夹,它又开始工作了。所以我怀疑这与任何事都有关系。
答案 0 :(得分:1)
这里有一些问题在起作用。请注意,ArrayList实现了List,因此您几乎不需要将List转换为ArrayList。 在doPost中,request.getParameter(&#34; button&#34;)将获得表单或查询参数&#34; button&#34;你没有通过你的ajax电话。要获得原始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&#34;数组&#34;无效。 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.
}
});
您收到编译错误&#34;对象无法转换为字符串&#34;因为当没有类型参数时,像ArrayList这样的泛型类型被隐式声明为ArrayList。查找原始类型以获取更多信息。要修复编译错误,请将ImageController的构造函数更改为
public ImageController(ArrayList<String> imageURLs)