I have a successful ajax that takes an array of urls e.g. "www.asd.com,www.efuief.com" and POSTs to my generate servlet. I can see the array string when i alert it during the ajax javascript file. I can see that POST to generate servlet occurs from the browser network tab.
The array is passed to my generate serlvet and there I want to
a) view the contents of the array , but i'm not sure how. i have some system.out.printlns but they don't seem to do anything when i run the webpage and click the button.
b) take the contents of the array and (if they are not already a string) then parse them into a java arraylist . a website gave me (rather longwinded) methods to do this where i convert the array to a List (object?) then the List to an ArrayList String
c) lastly i want to feed the Array to my imageController which tries to loop through the arraylist. HOWEVER, it gives me the message "object cannot be converted to string" , indicating that something hasn't worked down the line?
The code is pretty long but i think the problem areas are very distinct (i commented the two suspect areas). If you could take a look that would be amazing. If anything, maybe you could tell me how I can print these values to my screen somehow since my system.out.println thing isn't activating....
Thankyou
Ajax (should be working...)
$(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 (do stuff with the string , except it doesnt appear to have been turned into a string)
/*
* 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"));
}
}
}
Editing in all my files (updated versions):
Index 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>
Image 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>
}
Image controller
/*
* 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;
}
);
The only weird thing I can think of is that I deleted my WEB-INF config file (servlet mapping thing) because it had weird duplicates in it from when i renamed files. My web app stopped working for a while, eventually I just deleted the whole folder and it started working again. So I doubt thats anything to do with anything.
POST
data look like? What's the full request? – Boris the Spider yesterday'array'
is a valid datatype, so it's probably json. If so, you could use Jackson on the Java side to do the convertion. – Ralf yesterday