Code is not executing when nothing is entered - java

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(""))

Related

Send object from a JSP page

What I want to do is to make a list of persons with id and other attributes.
First of all the app opens with a form to enter personal data. Then it goes to the servlet responsible to capture the data. Then the servlet sends it to another JSP file that shows data. Then if the user chooses to add another one it adds it.
This worked fine but I had to change the app to add to the HTML table a submit button so the user can delete the person he wants using another servlet for delete.
I tried to set the ArrayList that contains all the data as an attribute but it didn't work.
First i tried this way:
String x = request.getParameter("submit");
if (x != null) {
request.setAttribute("list", list);
request.setAttribute("id", p.getId());
request.getRequestDispatcher("Supprimer").forward(request, response);}
Then I tried this way:
out.println(" <tr><td> <form method='POST'>");
out.println("<input type='hidden' name='id' value='" + p.getId() + "' >");
request.setAttribute("list", list);
out.println("<input type='submit' value='Supprimer' name='submit' ></td></tr> ");
out.println(" <tr><td> </form >");
and this is the jsp file that will show the data
<%
ArrayList<personne> list = (ArrayList<personne>) request.getAttribute("list");
request.setAttribute("listt", list);
for (personne p : list) {
out.println("<table border='2'>");
out.println("<tr> <td>ID</td><td>");
out.println(p.getId());
out.println("</td> </tr><tr><td>Nom</td> <td>");
out.println(p.getNom());
out.println(" </td> </tr><tr> <td>Prenom</td> <td>");
out.println(p.getPrenom());
out.println(" </td> </tr><tr> <td>Sexe</td> <td>");
out.println(p.getSexe());
out.println(" </td></tr><tr><td>CodePostale</td><td>");
out.println(p.getCodePostal());
out.println(" </td></tr> </table> </br>");
out.println(" <tr><td> <form method='POST'>");
out.println("<input type='hidden' name='id' value='" + p.getId() + "' >");
request.setAttribute("list", list);
out.println("<input type='submit' value='Supprimer' name='submit' ></td></tr> ");
out.println(" <tr><td> </form >");
String x = request.getParameter("submit");
if (x != null) {
request.setAttribute("list", list);
request.setAttribute("id", p.getId());
request.getRequestDispatcher("Supprimer").forward(request, response);
}
out.println(" </table> </br>");
}
%>
this is the first servlet that will capture the data coming from the first submited form
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
String sexe = request.getParameter("sexe");
int codePostal = Integer.parseInt(request.getParameter("cd"));
personne p = new personne(id, nom, prenom, sexe, codePostal);
ap.add(p);
request.setAttribute("list", ap);
request.getRequestDispatcher("affichage.jsp").forward(request, response);
}
and this is the servlet responsibale for deleting the object and resend us to the first servlet so it can send us again to the jsp file to show us the new data
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<personne> list = (ArrayList<personne>)request.getAttribute("list");
int id =Integer.parseInt(""+request.getAttribute("id"));
System.out.println(id);
java.util.Iterator<personne> itr = list.iterator();
while (itr.hasNext())
{
if(id==itr.next().getId()){
itr.remove();
}
}
request.setAttribute("list", list);
request.getRequestDispatcher("affichage.jsp").forward(request, response);
}
Btw this didn't help me: how to send ArrayList from jsp to servlet
The code you write can not work, because you are storing item info on request object when you are rendering the HTML page.
One solution is to define for each field an hidden HTML field, as you already define to id attribute.
I tried to set the Arraylist that contains all the data as an attribute but it didn't work.
Form submit from jsp will eventually discard old request object itself since browser makes a new request to server.
Instead of relying on request.setAttribute("list", list) make use of session.setAttribute("list", list) just once in the servlet itself, no need to set in jsp.
Now, to access the list use session.getAttribute("list")

regex to ignore a character in between two string?

My String is
**abcd
*[abc]
<td> **Welcome
**Welcome Again
</td>
Is their any way in which I can remove the * symbol in between the tags so that my final string string would be something like
**abcd
*[abc]
<td> Welcome
Welcome Again
</td>
Here all the * between <td> and </td> are removed
I dont want to use string.
Try this,
if (s.contains("<td>"))
{
String first = s.substring(0, s.indexOf("<td>"));
String last = s.substring(s.indexOf("<td>"), s.indexOf("</td>") + 5);
System.out.println("result : "+first + last.replace("**", ""));
}
else
{
System.out.println("result : "+s);
}

Calling a servlet from a dynamically generated form

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>

How to: Struts 2 validating dynamic forms array

I read through this
Struts2 Validation for an array
and it makes sense, but wished person (Quaternion) would explain how to
"rewrite the above to specifically name fields (with indexes) in which case you can use , and you'll use the addFieldError method. For details on these tags see http://struts.apache.org/2.3.1.2/docs/tag-reference.html"
This is what I have:
<s:form action="saveOrUpdateAction" method="get">
<s:token/>
<table>
<tr>
<td> Fund </td>
<td> Award Code </td>
</tr>
<s:iterator value="gfeListWithEmptyCode">
<tr>
<td> <s:property value="sfafund "/> </td>
<td> <s:property value="awardcode"/>
<input type="text" name="codeArray">
</td>
</tr>
</s:iterator>
<s:token />
<s:submit key="Submit2"/>
</table>
</s:form>
Part of my Action:
public void validate()
{
if (fund == null || fund.trim().length() != 5 )
{
System.out.println("testing+++++++++++++++++++1");
addFieldError("fund","Fund requires 5 characters.");
}
if (code == null || code.trim().length() != 3 )
{
System.out.println("testing+++++++++++++++++++2");
addFieldError("code","Fund requires 3 characters.");
}
if (gfeListWithEmptyCode !=null)
{
int index = 0;
for (GiftFundEntity giftFundEntity : gfeListWithEmptyCode)
{
if ( codeArray[index]!=null && codeArray[index].length() < 3 )
{
System.out.println("testing+++++++++++++++++++3");
// technically, this is not possible to do because it requires codeArray[index] and not a string.
addFieldError("codeArray","Code requires 3 characters.");
index++;
}
}
}
try
{
this.execute();
} catch (Exception e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
During validation, the red error message does not show up on the jsp page for obvious reasons because codeArray isn't listed by the indexes. How do I get this to work? * Please note* the array is dynamic.
I looked through the struts documentation and searched through stackoverflow, but I don't see how it can be done.
Thanks for your time.
The answer is Struts 2 treats the codeArray variable inside the Action class as an Array: String [] codeArray; This is not documented.

Nullpointer exception in doPost

I have de following Form:
<form action="/AppStore/publish" method="post" accept-charset="ISO-8859-1">
<fieldset>
<legend>Do you have an Account already?</legend>
<input type="radio" name="registred" value="yes"> Yes
<input type="radio" name="registred" value="no"> No
</fieldset>
<fieldset>
<legend>About your App</legend>
<table>
<tr>
<td><label for="AppDesc">Describe it:</label></td>
<td><input type="text" name="AppDesc" /></td>
</tr>
<tr>
<td><label for="AppName">Name:</label></td>
<td><input type="text" name="AppName" /></td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit" />
</form>
I pass this data to a Java Servlet, but every time I get a Nullpointer Exception at getParameter("AppDesc"), instead getParameter("AppName") works fine, what do I wrong?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
RequestDispatcher dispetcher = context.getRequestDispatcher("/publishForm.jsp");
List<String> errorMessages = new ArrayList<String>();
//Validating form input...
if(request.getParameter("AppName").toString().isEmpty())
{
errorMessages.add("Please type a valid Name for your App.");
}
if(request.getParameter("AppDesc").toString().isEmpty())
{
errorMessages.add("The Description of your App should contain at least 160 Characters.");
}
You're calling request.getParameter("...").toString().
request.getParameter() already returns a string reference, so you don't actually need to call toString() to get the value as a string, but it will return a null reference if the parameter is missing - in which case calling toString() will throw an exception. You need to check whether the value is null or empty. For example:
String description = request.getParameter("AppDesc");
if (description == null || description.isEmpty())
...
Of course, there are libraries around to check for "null or empty" - for example, in Guava you could use:
if (Strings.isNullOrEmpty(description))
If request.getParameter("AppDesc") is null, then
request.getParameter("AppDesc").toString().isEmpty() will throw a NullPointerException.
Why not change the condition to:
if(request.getParameter("AppDesc") == null ||
request.getParameter("AppDesc").toString().isEmpty()))
{
<td><input type="text" name="AppDescr" /></td>
You've named the actual field AppDescr (notice the trailing "r"), but you're calling getParameter for AppDesc (sans "r").
EDIT: Or not... you edited your post and fixed it. Was this not the problem?
It must be the case that request.getParameter("AppDesc") returns a null value, causing the chained toString() to generate a NullPointerException.
This parameter was never set; the name specified in the html was "AppDesr" (note the trailing 'r').
Your question title says doGet, your code says doPost. The difference between those two might explain your problem. :-)

Categories

Resources