Servlets - Factorial Calculation

FormFact.html

<!-- Servlet, form data and validation -->

 

<html>

<head>

         <title> Forms, servlet and factorial</title>

         <style>

                  h3{text-align:center}

         </style>

         <script type="text/javascript" language="javascript">

 

                  function fnvalidate()

                  {

                           // User Name Validation

                           var Num = document.FN.f1.value;

                           if (Num.toString().trim().length==0)

                           {

                                    alert( "Error...Enter number" );

                                    document.FN.f1.focus() ;

                                    return false;

                           }

                          

            if( isNaN(Num))

            {                  

                                    alert( "Invalid Number! Should have only digits." );

                                    document.FN.f1.focus() ;

                                    return false;

                           }

                            

                           return true;

                  }

         </script>                

</head>

<body>

         <br/><h3> Factorial Calculator </h3><br/><br/>

         <center>

         <form name="FN" method="get" action="http://localhost:8088/WT/FactCalc" onsubmit="return fnvalidate();">

        

                  <label> Enter Number : </label>

                  <input type="text" name="f1" />

                  <br/><br/>

                  <input type="submit" />

                  <input type="reset" />

                 

         </form>

</html>                         

 

 


 

FactCalc.java

 

import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*;

 

public class FactCalc extends HttpServlet

{

         int N;

         public void init(ServletConfig sc)

         {

         }

        

         public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

         {

                  res.setContentType("text/html");

                  PrintWriter pw = res.getWriter();

                                   

                  N = Integer.parseInt(req.getParameter("f1"));

                  int fact=1;

                  for(int i=1;i<=N;i++)

                           fact=fact*i;

                 

                  pw.println("<html><body><center>");

                  pw.println("<h3>");

                  pw.println("Factorial of "+N +" is "+fact);         

                  pw.println("</h3>");

                  pw.println("</center></body></html>");

                                   

                  pw.close();

         }

        

         public void destroy()

         {

         }

}


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu