We help IT Professionals succeed at work.

Help with Java, JSP and Servlet

BrainDeadStudent
on
Yes, this is classwork, these are the requirements
This project is intended to enforce your knowledge in:

applying EL, JSTL, and other techniques to minimize the maintenance and maximize the readability of JSP pages
developing and implementing world-ready JSP pages using scripting elements, EL, and JSTL
developing and implementing JavaBeans and use them with JSP pages
developing and implementing Model 1 architecture Web applications
developing and implementing secure Web applications using form-based declarative security
Project Requirements

Develop and implement a Web Application that calculates the roots of a quadratic equation of the form:

ax2 + bx + c

The Web application must use:

The Model 1 architecture -- a View-Controller JSP page and a Model JavaBean -- removing the model code from the presentation

Note: According to the Model 1 architecture, all the presentation logic (user input and text/results output) must be in the JSPs and all the business logic algorithms must be in the JavaBean. So, the quadratic equation algorithm has to be one method in the JavaBean and you have to use one additional property to pass the case to the JSP. The JSP would check the case property and display the proper text and/or solutions (also passed by properties from the JavaBean). No part of the business algorithm should be implemented in the JSP; no text/results presentation should be implemented in the JavaBean.

EL and JSTL -- avoiding scripting elements in the JSP page

The Web application's form should contain three boxes for input of the values for a, b, and c; and a Calculate button. An appropriate message and/or the calculated roots should be displayed at the bottom once the Calculate button is pressed.

Note: The roots of a quadratic equation of the provided above form, are determined by the following formula:  Ax^2 + Bx + C = 0

This is what I have so far using eclipse and Tomcat, would someone please take a look and tell me if I am doing the right thing and if I have set it up correctly and am using the right methods.

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Quad Solver</title>
</head>
<body>
<FORM action="GreetingServlet" method="POST">
Quadratic Equation Solver for Equations in the form of
Ax^2 + Bx + C<BR>
<BR>
Enter the value of A: <INPUT type="text" name="A" size="15"><BR>
Enter the value of B: <INPUT type="text" name="B" size="15"><BR>
Enter the value of C: <INPUT type="text" name="C" size="15"><BR>
<br>
<input type="submit" value="Calculate!">
<br>
<BR>
<BR>
</FORM>
</body>
</html>

GreetingServlet.java

package com.mycompany.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GreetingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GreetingServlet() {
		super();
	}
	 protected void doPost(HttpServletRequest request,
             HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
       PrintWriter out = response.getWriter();
       String A = request.getParameter("A").toString();
       String B = request.getParameter("B").toString();
       String C = request.getParameter("C").toString();
      
       double a = Double.parseDouble(A);
       double b = Double.parseDouble(B);
       double c = Double.parseDouble(C);
       double D = QuadraticSolver.getD();
       double[] roots = QuadraticSolver.quadratic();
       out.println("<html>");
		out.println("<head>");
		out.println("<title>Quadratic Equation Solver</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Quadratic Equation Solver </h1>");
		out.println("<h2>Your Equation is: <br><br>" + A + "x^2 + " + B + "x + " + C+ "<br>");
	   //QuadraticSolver solver = new QuadraticSolver ();
	   out.println("</h2>");
      
       //double D = QuadraticSolver.getD();
       if (a == 0.0) 
			out.println("<br>This is not a Quadratic quation ! ");
		if (b == 0.0) 
			out.println("<br>There is no solution ! ");
		if (a > 0.0 && b > 0) {
			out.println("<br><br>There is only 1 solution -C/B :  " );
			out.println("<br><br>Your Solution is : - "+ c + " / " + b + " equals" + -c/b );
			out.println("<br><br> X1 = "+ roots[0] );
			out.println("<br><br> X2 = "+ roots[1] );
     if(roots !=null){
            out.println("<br><br>Solutions are:<br><br>   X1 = " + roots[0] + " or X2 = " + roots[1]+"<br>");
             }else{
          out.println("<br><br>There Are No Real Solutions !!");
              }
 		out.println("</h2>");
		out.println("</body>");
		out.println("</html>");
		out.close();
}
}
}
	
QuadraticSolver.java

package com.mycompany.servlet;
import static java.lang.StrictMath.*;

public class QuadraticSolver {
	static double a;
	static double b;
	static double c;
	//double D;
	double discriminant = 0.0;
	double root1;
	double root2;

	static double[] quadratic() {
		double a = 0;
		double b = 0;
		double c = 0;
	
		// Return the roots of the quadratic equation
		double[] roots = new double[2];
		double D = Math.pow(b, 2) - (c*1)*(-c);
		if (D<0) {
			System.out.println("There are no real roots");
			System.out.println(D);
			return roots;
		}
		// Use Viete's formula to avoid loss of significance
		//double q = -0.5 * (b + copySign(sqrt(d), b));
		//roots[0] = q/a;
		//roots[1] = c/q;
		//return roots;
		//roots[0]=-b/2/a+Math.pow(Math.pow(b,2)-4*a*c,0.5)/2/a;
		roots[0] = ((-b + sqrt(D)) / (2 * a));
		return roots;
	}
	static double getD() {
		double D=0;
		D = b * b - 4.0f * a * c;  
		 return D;
	}
	public static void main(String[] args) {
		//double D=0;
		// D = Math.pow(b, 2) - (c*a)*(-c);
		 double D = QuadraticSolver.getD();
		double[] roots = quadratic();
		System.out.println(roots[0]);
		System.out.println(roots[1]);
	}
My ouput:
on the first page
Quadratic Equation Solver for Equations in the form of Ax^2 + Bx + C

Enter the value of A: 
Enter the value of B: 
Enter the value of C: 

on the second page

Quadratic Equation Solver 
Your Equation is: 

1x^2 + 3x + 4
There is only 1 solution -C/B : 
Your Solution is : - 4.0 / 3.0 equals-1.3333333333333333 

X1 = NaN 
X2 = 0.0 

Solutions are:

X1 = NaN or X2 = 0.0

My Directory structure:

MyFirstServlet
	Deployment descriptor:MyFirstServlet
	Java Resources :src
		Com.mycompany.servlet
	    	        GreetingServlet.java
	     	        QuadraticSolver.Java
		Libraries
	Java Script resources
	Build
	WebContent
		META-INF
		WEB-INF
			Classes
			Lib
			Web.xml
			Index.jsp

Open in new window

Comment
Watch Question

Commented:
You need to change your servlet to a JSP.
See near bottom of page at  
http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/ 
 and a make your QuadraticSolver class a javabean.  
http://en.wikipedia.org/wiki/JavaBean 

Author

Commented:
I have to post and run a servlet, a jsp and a quad class on a school  Tomcat server,  
I know I have information on the wrong pages but what goes where;
the jsp has all the INPUT AND OUPUT
the Quad class has the CALCULATIONS
the servlet has ?

Author

Commented:
I can not seem to avoid the servlet(we aren't required to but it is ok)  if I don't I can't seem to get the values from the jsp to the quad class and back again
Commented:
In your JSP, you can start coding like this.
<jsp:useBean id="myBean" class="com.mycompany.QuadraticSolver" />
<jsp:setProperty name="myBean" property="*" />   //this will set aaa,bbb, and ccc
<html>
<head>
<title>Quadratic Equation Solver</title>
</head>
<body>
<h1>Quadratic Equation Solver </h1>
<h2>
    Your Equation is: <br/><br/> ${myBean.aaa}x^2 + ${myBean.bbb}x + ${myBean.ccc}<br/>
</h2>  
Roots are  ${myBean.roots[0]} and ${myBean.roots[1]}

I changed the names of A,B and C to conform to javabean conventions. You can rename them to something better.This is just a rough start. We still have to validate the user inputs(that where JSTL will help).
Top Expert 2007

Commented:
Or you can leave everything pretty much as is, but move index.jsp out of the WEB-INF directory and up above into the webapp (at the same directory level as META-INF and WEB-INF, for example).

Then put an action into your JSP form to go to your servlet.

Author

Commented:
I am trying to get rid of the servlet, if I can.
I leave the input boxes in my jsp right?
Top Expert 2007
Commented:
rrz@871311 gave you some good links, above.  As well as the sample code for making a Java bean for your class.

If QuadraticSolver is a bean, then you manipulate data with it just as rrz@871311 suggested.

Are you having trouble with the concept of programming within a JSP page?  Conceptually, you do the following in your JSP page:

<%@ page directives
<%
[ code here pretty much identical to the code you have in your servlet ]
%>
<!DOCTYPE line and
[the rest of your HTML here]

In this case, action of your form is then the same jsp page.  Or you make 2 JSP pages, the first one as your input form, and the second one as the action of the form, which displays the results of applying QuadraticSolver to the input parameters from the first form.

You have to try the code to see how it fits together.

Author

Commented:
I am very confused as to where do I put my User Input on the jsp?
and then how do I access those values?

Author

Commented:
I mean how can I give the quad bean the value if I haven't gotten them yet?

Author

Commented:
Ok, I have changed sveral things,  I found a better solution for my bean calculations (I think) and I have tried to implement the changes you gave me on the jsp but I do not think I am following you exactly, I don't seem to get how I get the values.
When I run this it compiles but I get an error of:
type Status report

message /Project1/Quad

description The requested resource (/Project1/Quad) is not available.


THE JSP CODE
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="Quad" class="JavaBeans.Quad" />
<jsp:setProperty name="Quad" property="*" /> 
<html>
<head>
<title>Quadratic Equation Solver</title>
</head>
<body>
<h1>Quadratic Equation Solver </h1>
<h2>
    Your Equation is: <br/><br/> ${Quad.aaa}x^2 + ${Quad.bbb}x + ${Quad.ccc}<br/>

<br/><br/>Roots are  ${Quad.message}</h2> 

	 
       String A = request.getParameter("A").toString();
       String B = request.getParameter("B").toString();
       String C = request.getParameter("C").toString();
      
       double a = Double.parseDouble(A);
       double b = Double.parseDouble(B);
       double c = Double.parseDouble(C);
      

<FORM name="QuadForm" >
Quadratic Equation Solver for Equations in the form of
Ax^2 + Bx + C<BR>
<BR>
Enter the value of A: <INPUT type="text" name="A" size="15"><BR>
Enter the value of B: <INPUT type="text" name="B" size="15"><BR>
Enter the value of C: <INPUT type="text" name="C" size="15"><BR>
<br>
<input type=button value="Solve" >
<br>
<BR>
<BR>
</FORM>

</body>
</html>

THE BEAN CODE
package JavaBeans;


import static java.lang.StrictMath.*;

public class Quad {


	
	/**
	 * 
	 * 
	 * bean name="Quad"
	 *           
	 * The session context */
	      
	      private int aaa, bbb,ccc,ddd;
	      private int answer;
	      double sqrD;
	      private double discr1,discr2;
	      private String message;

	      public Quad() 
	      {
	            
	      }
	      
	      public void setValueA(String A)
	            throws Exception 
	      {
	            aaa = Integer.parseInt(A);                                    
	      }

	      public void setValueB(String B)
	      throws Exception 
	      {
	            bbb= Integer.parseInt(B);
	      }
	      
	      public void setValueC(String C)
	      throws Exception 
	      {
	            ccc = Integer.parseInt(C);
	      }
	      
	      public String getMessage()      
	      {
	            try{findRoots();}
	            catch(Exception e){
	            }
	            return message;
	      }
	      /*
	       * findRoots finds the discriminants and sets the String message which contains the answer to be returned
	       * to the user.
	       */
	      private void findRoots() throws Exception 
	      {
	            
	            if (aaa==0)
	            {
	                  if (bbb==0)
	                  {
	                        message ="There is no solution";
	                  }
	                  else if (bbb!=0)
	                  {
	                        answer = (-ccc)/bbb;
	                        message ="The Answer is " + answer;
	                  }
	                  
	            }
	            else 
	            {
	                  ddd = ((bbb*bbb)-(4*aaa*ccc));
	                  if (ddd==0)
	                  {
	                        answer = (-bbb)/(2*aaa);
	                        message = "The answer is "+answer;
	                  }
	                  else if (ddd > 0)
	                  {
	                        sqrD = Math.sqrt(ddd);
	                        discr1 = (-bbb+sqrD)/(2*aaa);
	                        discr2 = (-bbb-sqrD)/(2*aaa);
	                        message = "there are two possible answers "+discr1+" and "+discr2;
	                  }
	                  else if (ddd<0)
	                  {
	                        message ="There is no solution";
	                  }
	            }
	            
	      }

	}

Open in new window

Author

Commented:
I changed the line
<br/><br/>Roots are  ${Quad.message}</h2>
to
<br/><br/>Roots are  ${Quad.getMessage}</h2>
because that is the method name

I closed everything up and reloaded it and now I get this message:

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: /project1.jsp(15,23) The function getMessage must be used with a prefix when a default namespace is not specified
      org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
      org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
      org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148)
      org.apache.jasper.compiler.Validator$ValidateVisitor$1FVVisitor.visit(Validator.java:1480)
      org.apache.jasper.compiler.ELNode$Function.accept(ELNode.java:129)
      org.apache.jasper.compiler.ELNode$Nodes.visit(ELNode.java:200)
      org.apache.jasper.compiler.ELNode$Visitor.visit(ELNode.java:242)
      org.apache.jasper.compiler.ELNode$Root.accept(ELNode.java:56)
      org.apache.jasper.compiler.ELNode$Nodes.visit(ELNode.java:200)
      org.apache.jasper.compiler.Validator$ValidateVisitor.validateFunctions(Validator.java:1505)
      org.apache.jasper.compiler.Validator$ValidateVisitor.prepareExpression(Validator.java:1510)
      org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:726)
      org.apache.jasper.compiler.Node$ELExpression.accept(Node.java:940)
      org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
      org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2393)
      org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2399)
      org.apache.jasper.compiler.Node$Root.accept(Node.java:489)
      org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
      org.apache.jasper.compiler.Validator.validate(Validator.java:1739)
      org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:166)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:315)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
      org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Top Expert 2007

Commented:
To call methods, you must put Quad.getMessage()  .  If you don't put the parentheses, then it is not a method call.  It might help you to look through some Java tutorials.  The Sun tutorials are great, but they take a while.  I find RoseIndia.net to be a quick tutorial sometimes:
http://www.roseindia.net/jsp/

Author

Commented:
I am sorry, I did make that change and now I get an error of:
org.apache.jasper.JasperException: An exception occurred processing JSP page /project1.jsp at line 13

10: <body>
11: <h1>Quadratic Equation Solver </h1>
12: <h2>
13:     Your Equation is: <br/><br/> ${Quad.aaa}x^2 + ${Quad.bbb}x + ${Quad.ccc}<br/>
14:
15: <br/><br/>Roots are  ${Answer}</h2>
16:


Stacktrace:
      org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


root cause

Top Expert 2007

Commented:
Okay, if you see something like
Quad.aaa
then you know that your bean must have a field named aaa with getter and setter methods.  Which you don't.  You created get and set methods for fields named "A" "B" etc.  Those don't exist in your bean.  The way that beans work is with that naming convention, and if you don't follow it, the interpreters don't know what to do.  Again -- the links rrz@871311 you gave you for Java and beans would be helpful for you to follow.

You also might not have your environment configured to use EL which might be why you're not getting a better error message.  

What servlet engine are you using, and what version?  Is it Tomcat 6?  In which case your web.xml should have the declaration for the correct release of EL in order to interpret EL statements like "Quad.aaa".

Author

Commented:
I have added the getter and setter methods also just now,  but I stil get the same messeage.
exception

org.apache.jasper.JasperException: /project1.jsp(15,35) The function getA must be used with a prefix when a default namespace is not specified
      org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
      org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
      org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148)
      org.apache.jasper.compiler.Validator$ValidateVisitor$1FVVisitor.visit(Validator.java:1480)
      org.apache.jasper.compiler.ELNode$Function.accept(ELNode.java:129)
      org.apache.jasper.compiler.ELNode$Nodes.visit(ELNode.java:200)
      org.apache.jasper.compiler.ELNode$Visitor.visit(ELNode.java:242)
      org.apache.jasper.compiler.ELNode$Root.accept(ELNode.java:56)
      org.apache.jasper.compiler.ELNode$Nodes.visit(ELNode.java:200)
      org.apache.jasper.compiler.Validator$ValidateVisitor.validateFunctions(Validator.java:1505)
      org.apache.jasper.compiler.Validator$ValidateVisitor.prepareExpression(Validator.java:1510)
      org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:726)
      org.apache.jasper.compiler.Node$ELExpression.accept(Node.java:940)
      org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
      org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2393)
      org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2399)
      org.apache.jasper.compiler.Node$Root.accept(Node.java:489)
      org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343)
      org.apache.jasper.compiler.Validator.validate(Validator.java:1739)
      org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:166)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:315)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
      org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
      org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
      org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
      org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.18 logs.

Top Expert 2007

Commented:
Okay, it's good that you posted the full message.  You see how this time it says "The function getA must be used with a prefix when a default namespace is not specified" -- that's different from the previous exceptions you posted.

I don't know what you're calling, but if it thinks it should call something named A then you have to name the bean and call it with the bean name.  But you're not using conventional Java naming conventions, so you're hitting another problem (probably -- you need to post your changed JSP code, so I'm guessing here).

Read the JavaBean spec or tutorials -- they walk you through all of this, and more.

The convention for beans (as in all of Java programming, but it matters more for beans) is that field names start with a lowercase letter, as in rrz's example "aaa".  That will work for the get and set (although maybe a little odd-looking) because your get and set methods will be getAaa and setAaa .  The bean naming expects the first character in the field name to be lower case, which is the convention in Java programming, and it expects the method to have the first letter in the field name capitalized, while the rest stay as they are in the field name.  

You also should check your web.xml file and make sure that it references JSP 2.4 or above.  There should be a line something like this:
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

Author

Commented:
I do mean to seem sutpid but maybe that is the case, I have a 2 books sitting in front of me and All they show is snippets of this and that and I just can't figure out how to pull it together, My first run was much closer..at least I could see something on the screen.

I am now very very confused because one book says do this and the other says do that and then you say try this..  I have tried so many things my files do not even look like they are right to me and that says something... as apparently I am pretty dense!
I have renamed this and that so many times now I have multiple instances all over the place,  and eclipse or tomcat seems confused...I have really messed this up and I need to start over somehow, this just should not take me this long, I have a Good GPA and study very hard, but I do avoid any web stuff because it confuses me, somehow, but I would like to learn it, I am frustrated and confused.  (DEEP SIGH), could you walk me through step by step it doesnt even have to be my project, any one will do just so I am not so confused anymore?

Author

Commented:
I am trying to download an apache example but the thunder and lightning seem to be messing up the download as it is very very slow and keeps getting timed out.
Top Expert 2007

Commented:
EE is not a place to teach you how to program, but we help with problems you run into.

It is easy, when you're learning so many things, to get them mixed up.  Are you using textbooks for the class?  Which ones?  It might help us answer the questions if we know which ones you're taking your example from.

You're right, it's often helpful to start over.  You know more about programming now.

If I were you, I'd make a couple of JSP pages which do the basic Web programming that you're looking at for the example -- the input form and the result display.  It sounds as if you haven't done a lot of Web programming either, so there's a lot for you to learn.

Then, when you have 2 working JSP pages, you can take apart the pieces to make a bean and use EL.

JSP by itself is much easier than the full environment for beans and EL.  And it's much easier to debug than tag and bean errors (which is what you're getting).

Commented:
>could you walk me through step by step  
Yes, we will help.
I rewrote your latest code. Please cut and paste. It still needs work. But this should give you the next step. Please keep trying to improve it.
Keep us informed as to what you are doing. Post your code as you go. That way we can help you along the way.
Java really is fun. But we all have been through the headaches.
Your idea of using valueA as the name of the field in your is good. Later I will try to find the spec.
Your idea of create the String message was good. It allows you to keep that messy math in the bean(not in your JSP).  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="Quad" class="rrz.Quad" />
<jsp:setProperty name="Quad" property="*" /> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Quadratic Equation Solver</title>
</head>
<body>
<h1>Quadratic Equation Solver </h1>

<h2>
    Your Equation is: <br/><br/> ${Quad.valueA}x^2 + ${Quad.valueB}x + ${Quad.valueC}<br/>

<br/><br/>Roots are  ${Quad.message}</h2> 
<FORM name="QuadForm" >
Quadratic Equation Solver for Equations in the form of Ax^2 + Bx + C<BR/><BR/>
Enter the value of A: <INPUT type="text" name="valueA" size="15"><BR/>
Enter the value of B: <INPUT type="text" name="valueB" size="15"><BR/>
Enter the value of C: <INPUT type="text" name="valueC" size="15"><BR/>
<br/>
<input type="submit" value="Solve" >
<br/>
<BR/>
<BR/>
</FORM>
</body>
</html>
///////////////////////
package rrz;
public class Quad {
	      private String valueA, valueB, valueC;
	      private String message;
	      public Quad() 
	      {
	            
	      }
	      public void setValueA(String A)
	      {
	            valueA = A;                                    
	      }

	      public void setValueB(String B)
	      {
	            valueB = B;
	      }
	      
	      public void setValueC(String C) 
	      {
	            valueC = C;
	      }
	      public String getValueA(){
                     return valueA;
              }
	      public String getValueB(){
                     return valueB;
              }
	      public String getValueC(){
                     return valueC;
              }
	      public String getMessage()      
	      {
	            try{findRoots();}
	            catch(Exception e){
	                               message = "There was a problem finding roots."; 
	            }
                    return message;
	      }
	      /*
	       * findRoots finds the discriminants and sets the String message which contains the answer to be returned
	       * to the user.
	       */
	      private void findRoots() throws Exception 
	      {
	            double a = Double.parseDouble(valueA);
	            double b = Double.parseDouble(valueB);
	            double c = Double.parseDouble(valueC);
	            if ( a == 0)
	            {
	                  if (b == 0)
	                  {
	                        message ="There is no solution";
	                  }
	                  else if (b != 0)
	                  {
	                        message ="The Answer is " + (-c)/b;
	                  }   
	            }
	            else 
	            {
	                  double d = ((b * b) - (4 * a * c));
	                  if (d == 0)
	                  {
	                        message = "The answer is " + (-b)/(2 * a);
	                  }
	                  else if (d > 0)
	                  {
	                        double sqrD = Math.sqrt(d);
	                        double discr1 = (-b+sqrD)/(2*a);
	                        double discr2 = (-b-sqrD)/(2*a);
	                        message = "there are two possible answers "+discr1+" and "+discr2;
	                  }
	                  else if (d < 0)
	                  {
	                        message ="There is no solution";
	                  }
	            }
	            
	      }

	}

Open in new window

Author

Commented:
I had to reload eclipse because it got all fouled up, I don't know if it was the thunder and lightning causing the power surges we had or if I messed it up by trying to start over so many times,  so before I do this again the jsp goes in my WEB-INF folder and the Quad class goes in my JAVABEANS PACKAGE, correct?

Commented:
>so before I do this again the jsp goes in my WEB-INF folder and the Quad class goes in my JAVABEANS PACKAGE, correct?
No.  mrcoffee told you above here.
Your JSP files goes into your web folder.
Your bean goes into your package folder structure inside your src folder.

I quote the javabean spec below mrcoffee's solution at  
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/JSTL_Tags/Q_22416566.html 
Remember that one, mrcoffee ?

Author

Commented:
It will not compile, I t doesn't like the line
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
can't I donwload this somewhere?

Commented:
You  can take that line out for now. We didn't use JSTL yet.
Yes, need the two jars,  jstl.jar and the standard.jar  
from  
http://tomcat.apache.org/taglibs/standard/ 
get JSTL 1.1

Author

Commented:
Yay! it works better now,
I knew the use bean was not in the right place! that was the biggest change.  I thought I asked that question earlier but I did not understand your answer enough , well I shall have to ask clearer questions from now on, I am sorry for my confusion, but as they say "Women are from Venus and men are from Mars!
I did not think I had to parse again because I am parsing in the Quad class, but I could not figure out how to get the data back and forth,
you can be sure that
Your Equation is: <br/><br/> ${Quad.valueA}x^2 + ${Quad.valueB}x + ${Quad.valueC}<br/>
<br/> ${Quad.message}</h2>
is not a line I will forget again,  it has been nearly 10 years since I did any html, I have avaided this class till now, but I only have two programming classes to take and they both deal with either UNIX or WebApps.
Ok..Deep Sigh..I know there is more to do,  how do I implement EL?  I don't have any  "scripting elements"

Author

Commented:
I was going to use a javascript until I figured out that I can't  so this was tough for me.

Commented:
>how do I implement EL?  
What are you asking ?  
Didn't  ${Quad.valueA}  print out the value ?  
If your not clear on the subject look at  
http://java.sun.com/javaee/5/docs/tutorial/doc/bnahq.html
>I don't have any  "scripting elements"  
You don't want any do you ?

Author

Commented:
@rrz,
Thank-you I will take a long look at it tommorow.  You and MrCoffee must be very tired of me because me is tired too! ;)  Thank-you for your help
@MrCoffee, Thank-you for your help also!  When you said:
Are you having trouble with the concept of programming within a JSP page?  Conceptually, you do the following in your JSP page:

<%@ page directives
<%
[ code here pretty much identical to the code you have in your servlet ]
%>
<!DOCTYPE line and
[the rest of your HTML here]
You were so right and I just mis-understood what you wanted me to do, I should have clarified it before going any further.  Thanks again.

I feel it is a good idea for me to split the point between you, this will be ok, yes?
Top Expert 2007

Commented:
Great -- it sounds as if you have gotten much more of your code to work.  Splitting points is perfectly fine.  I'm glad you kept with it.

>I don't have any  "scripting elements"  
I think your teacher means that the JSP shouldn't have direct Java code -- they want you to put as much as possible of the actual Java code in the bean.  Then they want you to reference the bean with syntax like ${Quad.valueA} .  Which you appear to be doing.

I think it's easier to start with Java code in the JSP page, then figure out how to put it into the bean once you have the page working.

Once you understand beans, though, you can skip the beginning stage and develop the bean and the JSP the way you want.

In the JSP code you have posted, you still don't have the action defined for your form.  I don't think your page will work until you do that.  You have to put something in, like

<FORM name="QuadForm"  method="POST" action="myquadpage.jsp">

The action url is the results JSP page.