Calling a servlet from a dynamically generated form - java

I'm making a mock up of an online store for school. I'm storing my products in an SQL Database. I want to display all products in the DB with buttons next to them that will send their ID to the cart_servlet. In order to display the products I'm generating a table like so:
public static String getInventory(){
String result = "<table>";
for ( Product p : DAO_Product.getProducts() ) {
result = result + "<tr>"
+ "<td>" + p.getName() + "</td>"
+ "<td><img src=\"resources/images/" + p.getImage() + "\" alt=\"Duke waving his hand\"></td>"
+ "<td>" + p.getDollars() + "</td>"
+ "<td>" + p.getPennies() + "</td>"
+ "<td>" + p.getStock() + "</td>"
+ "<td>" + p.getDescription() + "</td>"
//creates a form consisting of one button and a hidden value
//clicking the button should submit the corresponding hidden value
+ "<td><form action=\"${pageContext.request.contextPath}/cart_servlet\" method=\"post\">"
+ "<input type=\"hidden\" name=\"product\" value=\"" + p.getId() + "\" />"
+ "<input type=\"submit\" name=\"submit\" value=\"Add to Cart\" />"
+ "</form>"
//End Form
+ "</tr>";
}
}
This creates the correct table as I envisioned and the HTML it generates looks correct:
<table><tr><td>Caverna</td>
<td><img src="resources/images/caverna.jpg" alt="sampleImage"></td>
<td>112</td><td>12</td><td>34</td>
<td> you are the bearded leader of a small dwarf family which lives in a little cave in the mountains. Together, you</td>
<td><form action ="${pageContext.request.contextPath}/cart_servlet" method="post">
<input type="hidden" name="product" value="4" />
<input type="submit" name="submit" value="Add to Cart" />
</form>
However when I click the button I am presented with: 'HTTP Status 404 - Not Found' description: 'The requested resource is not available'
The Servlet I am requesting is my 'CartServlet':
#WebServlet( "/cart_servlet" )
public class CartServlet extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String result;
Status status = new Status();
req.setAttribute( "status", status );
//RequestDispatcher view = req.getRequestDispatcher( "browseProducts.jsp" );
if ( req.getParameter( "submit" ) != null ) {
}
//view.forward( req, resp );
}
}
I've commenting out everything in my 'CartServlet' and I am sure that it probably cant get the context somehow or find the class but I am unsure about how to fix this.

It turns out I was approaching this all wrong. Instead I should have built the table within my JSP using JSTL. With the following code I was able to delete 'getInventory()':
The First step is to add the following line to the top of your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Note Ensure you have downloaded the JSTL library and added it to your project. You can find it here.
The Second step is to declare any variables you would need. In this case I require an ArrayList of 'Products':
<%
ArrayList<Product> products = DAO_Product.getProducts();
//Set an attribute to reference our Arraylist
pageContext.setAttribute( "products", products );
%>
Now we are ready to build our table. The table will display information about each product and have a button in the last column that will call 'cart_servlet'. We are going to use the 'forEach' from 'JSTL':
<table border="1" cellpadding="5" >
<tr>
<th>Name</th>
<th>Image</th>
<th>Price</th>
<th>Description</th>
<th>Stock</th>
<th>Add to Cart?</th>
</tr>
<c:forEach var="p" items="${products}" >
<tr>
<td>${p.name}</td>
<td><img src="resources/images/${p.getImage()}" alt="Cool Pic"></td>
<td>$${p.dollars}.${p.pennies}</td>
<td>${p.description}</td>
<td>${p.stock}</td>
<td>
<form action="${pageContext.request.contextPath}/cart_servlet" method="post">
<input type="hidden" name="productID" value="${p.id}">
<input type="submit" name="addToCart" value="Add to Cart">
</form>
</td>
</tr>
</c:forEach>
</table>

Related

JSOUP - Select only some text from html

I am trying to select some text from the HTML using Jsoup in Android.
My HTML code looks like that:
<tr class="tip " data-original-title="">
<td>
!!! NOT That !!! </td>
<td>
A205 </td>
<td>
I want to get this </td>
<td>
And this </td>
<td>
!!! And not this !!! </td>
<td>
</td>
</tr>
How can I do that? Thank you so much!
For example:
package ru.java.study;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Main {
private static String htmlText =
"<tr class=\"tip \" data-original-title=\"\">" +
"<td>!!! NOT That !!!</td>" +
" <td>" +
" A205 </td>" +
" <td>" +
" I want to get this </td>" +
" <td>" +
" And this </td>" +
" <td>" +
" !!! And not this !!! </td>" +
" <td>" +
" </td>" +
" </tr>";
public static void main(String[] args) {
Document document = Jsoup.parse("<table>"+htmlText); //Add <table>
String first_TD = document.select("td").get(2).text();
String second_TD = document.select("td").get(3).text();;
System.out.println(first_TD);
System.out.println(second_TD);
}
}
You must be more specific in your selection. There should be id="..." or class="..." attributes in <table> tag to precisely identify the table that you need.
// Don't forget about <table> tag
String html = "<table>" +
"<tr class=\"tip \" data-original-title=\"\">" +
"<td>!!! NOT That !!!</td>" +
"<td>A205</td>" +
"<td>I want to get this</td>" +
"<td>And this</td>" +
"<td>!!! And not this !!!</td>" +
"<td></td>" +
"</tr>" +
"</table>";
Document doc = Jsoup.parseBodyFragment(html);
// You should use more specific selector.
// For example if table tag looks like this: <table id="myID">...</table>
// then selector should look like this "table#myID tr.tip > td"
Elements cells = doc.select("tr.tip > td");
String cell3content = cells.get(2).html(); // use .text() for content without html tags
String cell4content = cells.get(3).html();
System.out.println(cell3content);
System.out.println(cell4content);

Code is not executing when nothing is entered

I am attempting to build a world clock, to display GMT, PST etc.
The only problem I'm having is that when the user types nothing in the text field, it's not going into the if statement that only executes when the user doesn't enter anything and displays the local time. I have provided all my code to see what the problem is.
html code:
<body>
<form action="WorldClockWebApp" method="post">
<table>
<tr>
<td>Enter Time Zone:</td>
<td><input type="text" name="timezone" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String input = request.getParameter("timezone");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
ZoneId z;
boolean valid = true;
TimeZone t = null;
String[] ids = TimeZone.getAvailableIDs();
if (input != "") // If the user enters in a timezone.
{
for (String id : ids) {
if (input.equalsIgnoreCase(id))
t = TimeZone.getTimeZone(id);
}
}
if (t == null)
response.getWriter().append("<h1>What's the time Mr Wolf?</h1>")
.append("<p>No time provided, but the local time is " + t.getDisplayName().toString() + " is:</p>")
.append("<h2>" + LocalTime.now(t.toZoneId()).format(dtf) + "</h2>")
.append("<form action=\"/project4/WorldClock.html\">" + "<button type=\"submit\">Go Back</button>"
+ "</form>"); // Button gives user option to go back.
else
response.getWriter().append("<h1>What's the time Mr Wolf?</h1>")
.append("<p>The current time in " + t.getDisplayName().toString() + " is:</p>")
.append("<h2>" + LocalTime.now(t.toZoneId()).format(dtf) + "</h2>")
.append("<form action=\"/project4/WorldClock.html\">" + "<button type=\"submit\">Go Back</button>"
+ "</form>"); // Button gives user option to go back.
}
I think you need to do if input != null instead of if input !="".
assuming that you implement doPost method and it is like doGet method, you should use equals instead of != "" .
your code can be like below code.
if (!input.equals(""))

Print Java Results to multiple locations

I got a scripts that convert google locations to google coordinates (lat/lng) and that works great.
My results are printed to a table with td and tr. Till now, everything works good.
But i want to print the results (The coordinates) also to another location in HTML.
I want that the results also printed to a table in XXXX. Optional also the location...
It is not working for me...
function getResultsListItem(resultNum, resultDescription) {
var html = '<a onclick="selectMarker(' + resultNum + ')">';
html += '<div class="info" id="p' + resultNum + '">';
html += '<table><tr valign="top">';
html += '<td style=""><img src="' + getMarkerImageUrl(resultNum) + '"/></td>';
html += '<td style="">' + resultDescription + '</td>';
html += '</tr></table>';
html += '</div></a>';
return html;
}
/**
* Get suggestions for a postcode with multiple localities.
* #param {!google.maps.GeocoderResult} resultDescription Geocoding result.
*/
function getPostcodeLocalitiesSuggestion(resultDescription) {
if (resultDescription.types.indexOf("postal_code") == -1) return "";
console.log(resultDescription.postcode_localities.length + " localities");
var postcode = resultDescription.address_components[0].long_name;
var html = '<span class="dym">Did you mean</span>: ' + '<span class="pc_localities">' + postcode + ' in ';
for (i in resultDescription.postcode_localities) {
var locality = resultDescription.postcode_localities[i];
html += '<a href="#' + escape(getPermalink(postcode + ' ' + locality)) + '">';
html += locality + '</a>';
html += (i == resultDescription.postcode_localities.length - 1 ? '.' : ', ');
}
return html;
}
/**
* Get a nicely formatted result description.
* #param {!google.maps.GeocoderResult} result Geocoding result.
*/
function getResultDescription(result) {
var bounds = result.geometry.bounds;
var html = '<table class="tabContent">';
html += tr('Address', result.formatted_address);
if (result.postcode_localities) {
html += tr('Localities', result.postcode_localities.join('<br/>'));
}
html += tr('Types', result.types.join(", "));
html += tr('Location', result.geometry.location.toString());
html += tr('Bounds', (bounds ? boundsToHtml(bounds) : "None"));
html += tr('Viewport', boundsToHtml(result.geometry.viewport));
html += tr('Location type', result.geometry.location_type);
if (result.partial_match) {
html += tr('Partial match', 'Yes');
}
html += '</table>';
return html;
}
The HTML with location and name...
<table width="90%" border="0">
<tr>
<td>Foto: *</td>
<td>
<input type="file" id="bestand" name="bestand">
</td>
</tr>
<tr>
<td>Boxname: *</td>
<td>
<input type="text" id="boxname" name="boxname">
</td>
</tr>
<tr>
<td>User: *</td>
<td>
<input type="text" id="user" name="user">
</td>
</tr>
<tr>
<td>Country: *</td>
<td>
<select name="categorie" id="categorie">
<option value=""> - Gelieve een Land te kiezen - </option>
<option value="<?php echo $categorie['categorie_id']; ?>">
<?php echo $categorie['naam']; ?>
</option>
</select>
</td>
</tr>
<tr>
<td>Location: *</td>
<td>
<textarea id="location" name="location"></textarea>
</td>
</tr>
<tr>
<td>Coordinates: *</td>
<td>
<textarea id="coordinates" name="coordinates"></textarea>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" id="knop" name="knop" value="Add New Suezbox">
</td>
</tr>
</table>

Invoking Java Applet with dynamic parameters

Here's the scenario. The user fill a form with a certain number of parameters in an html page, then I need to invoke my applet with this specific parameters, possibly within the same page. What's the easiest way to perform this pass?
I'm using the runApplet function, but it's not working. No messages in the JS console and in the Java console.
<html>
<head>
<title>Compila i dati</title>
</head>
<body>
<script src=
"http://www.java.com/js/deployJava.js"></script>
<script>
function runApplet(){
var attributes = { id:'anID', code:'Test', width:1, height:1, codebase: '.'} ;
var parameters = {width:'100', height:'100', code:'Test', archive: 'applet.jar, xyz.jar, abc.jar',
posX: document.forms["form1"]["posX"].value , posY: document.forms["form1"]["posY"].value , heightSign: '300' , widthSign: '600' ,
PDFUrl: 'http://anurl' ,
type:'application/x-java-applet' , scriptable:'false' } ;
deployJava.runApplet(attributes, parameters, 1.6);
}
</script>
<form name = "form1" onsubmit="runApplet()">
<div>
<label for="name">Nome:</label>
<input type="text" name="nome" />
</div>
<div>
<label for="mail">Cognome:</label>
<input type="text" name="cognome" />
</div>
<div>
<label for="msg">X:</label>
<input type="text" name="posX" />
</div>
<div>
<label for="msg">Y:</label>
<input type="text" name="posY" />
</div>
<div class="button">
<button type="submit">Invia</button>
</div>
</form>
</body>
I could try to create an dinamic applet contanier via javascript in this way:
$('#idappletv').empty();
$('#idappletv').hide();
var _xmhlcode = " <script> function javafxEmbed() {" +
"dtjava.embed( " +
"{" +
" id: 'myBrApplet'," +
" url : 'pages/applet/myApplet.jnlp'," +
" placeholder : 'javafx-app-placeholder'," +
" width : 890 ," +
" height : 200," +
" jnlp_content : 'bmFtZT0iQXBwbGV0RnhCcm93c2VyIiAvPg0KICA8dXBkYXRlIGNoZWNrPSJhbHdheXMiLz4NCjwvam5scD4NC=='" +
", params: {param1:'" + param1 + "',param2:'" + param2 + "'}" +
"}," +
"{" +
" javafx : '2.2+'" +
"}," +
"{}" +
");" +
"}" +
"dtjava.addOnloadCallback(javafxEmbed); </" + "script> ";
$('#idappletv').append("<div id='javafx-app-placeholder'></div>");
$('#idappletv').append(_xmhlcode);
dtjava.addOnloadCallback(javafxEmbed);
$('#idappletv').show();
Then when the applet starts you can read the parameter using:
#Override
public void start(Stage primaryStage) {
Parameters params = getParameters();
String param1 = params.getNamed().get("param1");
String param2 = params.getNamed().get("param2");
You can read the parameter "param1 and param2" from your html page.
It should be works.
I used JavaFX with java-webstart (http://docs.oracle.com/javafx/2/deployment/deploy_swing_apps.htm).

How to send values from java class to jsp page ?

I have created two jsp pages in which I am able to get the response of my input. Below are my 2 jsp pages. Also I would like to get a response from android java class to the same Index1.jsp.(For eg: If I am sending one string to Index1.jsp I would to get the response as same string).
Index.jsp
<form action="index1.jsp" method="POST">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
Index1.jsp
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getParameter(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>

Categories

Resources