Website functionality breaks when code comes from AJAX - java

I have a gallery of images, and when I hover the mouse over any of the images, the image pulls back revealing some text.
When I have the following HTML code (at bottom of post) inside the HTML document, everything works fine.
However, when I put the exact same HTML code inside a Java servlet and have it returned to the page, everything looks normal, but the image pullback doesn't work anymore.
Any idea why that would occur? Perhaps I need to do some kind of refresh to make it work properly?
relevant code for one of the items in the gallery:
<li>
<div class="header"><p>Product 1 Shirt</p></div>
<div class="gallery_item">
<img src="gallery/thumb/gallery_01.jpg" width="214" height="194" class="cover" alt="" />
<p>Highlight 1</p>
<p>Highlight 2</p>
<p>Highlight 3</p>
More Info
Enlarge
</div>
<div class="p2"><p>Price: $10</p></div>
<div class="p2"><p>In Stock: Yes</p></div>
</li>
As requested: the servlet:
public void service(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String requestType = request.getParameter("type");
String result;
if(requestType.equals("getproductlist"))
{
Products products = Products.getProductsInstance();
String keywords = request.getParameter(("keywords"));
String organization = request.getParameter(("organization"));
String price = request.getParameter(("price"));
String sort = request.getParameter(("sort"));
result = products.getProducts(keywords, organization, price, sort);
//this next lines of html are actually what is returned from products.getProducts. I'm just putting it here for clarity. All the variables (name, h1, etc) are okay.
result += "<li>"
+ "<div class=\"header\"><p>"+ name +"</p></div>"
+ "<div class=\"gallery_item\">"
+ "<img src=\"gallery/thumb/gallery_01.jpg\" width=\"214\" height=\"194\" class=\"cover\" alt=\"\" />"
+ "<p>"+ h1 +"</p>"
+ "<p>"+ h2 +"</p>"
+ "<p>"+ h3 +"</p>"
+ "More Info"
+ "Enlarge "
+ ""
+ "</div>"
+ "<div class=\"p2\"><p>Price: "+ itemPrice +"</p></div>"
+ "<div class=\"p2\"><p>In Stock: "+ inStock +"</p></div> "
+ "</li>";
out.println(result);
out.close();
}

Related

Export HTML with data to MS Word

We have a requirement where we are asking our customers to fill the BRD document which is in a HTML file. HTML consists of radio buttons, text box etc along with colors and table. We will have a button which when clicked should call a java class which exports the HTML along with data customer inputs to word document. We are successful in converting a HTML code which is given directly as a string in the java program to word document. We are having issues in sending the HTML along with data.
Can any one let me know how I can achieve this? Or is there any better way we can do this.
public class XhtmlToDocx {
public static void main(String[] args) throws Exception {
//String html = "<html><form><input type=\"checkbox\" name=\"xhtml_mp_tutorial_chapter\" value=\"1\"/></form></html>";
String html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"+
"<head>"+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"+
"<title>Untitled Form</title>"+
"<link rel=\"stylesheet\" type=\"text/css\" href=\"view.css\" media=\"all\">"+
"<script type=\"text/javascript\" src=\"view.js\"></script>"+
"<script type=\"text/javascript\" src=\"calendar.js\"></script>"+
"</head>"+
"<body id=\"main_body\" >"+
" "+
" <img id=\"top\" src=\"top.png\" alt=\"\">"+
" <div id=\"form_container\">"+
" "+
" <h1><a>Untitled Form</a></h1>"+
" <form id=\"form_82495\" class=\"appnitro\" method=\"post\" action=\"\">"+
" <div class=\"form_description\">"+
" <h2>Untitled Form</h2>"+
" <p>This is your form description. Click here to edit.</p>"+
" </div> "+
" <ul >"+
" "+
" <li id=\"li_1\" >"+
" <label class=\"description\" for=\"element_1\">Text </label>"+
" <div>"+
" <input id=\"element_1\" name=\"element_1\" class=\"element text medium\" type=\"text\" maxlength=\"255\" value=\"\"/> "+
" </div> "+
" </li> <li id=\"li_3\" >"+
" <label class=\"description\" for=\"element_3\">Multiple Choice </label>"+
" <span>"+
" <input id=\"element_3_1\" name=\"element_3\" class=\"element radio\" type=\"radio\" value=\"1\" />"+
"<label class=\"choice\" for=\"element_3_1\">First option</label>"+
"<input id=\"element_3_2\" name=\"element_3\" class=\"element radio\" type=\"radio\" value=\"2\" />"+
"<label class=\"choice\" for=\"element_3_2\">Second option</label>"+
"<input id=\"element_3_3\" name=\"element_3\" class=\"element radio\" type=\"radio\" value=\"3\" />"+
"<label class=\"choice\" for=\"element_3_3\">Third option</label>"+
""+
" </span> "+
" </li> <li id=\"li_2\" >"+
" <label class=\"description\" for=\"element_2\">Date </label>"+
" <span>"+
" <input id=\"element_2_1\" name=\"element_2_1\" class=\"element text\" size=\"2\" maxlength=\"2\" value=\"\" type=\"text\"> /"+
" <label for=\"element_2_1\">MM</label>"+
" </span>"+
" <span>"+
" <input id=\"element_2_2\" name=\"element_2_2\" class=\"element text\" size=\"2\" maxlength=\"2\" value=\"\" type=\"text\"> /"+
" <label for=\"element_2_2\">DD</label>"+
" </span>"+
" <span>"+
" <input id=\"element_2_3\" name=\"element_2_3\" class=\"element text\" size=\"4\" maxlength=\"4\" value=\"\" type=\"text\">"+
" <label for=\"element_2_3\">YYYY</label>"+
" </span>"+
" "+
" <span id=\"calendar_2\">"+
" <img id=\"cal_img_2\" class=\"datepicker\" src=\"calendar.gif\" alt=\"Pick a date.\"> "+
" </span>"+
" <script type=\"text/javascript\">"+
" Calendar.setup({"+
" inputField : \"element_2_3\","+
" baseField : \"element_2\","+
" displayArea : \"calendar_2\","+
" button : \"cal_img_2\","+
" ifFormat : \"%B %e, %Y\","+
" onSelect : selectDate"+
" });"+
" </script>"+
" "+
" </li>"+
" "+
" <li class=\"buttons\">"+
" <input type=\"hidden\" name=\"form_id\" value=\"82495\" />"+
" "+
" <input id=\"saveForm\" class=\"button_text\" type=\"submit\" name=\"submit\" value=\"Submit\" />"+
" </li>"+
" </ul>"+
" </form> "+
" <div id=\"footer\">"+
" Generated by pForm"+
" </div>"+
" </div>"+
" <img id=\"bottom\" src=\"bottom.png\" alt=\"\">"+
" </body>"+
"</html>";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.getBytes());
afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(afiPart);
// .. the bit in document body
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId() );
wordMLPackage.getMainDocumentPart().addObject(ac);
// .. content type
wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
wordMLPackage.save(new java.io.File("C:/Users/****/Downloads/Word.docx"));
}
}
The problem you are facing seems to be happening because you are reading the static HTML page not the submitted page.
In order to get the full content of the submitted html, you need to submit your form first with the data, create it as a static html page and then access that page with XMLSerializer or URLStreamReader to get the final data to be passed to the word processing part of your program.
I am not providing an exact solution with code as I suppose you will be able to implement the solution yourself and you are mainly stuck on the logic.

How to return an ID with an '<input type='text' string from Java using JSON and AJAX to HTML

I have some Award images with dates under them that I am retrieving using Java and then passing back to HTML with JSON and AJAX to display. Each Award has a unique ID. When I change a date under one of the Award images I want to use the Award image ID to update the correct date.
How do I capture the correct Award ID to update the date for?
Also, the AJAX $('#awardDate').on('change', function() is not being triggered (i.e., I do not see the alert when I change a date. I have used Inspect in Chrome and no errors are shown.
The Java that extracts the images is in a 'for' loop (if this code fragment is not enough then I can add all the code):
The WebServlet opens with:
public class GetYMAwardsView extends HttpServlet implements Serializable {
private static final long serialVersionUID = 1L;
public String ymID = null;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
The loop contains:
awardType2 = youthMemberAward.getAwAwardType();
//Youth encrypted member ID is stored in session storage - ssYMID
//The encrypted Award ID is: encoded_award_ID
//Selecting the picture will display the requirements for the Award
//Updating the date under the Award will be saved to the database for that Award
json = "<h3>" + awardType2 + "</h3>";
json = json + "<div class='row'><div class='col-md-1'><a href='CubAwardOverview.html?id=" + encoded_award_ID +
"'><img src=" +
image + " height='90' width='90' style='border-style: none' alt='award image' /></a>" +
"<div class='caption'> <p>" +
"<input type='text' name='awardDate' id='awardDate' value='" + newstring + "' style='width: 90px;'/>" +
"</p> </div></div>";
i++; col++;
And then passed back with:
response.setContentType("image/jpeg");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
The HTML is:
<form data-toggle="validator" role="form" id="selectAward">
<div class="container-fluid">
<!-- div class="col-xs-12"> -->
<div class="form-select">
<!-- Place for Award image -->
<div class="input-group" id="img-container2">
</div>
</div>
<!--</div>-->
</div>
</form>
Once all the images are displayed, with the date under them, I try to catch the change in a date with AJAX. The AJAX I am using to catch the change of 'awardDate' is:
$('#awardDate').on('change', function() {
alert($("#awardDate").val());
var dataToBeSent = {
ssYMID : sessionStorage.getItem('ssYMID'),
};
$.ajax({
type: "POST",
url: "UpdateAwardedDateView",
cache: false,
data: $(awardDate).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text('Awarded date success.');
},
error: function() {
$("#awardDate").focus();
$('#ajaxGetUserServletResponse').text('An error occured applying the awarded date.');
}
}).done(function(responseJson) {
$('#ajaxGetUserServletResponse').text('Awarded date completed.');
});
});
In this AJAX call I want to pass the Youth Member's ID (ssYMID), Award ID and new date to the WebServlet"UpdateAwardedDateView".
Replace:
"<input type='text' name='awardDate' id='awardDate' value='" + newstring + "' style='width: 90px;'/>" +
With:
json = json + "<p>";
json = json + "<input class='form-control mr-sm-2' type='date' name='awardDate' id='awardDate' value='" + youthMemberAward.getCaAwardedDate() + "' onchange='myFunction(this.value, " + youthMemberAward.getAwId() + ")' style='width: 160px;'/>";
json = json + "</p>";

Getting data in order with Jsoup

I'm trying to get data from html in order from a web. Html code looks like:
<div class="text">
First Text
<br>
<br>
<div style="margin:20px; margin-top:5px; ">
<table cellpadding="5">
<tbody><tr>
<td class="alt2">
<div>
Written by <b>excedent</b>
</div>
<div style="font-style:italic">quote message</div>
</td>
</tr>
</tbody></table>
</div>Second Text<br>
<br>
<img class="img" src="https://developer.android.com/_static/images/android/touchicon-180.png"><br>
<br>
Third Text
</div>
What I want to do is create an Android layout scraping html, but I need to preserve the order of the elements. In this case:
TextView => First Text
TextView => Quote Message
TextView => Second Text
ImageView => img
TextView => Third Text
The problem comes when I try to get html values in order, using JSoup I get a String with "First Text Second Text Third Text" with Element.ownText, an then img at the end, resulting:
TextView => First Text Second Text Third Text
TextView => Quote Message
ImageView => img
What can I do to get that data in order?
Thanks in advance
You can parse the html into a list of html nodes. The list of nodes will preserve the DOM order and give what you want.
Check the parseFragment method :
This method will give you a list of nodes.
Try this.
String html = ""
+ "<div class=\"text\">"
+ " First Text"
+ " <br>"
+ " <br>"
+ " <div style=\"margin:20px; margin-top:5px; \">"
+ " <table cellpadding=\"5\">"
+ " <tbody><tr>"
+ " <td class=\"alt2\">"
+ " <div>"
+ " Written by <b>excedent</b>"
+ " </div>"
+ " <div style=\"font-style:italic\">quote message</div>"
+ " </td>"
+ " </tr></tbody>"
+ " </table>"
+ " </div>Second Text<br>"
+ " <br>"
+ " <img class=\"img\" src=\"https://developer.android.com/_static/images/android/touchicon-180.png\"><br>"
+ " <br>"
+ " Third Text"
+ " </div>";
Document doc = Jsoup.parse(html);
List<String> rootTexts = doc.select("div.text").first().textNodes().stream()
.map(node -> node.text().trim())
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
System.out.println(rootTexts);
OUTPUT:
[First Text, Second Text, Third Text]
This answer is a little late, but the correct way to do what you want to do is this. For your outermost <div>, instead of getting the child elements using Element.children(), you'll want to use Element.childNodes() instead.
Element.children() only returns child Elements, in which text is not included.
Element.childNodes() returns all child nodes, which includes TextNodes and Elements.
This solution works for me.

h:commandLink not working as intended

I have an problem which in turn is causing a lot of headaches. I need to dynamically create buttons/images which link to JSF actionListener. Here is the code:
HTML:
<h:form>
<div class="carousel-container">
<div id="carousel">
<h:outputText value="#{courseBean.course}" escape="false"/>
</div>
</div>
</h:form>
what courseBean.course gets is the Overriden toString which returns the following:
#Override
public String toString() {
return "<div class=\"carousel-feature\"> "
+ "<h:commandLink id=\"" + courseID + "\" actionListener=\"#{courseBean.getCourseSelected}\">"
+ "<img class=\"carousel-image\" src=\"Images/testButton.jpg\"/>"
+ "<span style=\"display:bloack; position:absolute; top:20px; bottom:20px; left:0; right:0; "
+ "background:white; background:rgba(255, 255, 255, 0.25);\">" + courseName + "</span>"
+ "</h:commandLink> "
+ "<div class=\"carousel-caption\"> "
+ "</div>"
+ "</div>";
}//end method toString
The HTML is being rendered fine and image is being displayed in the carousel however when it is clicked actionListener is not being called which is the issue here.
edit: the actionListener only prints the courseID to the console nothing major.
Thank you for taking your time :)
That approach is wrong, if you do "view source" you will see the <h:commandLink in the source of your page (because it wont be processed by JSF life cycle at all) , while if you had a <h:commandLink in your xhtml page the generated html source will contain a <a href....> element
You better rethink of your original goal and ask a question on how to achieve it...

Confused with Java Servlets and HTML

Part of my homework for tomorrow is to search and add entries using Java EE. If the search is not existing, an add item option will show as follow:
Supposedly, when the Stock ID is not existing, It will be transfered to the Add Item Text Field of StockID. But I have no idea how to do it. My code is as follows:
Servlet:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("/DataForm.html");
rd.include(request, response);
out.println("Sorry Item not found..");
rd = request.getRequestDispatcher("AddEntry.html");
rd.include(request, response);
}
}
}
HTML:
<html>
<head>
<title>Add Entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Add Item:</h2>
Stock ID: <input type ="text" name ="stockId" value="???"> <br> <--how to get it?
Item Name: <input type ="text" name ="name"> <br>
Unit Price: <input type ="text" name ="unitPrice"> <br>
On Stock : <input type ="text" name ="stock"> <br><br>
<input type ="submit" value ="Add Item">
</body>
</html>
You're approaching this the wrong way. HTML belongs in JSP files, not in Servlet classes. Also, EL ${} doesn't run in plain HTML files at all, but in JSP files only. Rename your .html files to .jsp. This way EL like ${param.id} will then also work, even though you still have a XSS attack hole open.
See also:
Our JSP wiki page
Our Servlets wiki page
(please read them, they contains hello world examples which should turn on some lights in your head)
You can't use the expression language (i.e. ${param.id}) in plain HTML files. It'll only be interpreted in JSPs (files with a .jsp extension).

Categories